public function Checkout::capturePayment in Commerce PayPal 8
Captures the given authorized payment.
Only payments in the 'authorization' state can be captured.
Parameters
\Drupal\commerce_payment\Entity\PaymentInterface $payment: The payment to capture.
\Drupal\commerce_price\Price $amount: The amount to capture. If NULL, defaults to the entire payment amount.
Throws
\Drupal\commerce_payment\Exception\PaymentGatewayException Thrown when the transaction fails for any reason.
Overrides SupportsAuthorizationsInterface::capturePayment
File
- src/
Plugin/ Commerce/ PaymentGateway/ Checkout.php, line 504
Class
- Checkout
- Provides the PayPal Checkout payment gateway.
Namespace
Drupal\commerce_paypal\Plugin\Commerce\PaymentGatewayCode
public function capturePayment(PaymentInterface $payment, Price $amount = NULL) {
$this
->assertPaymentState($payment, [
'authorization',
]);
// If not specified, capture the entire amount.
$amount = $amount ?: $payment
->getAmount();
$remote_id = $payment
->getRemoteId();
$params = [
'amount' => [
'value' => Calculator::trim($amount
->getNumber()),
'currency_code' => $amount
->getCurrencyCode(),
],
];
if ($amount
->equals($payment
->getAmount())) {
$params['final_capture'] = TRUE;
}
try {
$sdk = $this->checkoutSdkFactory
->get($this->configuration);
// If the payment was authorized more than 3 days ago, attempt to
// reauthorize it.
if ($this->time
->getRequestTime() >= $payment
->getAuthorizedTime() + 86400 * 3 && !$payment
->isExpired()) {
$sdk
->reAuthorizePayment($remote_id, [
'amount' => $params['amount'],
]);
}
$response = $sdk
->capturePayment($remote_id, $params);
$response = Json::decode($response
->getBody()
->getContents());
} catch (BadResponseException $exception) {
$this->logger
->error($exception
->getResponse()
->getBody()
->getContents());
throw new PaymentGatewayException('An error occurred while capturing the authorized payment.');
}
$remote_state = strtolower($response['status']);
$state = $this
->mapPaymentState('capture', $remote_state);
if (!$state) {
throw new PaymentGatewayException('Unhandled payment state.');
}
$payment
->setState('completed');
$payment
->setAmount($amount);
$payment
->setRemoteId($response['id']);
$payment
->setRemoteState($remote_state);
$payment
->save();
}