クラス
Update
ソース ソース
ファイル: src/API/CheckoutSession/Update.php
class Update extends ErrorStore
{
// Errors
const RESOURCE_NOT_FOUND = 'ResourceNotFound';
const INVALID_CHECKOUT_SESSION_STATUS = 'InvalidCheckoutSessionStatus';
// Constraints
const CONSTRAINT_CHECKOUT_RESULT_RETURN_URL_NOT_SET = 'CheckoutResultReturnUrlNotSet';
const CONSTRAINT_CHARGE_AMOUNT_NOT_SET = 'ChargeAmountNotSet';
const CONSTRAINT_PAYMENT_INTENT_NOT_SET = 'PaymentIntentNotSet';
const CONSTRAINT_BUYER_NOT_ASSOCIATED = 'BuyerNotAssociated';
/**
* AmazonPay module object
*
* @var AmazonPay
*/
private $module;
/**
* Amazon checkout `paymentIntent`
*
* `Authorize`, `AuthorizeWithCapture` or `Confirm`
*
* @var string
*/
private $paymentIntent;
/**
* True for asynchronous processing. False otherwise
*
* @var bool
*/
private $canHandlePendingAuthorization;
/**
* Redirect URL for checkout result page
*
* @var string
*/
private $checkoutResultUrl;
/**
* The type of Amazon Pay settlement.
*
* Should be `payonly` or `payandship`
*
* This variable is used for conditionally firing hooks
* relative to the settlement type.
*
* @var string
*/
private $settlementType;
/**
* PaymentIntent option
*
* @var string
*/
public static $authorizeWithCapture = 'AuthorizeWithCapture';
/**
* PaymentIntent option
*
* @var string
*/
public static $authorize = 'Authorize';
/**
* PaymentIntent option
*
* @var string
*/
public static $confirm = 'Confirm';
/**
* Sets `$module` member var with dependency injection.
*
* @author Evan D Shaw <evandanielshaw@gmail.com>
* @param AmazonPay $module
* @param string $checkoutResultUrl
* @param bool $canHandlePendingAuthorization Default: `false`
* @param string $paymentIntent `Authorize`, `AuthorizeWithCapture`, or `Confirm`. `Authorize` by default
* @return void
* @throws InvalidArgumentException Thrown if paymentIntent is `AuthorizeWithCapture` when
* canHandlePendingAuthorization is `true`.
*/
public function __construct(
AmazonPay $module,
$checkoutResultUrl,
$canHandlePendingAuthorization = false,
$paymentIntent = 'Authorize'
) {
if ($canHandlePendingAuthorization === true && $paymentIntent === 'AuthorizeWithCapture') {
throw new InvalidArgumentException(
"paymentIntent cannot be 'AuthorizeWithCapture' when canHandlePendingAuthorization is true"
);
}
$this->module = $module;
$this->checkoutResultUrl = $checkoutResultUrl;
$this->canHandlePendingAuthorization = $canHandlePendingAuthorization;
$this->paymentIntent = $paymentIntent;
parent::__construct();
$this->populate();
}
/**
* Updates a checkout session
*
* @see https://amazonpaycheckoutintegrationguide.s3.amazonaws.com/amazon-pay-api-v2/checkout-session.html#update-checkout-session
* @author Evan D Shaw <evandanielshaw@gmail.com>
* @param array $args {
* URL params
*
* @type int $id Checkout Session ID
* }
* @return array
* @throws InvalidArgumentException Thrown by `getAmazonClient`.
*/
public function patch(array $args) {
$formExtras = !empty($_POST['formExtras']) ? $_POST['formExtras'] : [];
/**
* Fires **before** calling Amazon Pay's `Update Checkout Session` API
*
* @param array $formExtras
* @param array $args See {@see \Aivec\Welcart\SettlementModules\AmazonPay\API\CheckoutSession\Update::patch()}
* @param string $settlementType `payonly` or `payandship`
* @param string $paymentIntent `Authorize`, `AuthorizeWithCapture` or `Confirm`
*/
do_action(
'wcexaap_on_before_update_checkout_session',
$formExtras,
$args,
$this->settlementType,
$this->paymentIntent
);
if (!empty($this->settlementType)) {
/**
* Fires **before** calling Amazon Pay's `Update Checkout Session` API
*
* @param array $formExtras
* @param array $args See {@see \Aivec\Welcart\SettlementModules\AmazonPay\API\CheckoutSession\Update::patch()}
* @param string $settlementType `payonly` or `payandship`
* @param string $paymentIntent `Authorize`, `AuthorizeWithCapture` or `Confirm`
*/
do_action(
"wcexaap_on_before_update_checkout_session_{$this->settlementType}",
$formExtras,
$args,
$this->settlementType,
$this->paymentIntent
);
}
$id = $args['id'];
$order = (new API\WelcartEntries())->getOrder();
$payload = [
'webCheckoutDetails' => [
'checkoutResultReturnUrl' => $this->checkoutResultUrl,
],
'paymentDetails' => [
'paymentIntent' => $this->paymentIntent,
'canHandlePendingAuthorization' => $this->canHandlePendingAuthorization,
'chargeAmount' => [
'amount' => $order['total_full_price'],
'currencyCode' => usces_crcode('return'),
],
],
'platformId' => Constants::PLATFORM_ID,
];
$headers = (new SandboxSimulation($this->module))->updateCheckoutSessionSetSimCodeIfSandbox();
try {
$client = $this->module->getAmazonClient();
$result = $client->updateCheckoutSession($id, $payload, $headers);
if ($this->module->errors->hasError($result)) {
return $this->module->errors->getAmzErrorResponse($result, $this);
}
if ($this->hasConstraints($result)) {
return $this->getConstraintsResponse($result);
}
} catch (\Exception $e) {
return $this->module->errors->getErrorResponse(
GenericErrorStore::AMAZON_PAY_SDK_CLIENT_EXCEPTION,
[$e->getMessage()]
);
}
/**
* Fires **after** calling Amazon Pay's `Update Checkout Session` API
*
* This hook will not be called if an error occured
*
* @param array $result
* @param array $formExtras
* @param array $args See {@see \Aivec\Welcart\SettlementModules\AmazonPay\API\CheckoutSession\Update::patch()}
* @param string $settlementType `payonly` or `payandship`
* @param string $paymentIntent `Authorize`, `AuthorizeWithCapture` or `Confirm`
*/
do_action(
'wcexaap_on_after_update_checkout_session',
$result,
$formExtras,
$args,
$this->settlementType,
$this->paymentIntent
);
if (!empty($this->settlementType)) {
/**
* Fires **after** calling Amazon Pay's `Update Checkout Session` API
*
* This hook will not be called if an error occured
*
* @param array $result
* @param array $formExtras
* @param array $args See {@see \Aivec\Welcart\SettlementModules\AmazonPay\API\CheckoutSession\Update::patch()}
* @param string $settlementType `payonly` or `payandship`
* @param string $paymentIntent `Authorize`, `AuthorizeWithCapture` or `Confirm`
*/
do_action(
"wcexaap_on_after_update_checkout_session_{$this->settlementType}",
$result,
$formExtras,
$args,
$this->settlementType,
$this->paymentIntent
);
}
return $result;
}
/**
* Parses update result and returns true if any constraints exist
*
* @author Evan D Shaw <evandanielshaw@gmail.com>
* @param array $result
* @return bool
*/
public function hasConstraints(array $result) {
$body = json_decode($result['response'], true);
if (isset($body['constraints']) && count($body['constraints']) > 0) {
return true;
}
return false;
}
/**
* Returns `AmazonGenericError` object created from response constraints
*
* @author Evan D Shaw <evandanielshaw@gmail.com>
* @param array $result
* @return AmazonGenericError
*/
public function getConstraintsResponse(array $result) {
$body = json_decode($result['response'], true);
$constraint = $body['constraints'][0];
$genericerr = $this->getErrorResponse($constraint['constraintId'], [$constraint['description']]);
return new AmazonGenericError(
$genericerr->errorcode,
$genericerr->errorname,
$genericerr->httpcode,
$genericerr->debugmsg,
$genericerr->message,
$genericerr->adminmsg,
$genericerr->logger,
$result
);
}
/**
* Setter for `settlementType` member variable.
*
* @author Evan D Shaw <evandanielshaw@gmail.com>
* @param string $type Should be either `payonly` or `payandship`
* @return void
*/
public function setSettlementType($type) {
$this->settlementType = $type;
}
/**
* Populates error store
*
* @see https://amazonpaycheckoutintegrationguide.s3.amazonaws.com/amazon-pay-api-v2/checkout-session.html#error-codes-2
* @author Evan D Shaw <evandanielshaw@gmail.com>
* @return void
* @throws InvalidArgumentException Thrown if duplicate errorcodes exist.
*/
public function populate() {
$defaultErrors = $this->getErrorCodeMap();
$defaultErrorMessage = $defaultErrors[parent::INTERNAL_SERVER_ERROR]->message;
$actingLogger = new ActingLogger($this->module);
$this->addError(new GenericError(
self::RESOURCE_NOT_FOUND,
$this->getConstantNameByValue(self::RESOURCE_NOT_FOUND),
404,
function ($message) {
return $message;
},
__('Youre checkout session has expired or is not available', 'wcexaap')
));
$this->addError((new GenericError(
self::INVALID_CHECKOUT_SESSION_STATUS,
$this->getConstantNameByValue(self::INVALID_CHECKOUT_SESSION_STATUS),
422,
function ($message) {
return $message;
},
__('Illegal operation. Please try again.', 'wcexaap')
))->setLogger($actingLogger));
$this->addError((new GenericError(
self::CONSTRAINT_CHECKOUT_RESULT_RETURN_URL_NOT_SET,
$this->getConstantNameByValue(self::CONSTRAINT_CHECKOUT_RESULT_RETURN_URL_NOT_SET),
400,
function ($message) {
return $message;
},
$defaultErrorMessage
))->setLogger($actingLogger));
$this->addError((new GenericError(
self::CONSTRAINT_CHARGE_AMOUNT_NOT_SET,
$this->getConstantNameByValue(self::CONSTRAINT_CHARGE_AMOUNT_NOT_SET),
400,
function ($message) {
return $message;
},
$defaultErrorMessage
))->setLogger($actingLogger));
$this->addError((new GenericError(
self::CONSTRAINT_PAYMENT_INTENT_NOT_SET,
$this->getConstantNameByValue(self::CONSTRAINT_PAYMENT_INTENT_NOT_SET),
400,
function ($message) {
return $message;
},
$defaultErrorMessage
))->setLogger($actingLogger));
$this->addError((new GenericError(
self::CONSTRAINT_BUYER_NOT_ASSOCIATED,
$this->getConstantNameByValue(self::CONSTRAINT_BUYER_NOT_ASSOCIATED),
400,
function ($message) {
return $message;
},
__('Please select your preferred payment method and shipping address to complete the purchase.', 'wcexaap')
))->setLogger($actingLogger));
}
}
- __construct — Sets `$module` member var with dependency injection.
- getConstraintsResponse — Returns `AmazonGenericError` object created from response constraints
- hasConstraints — Parses update result and returns true if any constraints exist
- patch — Updates a checkout session
- populate — Populates error store
- setSettlementType — Setter for `settlementType` member variable.