Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refund: basic refund implemented #10

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 67 additions & 7 deletions Model/Payment.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Psr\Log\LoggerInterface;
use Magento\Quote\Api\Data\PaymentInterface;
use Aligent\Pinpay\Helper\Pinpay as PinHelper;
use Magento;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't look like it belongs here, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@moloughlin it is here so we don't need to access root namespace \Magento which PhpStorm shows as a warning


/**
*
Expand All @@ -37,6 +38,8 @@ class Payment implements MethodInterface

const REQUEST_TYPE_CAPTURE_ONLY = 'CAPTURE_ONLY';

const REQUEST_TYPE_REFUND = 'REFUND';

/**
* @var string
*/
Expand Down Expand Up @@ -186,8 +189,7 @@ public function canCaptureOnce()
*/
public function canRefund()
{
// TODO: Implement canRefund() method.
return false;
return true;
}

/**
Expand Down Expand Up @@ -354,6 +356,10 @@ public function getClient($payment, $order, $amount, $transactionType = self::RE
$endpoint .= '/' . $payment->getCcTransId() . '/capture';
$method = \Zend_Http_Client::PUT;
}
elseif ($transactionType == static::REQUEST_TYPE_REFUND){
$endpoint .= '/' . $payment->getData('refund_transaction_id') . '/refunds';
$method = \Zend_Http_Client::POST;
}

$client->setAuth($this->getConfigData('secret_key', $order->getStoreId()));
$client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
Expand All @@ -366,7 +372,11 @@ public function getClient($payment, $order, $amount, $transactionType = self::RE
*/
if ($transactionType === self::REQUEST_TYPE_CAPTURE_ONLY) {
$data = ['amount' => $this->_pinHelper->getRequestAmount($order->getBaseCurrencyCode(), $amount)];
} else {
}
elseif ($transactionType === self::REQUEST_TYPE_REFUND){
$data = ['amount' => $this->_pinHelper->getRequestAmount($order->getBaseCurrencyCode(), $amount)];
}
else {
$capture = $transactionType === self::REQUEST_TYPE_AUTH_CAPTURE;
$data = $this->_buildAuthRequest($order, $payment, $amount, $capture);
}
Expand Down Expand Up @@ -461,6 +471,11 @@ protected function _handleResponse($response, $payment)
} elseif ($error) {
throw new LocalizedException(__($result->getErrorDescription()));
}
//success is set to null in response but approved (like in pending credit memo)
elseif($result->isApproved()){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we just roll this up with the if to avoid repetition?
if ($result->isSuccess() || $result->isApproved()) {...}

A bit confused by the comment as well, does the refund response just have a slightly different structure to the capture response?

Copy link
Contributor Author

@zainengineer zainengineer May 24, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@moloughlin yes refund response seem to be slightly different
here is the response from curl request (formatted JSON for readibility)

  "response": {
    "token": "rf_removed_for_security",
    "success": null,
    "amount": 10,
    "currency": "AUD",
    "charge": "ch_removed_for_security",
    "created_at": "2018-05-24T02:52:34Z",
    "error_message": null,
    "status_message": "Pending"
  }
}

so success, so isset returns false and function returns false for isSuccess returns false
And there is no error_message either
HTTP response code is 201 which pinpay for successful.

What makes this confusing is JSON success is different to response code 201 which is another kind of Success.

Copy link
Contributor Author

@zainengineer zainengineer May 24, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a second look in our modules, both magento1 and magento2

const HTTP_RESPONSE_CODE_APPROVED = 201;

and https://github.com/aligent/PINpayments/blob/48fd120be7c530a3e69c6bbbd060878e0835a305/app/code/local/Dwyera/Pinpay/Model/Result.php#L13
we call it Approved
HTTP_RESPONSE_CODE_APPROVED

but in API its referred to as https://pinpayments.com/developers/api-reference/cards
Created

According to API documentation overview/errors section:
https://pinpayments.com/developers/api-reference
If an API request results in an error, a non-2xx status code will be returned, along with a JSON object containing error and error_description keys.

So not sure how should we treat absence of success (or null) in response.
A bit nervous to touch capture/authorize code which is already working.

$payment->setCcTransId($result->getToken());
$payment->setTransactionId($result->getToken());
}
}

/**
Expand Down Expand Up @@ -488,13 +503,58 @@ protected function _buildAuthRequest($order, $payment, $amount, $capture = true)
'capture' => $capture
];
}

/**
* @inheritDoc
*/
public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
public function refund(Magento\Payment\Model\InfoInterface $payment, $amount)
{
// TODO: Implement refund() method.
if ($amount <= 0) {
$this->_logger->error('Expected amount for transaction is zero or below');
throw new LocalizedException(__("Invalid payment amount."));
}
/**
* @var $payment Magento\Sales\Api\Data\OrderPaymentInterface
*/
if (!($payment instanceof Magento\Sales\Api\Data\OrderPaymentInterface)){
throw new LocalizedException(__("refund payment needs to be instance of Magento\Sales\Api\Data\OrderPaymentInterface"));
}
if (!$this->canRefund()) {
throw new LocalizedException (__('Refund action is not available.'));
}
/* Rounding error may occur, checking if the differences is not less than 0.5c */
if ($amount - $payment->getAmountPaid() - $payment->getAmountRefunded() >= 0.005) {
throw new LocalizedException(__("Invalid refund amount"));
}

$order = null;
$online = null;
if ($payment instanceof Magento\Sales\Model\Order\Payment){
$order = $payment->getOrder();
$creditMemo = $payment->getCreditmemo();
if ($creditMemo){
$online = $creditMemo->getDoTransaction();
}
}
$online = is_null($online) ? !$this->isOffline() : $online;
if (!$online) {
$payment->setCcTransId($payment->getAdditionalInformation('reference_number'));
$payment->setTransactionId($payment->getAdditionalInformation('reference_number'));
}
//online transaction
else {
$transactionType = self::REQUEST_TYPE_REFUND;
$client = $this->getClient($payment, $order, $amount, $transactionType);

$response = null;
try {
$response = $client->request();
$this->_handleResponse($response, $payment);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it correct to be updating the Payment object in the refund case? I'd have thought this should hold onto the original transaction data instead, but maybe this pattern is standard elsewhere?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here is the example of magneto core DirectPost refund
magento/vendor/magento/module-authorizenet/Model/Directpost.php:403

        $payment->setAmount($amount);
        $payment->setXTransId($this->getRealParentTransactionId($payment));```
in other places too it is changing payment object in refund

} catch (\Exception $e) {
$this->_logger->error("Payment Error: " . $e->getMessage());
throw new LocalizedException(__($e->getMessage()));
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function should return $this to adhere to interface spec.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will make this change

//required by interface
return $this;
}

Expand Down Expand Up @@ -618,4 +678,4 @@ public function getPaymentUrl($storeId = 0)
return $isTest ? self::TEST_GATEWAY_URL : self::GATEWAY_URL;
}

}
}
7 changes: 6 additions & 1 deletion Model/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ public function getToken()
return '';
}


public function isApproved()
{
return $this->_responseCode === static::HTTP_RESPONSE_CODE_APPROVED;
}
/**
* @return string | null
*/
Expand All @@ -81,7 +86,7 @@ public function getCCType()
*
* @return mixed
*/
protected function getResponseValue($vKey)
public function getResponseValue($vKey)
{
if (!isset($this->_response) || (!isset($this->_response->response)) || (!isset($this->_response->response->$vKey))){
return null;
Expand Down