From a1548b7e3da2cd0575383ea6e0fd8dfc1e5932f0 Mon Sep 17 00:00:00 2001 From: Elliott Eggleston Date: Wed, 9 Aug 2017 19:24:13 -0400 Subject: [PATCH] Make whitespace consistent To make future diffs cleaner. Also inserts explicit braces around oneline if statements. --- AmazonPay/Client.php | 441 ++++++++++++++++-------------- AmazonPay/HttpCurl.php | 13 +- AmazonPay/HttpCurlInterface.php | 16 +- AmazonPay/IpnHandler.php | 95 ++++--- AmazonPay/IpnHandlerInterface.php | 8 +- AmazonPay/Regions.php | 32 ++- AmazonPay/ResponseInterface.php | 18 +- AmazonPay/ResponseParser.php | 80 +++--- tst/unit/ClientTest.php | 252 ++++++++--------- tst/unit/IpnHandlerTest.php | 94 +++---- tst/unit/Signature.php | 90 +++--- 11 files changed, 591 insertions(+), 548 deletions(-) diff --git a/AmazonPay/Client.php b/AmazonPay/Client.php index 5169a7e..51c50c6 100644 --- a/AmazonPay/Client.php +++ b/AmazonPay/Client.php @@ -12,12 +12,13 @@ require_once 'ClientInterface.php'; require_once 'Regions.php'; if (!interface_exists('\Psr\Log\LoggerAwareInterface')) { - require_once(__DIR__.'/../Psr/Log/LoggerAwareInterface.php'); + require_once(__DIR__ . '/../Psr/Log/LoggerAwareInterface.php'); } if (!interface_exists('\Psr\Log\LoggerInterface')) { - require_once(__DIR__.'/../Psr/Log/LoggerInterface.php'); + require_once(__DIR__ . '/../Psr/Log/LoggerInterface.php'); } + use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; @@ -34,25 +35,25 @@ class Client implements ClientInterface, LoggerAwareInterface private $mwsEndpointUrl = null; private $profileEndpoint = null; private $config = array( - 'merchant_id' => null, - 'secret_key' => null, - 'access_key' => null, - 'region' => null, - 'currency_code' => null, - 'sandbox' => false, - 'platform_id' => null, - 'cabundle_file' => null, - 'application_name' => null, - 'application_version' => null, - 'proxy_host' => null, - 'proxy_port' => -1, - 'proxy_username' => null, - 'proxy_password' => null, - 'client_id' => null, - 'app_id' => null, - 'handle_throttle' => true, - 'override_service_url' => null - ); + 'merchant_id' => null, + 'secret_key' => null, + 'access_key' => null, + 'region' => null, + 'currency_code' => null, + 'sandbox' => false, + 'platform_id' => null, + 'cabundle_file' => null, + 'application_name' => null, + 'application_version' => null, + 'proxy_host' => null, + 'proxy_port' => -1, + 'proxy_username' => null, + 'proxy_password' => null, + 'client_id' => null, + 'app_id' => null, + 'handle_throttle' => true, + 'override_service_url' => null + ); private $modePath = null; @@ -68,11 +69,11 @@ class Client implements ClientInterface, LoggerAwareInterface // Boolean variable to check if the API call was a success public $success = false; - /* Takes user configuration array from the user as input * Takes JSON file path with configuration information as input * Validates the user configuration array against existing config array */ + public function __construct($config = null) { $this->getRegionUrls(); @@ -100,21 +101,22 @@ public function __construct($config = null) } } - - public function setLogger(LoggerInterface $logger = null) { + public function setLogger(LoggerInterface $logger = null) + { $this->logger = $logger; } - /* Helper function to log data within the Client */ - private function logMessage($message) { + + private function logMessage($message) + { if ($this->logger) { $this->logger->debug($message); } } - /* Get the Region specific properties from the Regions class.*/ + private function getRegionUrls() { $regionObject = new Regions(); @@ -123,12 +125,12 @@ private function getRegionUrls() $this->profileEndpointUrls = $regionObject->profileEndpointUrls; } - /* checkIfFileExists - check if the JSON file exists in the path provided */ + private function checkIfFileExists($config) { if (file_exists($config)) { - $jsonString = file_get_contents($config); + $jsonString = file_get_contents($config); $configArray = json_decode($jsonString, true); $jsonError = json_last_error(); @@ -138,17 +140,17 @@ private function checkIfFileExists($config) throw new \Exception($errorMsg); } } else { - $errorMsg ='$config is not a Json File path or the Json File was not found in the path provided'; + $errorMsg = '$config is not a Json File path or the Json File was not found in the path provided'; throw new \Exception($errorMsg); } return $configArray; } - /* Checks if the keys of the input configuration matches the keys in the config array * if they match the values are taken else throws exception * strict case match is not performed */ + private function checkConfigKeys($config) { $config = array_change_key_case($config, CASE_LOWER); @@ -164,13 +166,13 @@ private function checkConfigKeys($config) } } - /* Convert a json error code to a descriptive error message * * @param int $jsonError message code * * @return string error message */ + private function getErrorMessageForJsonError($jsonError) { switch ($jsonError) { @@ -192,10 +194,10 @@ private function getErrorMessageForJsonError($jsonError) } } - /* Setter for sandbox * Sets the Boolean value for config['sandbox'] variable */ + public function setSandbox($value) { if (is_bool($value)) { @@ -205,10 +207,10 @@ public function setSandbox($value) } } - /* Setter for config['client_id'] * Sets the value for config['client_id'] variable */ + public function setClientId($value) { if (!empty($value)) { @@ -218,10 +220,10 @@ public function setClientId($value) } } - /* Setter for config['app_id'] * Sets the value for config['app_id'] variable */ + public function setAppId($value) { if (!empty($value)) { @@ -231,7 +233,6 @@ public function setAppId($value) } } - /* Setter for Proxy * input $proxy [array] * @param $proxy['proxy_user_host'] - hostname for the proxy @@ -239,34 +240,39 @@ public function setAppId($value) * @param $proxy['proxy_user_name'] - if your proxy required a username * @param $proxy['proxy_user_password'] - if your proxy required a password */ + public function setProxy($proxy) { - if (!empty($proxy['proxy_user_host'])) + if (!empty($proxy['proxy_user_host'])) { $this->config['proxy_host'] = $proxy['proxy_user_host']; + } - if (!empty($proxy['proxy_user_port'])) + if (!empty($proxy['proxy_user_port'])) { $this->config['proxy_port'] = $proxy['proxy_user_port']; + } - if (!empty($proxy['proxy_user_name'])) + if (!empty($proxy['proxy_user_name'])) { $this->config['proxy_username'] = $proxy['proxy_user_name']; + } - if (!empty($proxy['proxy_user_password'])) + if (!empty($proxy['proxy_user_password'])) { $this->config['proxy_password'] = $proxy['proxy_user_password']; + } } - /* Setter for $mwsServiceUrl * Set the URL to which the post request has to be made for unit testing */ + public function setMwsServiceUrl($url) { $this->mwsServiceUrl = $url; } - /* Getter * Gets the value for the key if the key exists in config */ + public function __get($name) { if (array_key_exists(strtolower($name), $this->config)) { @@ -276,17 +282,17 @@ public function __get($name) } } - /* Getter for parameters string * Gets the value for the parameters string for unit testing */ + public function getParameters() { return trim($this->parameters); } - /* Trim the input Array key values */ + private function trimArray($array) { foreach ($array as $key => $value) { @@ -299,12 +305,12 @@ private function trimArray($array) return $array; } - /* GetUserInfo convenience function - Returns user's profile information from Amazon using the access token returned by the Button widget. * * @see http://login.amazon.com/website Step 4 * @param $accessToken [String] */ + public function getUserInfo($accessToken) { // Get the correct Profile Endpoint URL based off the country/region provided in the config['region'] @@ -316,12 +322,12 @@ public function getUserInfo($accessToken) // To make sure double encoding doesn't occur decode first and encode again. $accessToken = urldecode($accessToken); - $url = $this->profileEndpoint . '/auth/o2/tokeninfo?access_token=' . $this->urlEncode($accessToken); + $url = $this->profileEndpoint . '/auth/o2/tokeninfo?access_token=' . $this->urlEncode($accessToken); $httpCurlRequest = new HttpCurl($this->config); $response = $httpCurlRequest->httpGet($url); - $data = json_decode($response); + $data = json_decode($response); // Ensure that the Access Token matches either the supplied Client ID *or* the supplied App ID // Web apps and Mobile apps will have different Client ID's but App ID should be the same @@ -332,7 +338,7 @@ public function getUserInfo($accessToken) } // Exchange the access token for user profile - $url = $this->profileEndpoint . '/user/profile'; + $url = $this->profileEndpoint . '/user/profile'; $httpCurlRequest = new HttpCurl($this->config); $httpCurlRequest->setAccessToken($accessToken); @@ -343,11 +349,11 @@ public function getUserInfo($accessToken) return $userInfo; } - /* setParametersAndPost - sets the parameters array with non empty values from the requestParameters array sent to API calls. * If Provider Credit Details is present, values are set by setProviderCreditDetails * If Provider Credit Reversal Details is present, values are set by setProviderCreditDetails */ + private function setParametersAndPost($parameters, $fieldMappings, $requestParameters) { /* For loop to take all the non empty parameters in the $requestParameters and add it into the $parameters array, @@ -372,7 +378,7 @@ private function setParametersAndPost($parameters, $fieldMappings, $requestParam } // When checking for non-empty values, consider any boolean as non-empty - if (array_key_exists($param, $fieldMappings) && (is_bool($value) || $value!='')) { + if (array_key_exists($param, $fieldMappings) && (is_bool($value) || $value != '')) { if (is_array($value)) { // If the parameter is a provider_credit_details or provider_credit_reversal_details, call the respective functions to set the values @@ -396,8 +402,8 @@ private function setParametersAndPost($parameters, $fieldMappings, $requestParam return $responseObject; } - /* calculateSignatureAndPost - convert the Parameters array to string and curl POST the parameters to MWS */ + private function calculateSignatureAndPost($parameters) { // Call the signature and Post function to perform the actions. Returns XML in array format @@ -411,7 +417,6 @@ private function calculateSignatureAndPost($parameters) return $responseObject; } - /* If merchant_id is not set via the requestParameters array then it's taken from the config array * * Set the platform_id if set in the config['platform_id'] array @@ -419,19 +424,23 @@ private function calculateSignatureAndPost($parameters) * If currency_code is set in the $requestParameters and it exists in the $fieldMappings array, strtoupper it * else take the value from config array if set */ + private function setDefaultValues($parameters, $fieldMappings, $requestParameters) { - if (empty($requestParameters['merchant_id'])) + if (empty($requestParameters['merchant_id'])) { $parameters['SellerId'] = $this->config['merchant_id']; + } if (array_key_exists('platform_id', $fieldMappings)) { - if (empty($requestParameters['platform_id']) && !empty($this->config['platform_id'])) - $parameters[$fieldMappings['platform_id']] = $this->config['platform_id']; + if (empty($requestParameters['platform_id']) && !empty($this->config['platform_id'])) { + $parameters[$fieldMappings['platform_id']] = $this->config['platform_id']; + } } + if (array_key_exists('currency_code', $fieldMappings)) { if (!empty($requestParameters['currency_code'])) { $parameters[$fieldMappings['currency_code']] = strtoupper($requestParameters['currency_code']); - } else if (!(array_key_exists('Action', $parameters) && $parameters['Action'] === 'SetOrderAttributes')) { + } elseif (!(array_key_exists('Action', $parameters) && $parameters['Action'] === 'SetOrderAttributes')) { // Only supply a default CurrencyCode parameter if not using SetOrderAttributes API $parameters[$fieldMappings['currency_code']] = strtoupper($this->config['currency_code']); } @@ -463,6 +472,7 @@ private function setOrderItemCategories($parameters, $categories) * @param credit_amount - [String] * @optional currency_code - [String] */ + private function setProviderCreditDetails($parameters, $providerCreditInfo) { $providerIndex = 0; @@ -479,26 +489,26 @@ private function setProviderCreditDetails($parameters, $providerCreditInfo) $providerIndex = $providerIndex + 1; foreach ($value as $param => $val) { - if (array_key_exists($param, $fieldMappings) && trim($val)!='') { - $parameters[$providerString.$providerIndex. '.' .$fieldMappings[$param]] = $val; - } + if (array_key_exists($param, $fieldMappings) && trim($val) != '') { + $parameters[$providerString . $providerIndex . '.' . $fieldMappings[$param]] = $val; + } } // If currency code is not entered take it from the config array - if (empty($parameters[$providerString.$providerIndex. '.' .$fieldMappings['currency_code']])) { - $parameters[$providerString.$providerIndex. '.' .$fieldMappings['currency_code']] = strtoupper($this->config['currency_code']); + if (empty($parameters[$providerString . $providerIndex . '.' . $fieldMappings['currency_code']])) { + $parameters[$providerString . $providerIndex . '.' . $fieldMappings['currency_code']] = strtoupper($this->config['currency_code']); } } return $parameters; } - /* setProviderCreditReversalDetails - sets the reverse provider credit details sent via the Refund API call. * @param provider_id - [String] * @param credit_amount - [String] * @optional currency_code - [String] */ + private function setProviderCreditReversalDetails($parameters, $providerCreditInfo) { $providerIndex = 0; @@ -515,21 +525,20 @@ private function setProviderCreditReversalDetails($parameters, $providerCreditIn $providerIndex = $providerIndex + 1; foreach ($value as $param => $val) { - if (array_key_exists($param, $fieldMappings) && trim($val)!='') { - $parameters[$providerString.$providerIndex. '.' .$fieldMappings[$param]] = $val; - } + if (array_key_exists($param, $fieldMappings) && trim($val) != '') { + $parameters[$providerString . $providerIndex . '.' . $fieldMappings[$param]] = $val; + } } // If currency code is not entered take it from the config array - if (empty($parameters[$providerString.$providerIndex. '.' .$fieldMappings['currency_code']])) { - $parameters[$providerString.$providerIndex. '.' .$fieldMappings['currency_code']] = strtoupper($this->config['currency_code']); + if (empty($parameters[$providerString . $providerIndex . '.' . $fieldMappings['currency_code']])) { + $parameters[$providerString . $providerIndex . '.' . $fieldMappings['currency_code']] = strtoupper($this->config['currency_code']); } } return $parameters; } - /* GetOrderReferenceDetails API call - Returns details about the Order Reference object and its current state. * @see https://pay.amazon.com/developer/documentation/apireference/201751970 * @@ -542,11 +551,12 @@ private function setProviderCreditReversalDetails($parameters, $providerCreditIn * You cannot pass both address_consent_token and access_token in * the same call or you will encounter a 400/"AmbiguousToken" error */ + public function getOrderReferenceDetails($requestParameters = array()) { $parameters['Action'] = 'GetOrderReferenceDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -560,7 +570,6 @@ public function getOrderReferenceDetails($requestParameters = array()) return ($responseObject); } - /* SetOrderReferenceDetails API call - Sets order reference details such as the order total and a description for the order. * @see https://pay.amazon.com/developer/documentation/apireference/201751960 * @@ -576,11 +585,12 @@ public function getOrderReferenceDetails($requestParameters = array()) * @optional requestParameters['request_payment_authorization'] - [Boolean] * @optional requestParameters['mws_auth_token'] - [String] */ + public function setOrderReferenceDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'SetOrderReferenceDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -620,9 +630,9 @@ public function setOrderReferenceDetails($requestParameters = array()) */ public function setOrderAttributes($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'SetOrderAttributes'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -645,7 +655,6 @@ public function setOrderAttributes($requestParameters = array()) return ($responseObject); } - /* ConfirmOrderReference API call - Confirms that the order reference is free of constraints and all required information has been set on the order reference. * @see https://pay.amazon.com/developer/documentation/apireference/201751980 @@ -653,23 +662,24 @@ public function setOrderAttributes($requestParameters = array()) * @param requestParameters['amazon_order_reference_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function confirmOrderReference($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'ConfirmOrderReference'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_order_reference_id' => 'AmazonOrderReferenceId', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* CancelOrderReference API call - Cancels a previously confirmed order reference. * @see https://pay.amazon.com/developer/documentation/apireference/201751990 * @@ -678,11 +688,12 @@ public function confirmOrderReference($requestParameters = array()) * @optional requestParameters['cancelation_reason'] [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function cancelOrderReference($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'CancelOrderReference'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -696,7 +707,6 @@ public function cancelOrderReference($requestParameters = array()) return ($responseObject); } - /* CloseOrderReference API call - Confirms that an order reference has been fulfilled (fully or partially) * and that you do not expect to create any new authorizations on this order reference. * @see https://pay.amazon.com/developer/documentation/apireference/201752000 @@ -706,11 +716,12 @@ public function cancelOrderReference($requestParameters = array()) * @optional requestParameters['closure_reason'] [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function closeOrderReference($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'CloseOrderReference'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -724,7 +735,6 @@ public function closeOrderReference($requestParameters = array()) return ($responseObject); } - /* CloseAuthorization API call - Closes an authorization. * @see https://pay.amazon.com/developer/documentation/apireference/201752070 * @@ -733,17 +743,18 @@ public function closeOrderReference($requestParameters = array()) * @optional requestParameters['closure_reason'] [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function closeAuthorization($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'CloseAuthorization'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( - 'merchant_id' => 'SellerId', - 'amazon_authorization_id' => 'AmazonAuthorizationId', - 'closure_reason' => 'ClosureReason', - 'mws_auth_token' => 'MWSAuthToken' + 'merchant_id' => 'SellerId', + 'amazon_authorization_id' => 'AmazonAuthorizationId', + 'closure_reason' => 'ClosureReason', + 'mws_auth_token' => 'MWSAuthToken' ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); @@ -767,12 +778,11 @@ public function closeAuthorization($requestParameters = array()) * @optional requestParameters['mws_auth_token'] - [String] */ - public function authorize($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'Authorize'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -793,7 +803,6 @@ public function authorize($requestParameters = array()) return ($responseObject); } - /* GetAuthorizationDetails API call - Returns the status of a particular authorization and the total amount captured on the authorization. * @see https://pay.amazon.com/developer/documentation/apireference/201752030 * @@ -801,11 +810,12 @@ public function authorize($requestParameters = array()) * @param requestParameters['amazon_authorization_id'] [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function getAuthorizationDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetAuthorizationDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -814,6 +824,7 @@ public function getAuthorizationDetails($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } @@ -830,11 +841,12 @@ public function getAuthorizationDetails($requestParameters = array()) * @optional requestParameters['soft_descriptor'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function capture($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'Capture'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -849,10 +861,10 @@ public function capture($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* GetCaptureDetails API call - Returns the status of a particular capture and the total amount refunded on the capture. * @see https://pay.amazon.com/developer/documentation/apireference/201752060 * @@ -860,11 +872,12 @@ public function capture($requestParameters = array()) * @param requestParameters['amazon_capture_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function getCaptureDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetCaptureDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -873,10 +886,10 @@ public function getCaptureDetails($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* Refund API call - Refunds a previously captured amount. * @see https://pay.amazon.com/developer/documentation/apireference/201752080 * @@ -890,11 +903,12 @@ public function getCaptureDetails($requestParameters = array()) * @optional requestParameters['soft_descriptor'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function refund($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'Refund'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -909,10 +923,10 @@ public function refund($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* GetRefundDetails API call - Returns the status of a particular refund. * @see https://pay.amazon.com/developer/documentation/apireference/201752100 * @@ -920,16 +934,17 @@ public function refund($requestParameters = array()) * @param requestParameters['amazon_refund_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function getRefundDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetRefundDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( - 'merchant_id' => 'SellerId', - 'amazon_refund_id' => 'AmazonRefundId', - 'mws_auth_token' => 'MWSAuthToken' + 'merchant_id' => 'SellerId', + 'amazon_refund_id' => 'AmazonRefundId', + 'mws_auth_token' => 'MWSAuthToken' ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); @@ -937,7 +952,6 @@ public function getRefundDetails($requestParameters = array()) return ($responseObject); } - /* GetServiceStatus API Call - Returns the operational status of the OffAmazonPayments API section * @see https://pay.amazon.com/developer/documentation/apireference/201752110 * @@ -948,11 +962,12 @@ public function getRefundDetails($requestParameters = array()) * @param requestParameters['merchant_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function getServiceStatus($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetServiceStatus'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -964,7 +979,6 @@ public function getServiceStatus($requestParameters = array()) return ($responseObject); } - /* CreateOrderReferenceForId API Call - Creates an order reference for the given object * @see https://pay.amazon.com/developer/documentation/apireference/201751670 * @@ -980,11 +994,12 @@ public function getServiceStatus($requestParameters = array()) * @optional requestParameters['custom_information'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function createOrderReferenceForId($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'CreateOrderReferenceForId'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1003,10 +1018,10 @@ public function createOrderReferenceForId($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* GetBillingAgreementDetails API Call - Returns details about the Billing Agreement object and its current state. * @see https://pay.amazon.com/developer/documentation/apireference/201751690 * @@ -1019,11 +1034,12 @@ public function createOrderReferenceForId($requestParameters = array()) * You cannot pass both address_consent_token and access_token in * the same call or you will encounter a 400/"AmbiguousToken" error */ + public function getBillingAgreementDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetBillingAgreementDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1034,10 +1050,10 @@ public function getBillingAgreementDetails($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* SetBillingAgreementDetails API call - Sets Billing Agreement details such as a description of the agreement and other information about the seller. * @see https://pay.amazon.com/developer/documentation/apireference/201751700 * @@ -1052,11 +1068,12 @@ public function getBillingAgreementDetails($requestParameters = array()) * @optional requestParameters['custom_information'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function setBillingAgreementDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'SetBillingAgreementDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1070,10 +1087,10 @@ public function setBillingAgreementDetails($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* ConfirmBillingAgreement API Call - Confirms that the Billing Agreement is free of constraints and all required information has been set on the Billing Agreement. * @see https://pay.amazon.com/developer/documentation/apireference/201751710 * @@ -1081,11 +1098,12 @@ public function setBillingAgreementDetails($requestParameters = array()) * @param requestParameters['amazon_billing_agreement_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function confirmBillingAgreement($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'ConfirmBillingAgreement'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1094,10 +1112,10 @@ public function confirmBillingAgreement($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* ValidateBillignAgreement API Call - Validates the status of the Billing Agreement object and the payment method associated with it. * @see https://pay.amazon.com/developer/documentation/apireference/201751720 * @@ -1105,11 +1123,12 @@ public function confirmBillingAgreement($requestParameters = array()) * @param requestParameters['amazon_billing_agreement_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function validateBillingAgreement($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'ValidateBillingAgreement'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1118,10 +1137,10 @@ public function validateBillingAgreement($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* AuthorizeOnBillingAgreement API call - Reserves a specified amount against the payment method(s) stored in the Billing Agreement. * @see https://pay.amazon.com/developer/documentation/apireference/201751940 * @@ -1142,11 +1161,12 @@ public function validateBillingAgreement($requestParameters = array()) * @optional requestParameters['inherit_shipping_address'] [Boolean] - Defaults to true * @optional requestParameters['mws_auth_token'] - [String] */ + public function authorizeOnBillingAgreement($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'AuthorizeOnBillingAgreement'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1168,10 +1188,10 @@ public function authorizeOnBillingAgreement($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* CloseBillingAgreement API Call - Returns details about the Billing Agreement object and its current state. * @see https://pay.amazon.com/developer/documentation/apireference/201751950 * @@ -1180,11 +1200,12 @@ public function authorizeOnBillingAgreement($requestParameters = array()) * @optional requestParameters['closure_reason'] [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function closeBillingAgreement($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'CloseBillingAgreement'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1194,10 +1215,10 @@ public function closeBillingAgreement($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* charge convenience method * Performs the API calls * 1. SetOrderReferenceDetails / SetBillingAgreementDetails @@ -1220,7 +1241,9 @@ public function closeBillingAgreement($requestParameters = array()) * @optional requestParameters['charge_order_id'] - [String] : Custom Order ID provided * @optional requestParameters['mws_auth_token'] - [String] */ - public function charge($requestParameters = array()) { + + public function charge($requestParameters = array()) + { $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $requestParameters = $this->trimArray($requestParameters); @@ -1228,12 +1251,12 @@ public function charge($requestParameters = array()) { $setParameters = $authorizeParameters = $confirmParameters = $requestParameters; $chargeType = ''; - + if (!empty($requestParameters['amazon_order_reference_id'])) { $chargeType = 'OrderReference'; } elseif (!empty($requestParameters['amazon_billing_agreement_id'])) { $chargeType = 'BillingAgreement'; - + } elseif (!empty($requestParameters['amazon_reference_id'])) { switch (substr(strtoupper($requestParameters['amazon_reference_id']), 0, 1)) { case 'P': @@ -1275,33 +1298,33 @@ public function charge($requestParameters = array()) { return $response; } - /* makeChargeCalls - makes API calls based off the charge type (OrderReference or BillingAgreement) */ + private function makeChargeCalls($chargeType, $setParameters, $confirmParameters, $authorizeParameters) { switch ($chargeType) { - + case 'OrderReference': - + // Get the Order Reference details and feed the response object to the ResponseParser $responseObj = $this->getOrderReferenceDetails($setParameters); - - // Call the function getOrderReferenceDetailsStatus in ResponseParser.php providing it the XML response - // $oroStatus is an array containing the State of the Order Reference ID - $oroStatus = $responseObj->getOrderReferenceDetailsStatus($responseObj->toXml()); - + + // Call the function getOrderReferenceDetailsStatus in ResponseParser.php providing it the XML response + // $oroStatus is an array containing the State of the Order Reference ID + $oroStatus = $responseObj->getOrderReferenceDetailsStatus($responseObj->toXml()); + if ($oroStatus['State'] === 'Draft') { $response = $this->setOrderReferenceDetails($setParameters); if ($this->success) { $this->confirmOrderReference($confirmParameters); } } - + $responseObj = $this->getOrderReferenceDetails($setParameters); - + // Check the Order Reference Status again before making the Authorization. $oroStatus = $responseObj->getOrderReferenceDetailsStatus($responseObj->toXml()); - + if ($oroStatus['State'] === 'Open') { if ($this->success) { $response = $this->authorize($authorizeParameters); @@ -1311,38 +1334,38 @@ private function makeChargeCalls($chargeType, $setParameters, $confirmParameters if ($oroStatus['State'] != 'Open' && $oroStatus['State'] != 'Draft') { throw new \Exception('The Order Reference is in the ' . $oroStatus['State'] . " State. It should be in the Draft or Open State"); } - + return $response; - + case 'BillingAgreement': - + // Get the Billing Agreement details and feed the response object to the ResponseParser - + $responseObj = $this->getBillingAgreementDetails($setParameters); - + // Call the function getBillingAgreementDetailsStatus in ResponseParser.php providing it the XML response // $baStatus is an array containing the State of the Billing Agreement $baStatus = $responseObj->getBillingAgreementDetailsStatus($responseObj->toXml()); - + if ($baStatus['State'] === 'Draft') { $response = $this->setBillingAgreementDetails($setParameters); if ($this->success) { $response = $this->confirmBillingAgreement($confirmParameters); } } - + // Check the Billing Agreement status again before making the Authorization. $responseObj = $this->getBillingAgreementDetails($setParameters); $baStatus = $responseObj->getBillingAgreementDetailsStatus($responseObj->toXml()); - + if ($this->success && $baStatus['State'] === 'Open') { $response = $this->authorizeOnBillingAgreement($authorizeParameters); } - + if ($baStatus['State'] != 'Open' && $baStatus['State'] != 'Draft') { throw new \Exception('The Billing Agreement is in the ' . $baStatus['State'] . " State. It should be in the Draft or Open State"); } - + return $response; default: @@ -1350,18 +1373,18 @@ private function makeChargeCalls($chargeType, $setParameters, $confirmParameters } } - /* GetProviderCreditDetails API Call - Get the details of the Provider Credit. * * @param requestParameters['merchant_id'] - [String] * @param requestParameters['amazon_provider_credit_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function getProviderCreditDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetProviderCreditDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1370,21 +1393,22 @@ public function getProviderCreditDetails($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* GetProviderCreditReversalDetails API Call - Get details of the Provider Credit Reversal. * * @param requestParameters['merchant_id'] - [String] * @param requestParameters['amazon_provider_credit_reversal_id'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function getProviderCreditReversalDetails($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'GetProviderCreditReversalDetails'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1393,10 +1417,10 @@ public function getProviderCreditReversalDetails($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* ReverseProviderCredit API Call - Reverse the Provider Credit. * * @param requestParameters['merchant_id'] - [String] @@ -1407,11 +1431,12 @@ public function getProviderCreditReversalDetails($requestParameters = array()) * @optional requestParameters['credit_reversal_note'] - [String] * @optional requestParameters['mws_auth_token'] - [String] */ + public function reverseProviderCredit($requestParameters = array()) { - $parameters = array(); + $parameters = array(); $parameters['Action'] = 'ReverseProviderCredit'; - $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); + $requestParameters = array_change_key_case($requestParameters, CASE_LOWER); $fieldMappings = array( 'merchant_id' => 'SellerId', @@ -1424,10 +1449,10 @@ public function reverseProviderCredit($requestParameters = array()) ); $responseObject = $this->setParametersAndPost($parameters, $fieldMappings, $requestParameters); + return ($responseObject); } - /* Create an Array of required parameters, sort them * Calculate signature and invoke the POST to the MWS Service URL * @@ -1437,6 +1462,7 @@ public function reverseProviderCredit($requestParameters = array()) * @param Timestamp [String] * @param Signature [String] */ + private function calculateSignatureAndParametersToString($parameters = array()) { foreach ($parameters as $key => $value) { @@ -1453,17 +1479,17 @@ private function calculateSignatureAndParametersToString($parameters = array()) } } - $parameters['AWSAccessKeyId'] = $this->config['access_key']; - $parameters['Version'] = self::MWS_VERSION; - $parameters['SignatureMethod'] = 'HmacSHA256'; + $parameters['AWSAccessKeyId'] = $this->config['access_key']; + $parameters['Version'] = self::MWS_VERSION; + $parameters['SignatureMethod'] = 'HmacSHA256'; $parameters['SignatureVersion'] = 2; - $parameters['Timestamp'] = $this->getFormattedTimestamp(); + $parameters['Timestamp'] = $this->getFormattedTimestamp(); uksort($parameters, 'strcmp'); $this->createServiceUrl(); $parameters['Signature'] = $this->signParameters($parameters); - $parameters = $this->getParametersAsString($parameters); + $parameters = $this->getParametersAsString($parameters); // Save these parameters in the parameters variable so that it can be returned for unit testing. $this->parameters = $parameters; @@ -1471,7 +1497,6 @@ private function calculateSignatureAndParametersToString($parameters = array()) return $parameters; } - /* Computes RFC 2104-compliant HMAC signature for request parameters * Implements AWS Signature, as per following spec: * @@ -1501,15 +1526,16 @@ private function calculateSignatureAndParametersToString($parameters = array()) * Pairs of parameter and values are separated by the '&' character (ASCII code 38). * */ + private function signParameters(array $parameters) { $signatureVersion = $parameters['SignatureVersion']; - $algorithm = "HmacSHA1"; - $stringToSign = null; + $algorithm = "HmacSHA1"; + $stringToSign = null; if (2 === $signatureVersion) { - $algorithm = "HmacSHA256"; + $algorithm = "HmacSHA256"; $parameters['SignatureMethod'] = $algorithm; - $stringToSign = $this->calculateStringToSignV2($parameters); + $stringToSign = $this->calculateStringToSignV2($parameters); } else { throw new \Exception("Invalid Signature Version specified"); } @@ -1517,11 +1543,11 @@ private function signParameters(array $parameters) return $this->sign($stringToSign, $algorithm); } - /* Calculate String to Sign for SignatureVersion 2 * @param array $parameters request parameters * @return String to Sign */ + private function calculateStringToSignV2(array $parameters) { $data = 'POST'; @@ -1537,8 +1563,8 @@ private function calculateStringToSignV2(array $parameters) return $data; } - /* Convert paremeters to Url encoded query string */ + private function getParametersAsString(array $parameters) { $queryParameters = array(); @@ -1550,19 +1576,18 @@ private function getParametersAsString(array $parameters) } - private function urlEncode($value) { return str_replace('%7E', '~', rawurlencode($value)); } - /* Computes RFC 2104-compliant HMAC signature */ + private function sign($data, $algorithm) { if ($algorithm === 'HmacSHA1') { $hash = 'sha1'; - } else if ($algorithm === 'HmacSHA256') { + } elseif ($algorithm === 'HmacSHA256') { $hash = 'sha256'; } else { throw new \Exception("Non-supported signing method specified"); @@ -1571,28 +1596,28 @@ private function sign($data, $algorithm) return base64_encode(hash_hmac($hash, $data, $this->config['secret_key'], true)); } - /* Formats date as ISO 8601 timestamp */ + private function getFormattedTimestamp() { return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()); } - /* invokePost takes the parameters and invokes the httpPost function to POST the parameters * Exponential retries on error 500 and 503 * The response from the POST is an XML which is converted to Array */ + private function invokePost($parameters) { - $response = array(); - $statusCode = 200; + $response = array(); + $statusCode = 200; $this->success = false; // Submit the request and read response body try { $shouldRetry = true; - $retries = 0; + $retries = 0; do { try { $this->constructUserAgentHeader(); @@ -1602,13 +1627,13 @@ private function invokePost($parameters) $statusCode = $curlResponseInfo["http_code"]; $this->logMessage($this->userAgent); $response = array( - 'Status' => $statusCode, + 'Status' => $statusCode, 'ResponseBody' => $response ); $statusCode = $response['Status']; if ($statusCode == 200) { - $shouldRetry = false; + $shouldRetry = false; $this->success = true; } elseif ($statusCode == 500 || $statusCode == 503) { @@ -1631,13 +1656,13 @@ private function invokePost($parameters) return $response; } - /* Exponential sleep on failed request * Up to three retries will occur if first reqest fails * after 1.0 second, 2.2 seconds, and finally 7.0 seconds * @param retries current retry * @throws Exception if maximum number of retries has been reached */ + private function pauseOnRetry($retries, $status) { if ($retries <= self::MAX_ERROR_RETRY) { @@ -1645,15 +1670,15 @@ private function pauseOnRetry($retries, $status) // 1st delay is (4^1) * 100000 + 600000 = 0.4 + 0.6 second = 1.0 sec // 2nd delay is (4^2) * 100000 + 600000 = 1.6 + 0.6 second = 2.2 sec // 3rd delay is (4^3) * 100000 + 600000 = 6.4 + 0.6 second = 7.0 sec - $delay = (int) (pow(4, $retries) * 100000) + 600000; + $delay = (int)(pow(4, $retries) * 100000) + 600000; usleep($delay); } else { - throw new \Exception('Error Code: '. $status.PHP_EOL.'Maximum number of retry attempts - '. $retries .' reached'); + throw new \Exception('Error Code: ' . $status . PHP_EOL . 'Maximum number of retry attempts - ' . $retries . ' reached'); } } - /* Create MWS service URL and the Endpoint path */ + private function createServiceUrl() { $this->modePath = strtolower($this->config['sandbox']) ? 'OffAmazonPayments_Sandbox' : 'OffAmazonPayments'; @@ -1663,12 +1688,12 @@ private function createServiceUrl() if (array_key_exists($region, $this->regionMappings)) { if (!is_null($this->config['override_service_url'])) { - $this->mwsEndpointUrl = preg_replace("(https?://)", "", $this->config['override_service_url']); + $this->mwsEndpointUrl = preg_replace("(https?://)", "", $this->config['override_service_url']); } else { - $this->mwsEndpointUrl = $this->mwsServiceUrls[$this->regionMappings[$region]]; + $this->mwsEndpointUrl = $this->mwsServiceUrls[$this->regionMappings[$region]]; } - $this->mwsServiceUrl = 'https://' . $this->mwsEndpointUrl . '/' . $this->modePath . '/' . self::MWS_VERSION; + $this->mwsServiceUrl = 'https://' . $this->mwsEndpointUrl . '/' . $this->modePath . '/' . self::MWS_VERSION; $this->mwsEndpointPath = '/' . $this->modePath . '/' . self::MWS_VERSION; } else { throw new \Exception($region . ' is not a valid region'); @@ -1678,16 +1703,16 @@ private function createServiceUrl() } } - /* Based on the config['region'] and config['sandbox'] values get the user profile URL */ + private function profileEndpointUrl() { $profileEnvt = strtolower($this->config['sandbox']) ? "api.sandbox" : "api"; - + if (!empty($this->config['region'])) { $region = strtolower($this->config['region']); - if (array_key_exists($region, $this->regionMappings) ) { + if (array_key_exists($region, $this->regionMappings)) { $this->profileEndpoint = 'https://' . $profileEnvt . '.' . $this->profileEndpointUrls[$region]; } else { throw new \Exception($region . ' is not a valid region'); @@ -1697,9 +1722,8 @@ private function profileEndpointUrl() } } - /* Create the User Agent Header sent with the POST request */ - /* Protected because of PSP module usaged */ + /* Protected because of PSP module usage */ protected function constructUserAgentHeader() { $this->userAgent = 'amazon-pay-sdk-php/' . self::SDK_VERSION . ' ('; @@ -1711,7 +1735,7 @@ protected function constructUserAgentHeader() $this->userAgent .= '/'; } } - + if ($this->config['application_version']) { $this->userAgent .= $this->quoteApplicationVersion($this->config['application_version']); } @@ -1723,12 +1747,12 @@ protected function constructUserAgentHeader() $this->userAgent .= ')'; } - /* Collapse multiple whitespace characters into a single ' ' and backslash escape '\', * and '/' characters from a string. * @param $s * @return string */ + private function quoteApplicationName($s) { $quotedString = preg_replace('/ {2,}|\s/', ' ', $s); @@ -1737,13 +1761,13 @@ private function quoteApplicationName($s) return $quotedString; } - /* Collapse multiple whitespace characters into a single ' ' and backslash escape '\', * and '(' characters from a string. * * @param $s * @return string */ + private function quoteApplicationVersion($s) { $quotedString = preg_replace('/ {2,}|\s/', ' ', $s); @@ -1802,5 +1826,4 @@ public static function getSignature($stringToSign, $secretKey) { return base64_encode(hash_hmac('sha256', $stringToSign, $secretKey, true)); } - } diff --git a/AmazonPay/HttpCurl.php b/AmazonPay/HttpCurl.php index df281b2..feeec50 100644 --- a/AmazonPay/HttpCurl.php +++ b/AmazonPay/HttpCurl.php @@ -47,7 +47,7 @@ public function setAccessToken($accesstoken) * config['proxy_password'] */ - protected function commonCurlParams($url,$userAgent) + protected function commonCurlParams($url, $userAgent) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); @@ -60,8 +60,9 @@ protected function commonCurlParams($url,$userAgent) curl_setopt($ch, CURLOPT_CAINFO, $this->config['cabundle_file']); } - if (!empty($userAgent)) + if (!empty($userAgent)) { curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); + } if ($this->config['proxy_host'] != null && $this->config['proxy_port'] != -1) { curl_setopt($ch, CURLOPT_PROXY, $this->config['proxy_host'] . ':' . $this->config['proxy_port']); @@ -82,12 +83,12 @@ protected function commonCurlParams($url,$userAgent) public function httpPost($url, $userAgent = null, $parameters = null) { - $ch = $this->commonCurlParams($url,$userAgent); - + $ch = $this->commonCurlParams($url, $userAgent); + curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); curl_setopt($ch, CURLOPT_HEADER, false); - + $response = $this->execute($ch); return $response; } @@ -99,7 +100,7 @@ public function httpPost($url, $userAgent = null, $parameters = null) public function httpGet($url, $userAgent = null) { - $ch = $this->commonCurlParams($url,$userAgent); + $ch = $this->commonCurlParams($url, $userAgent); // Setting the HTTP header with the Access Token only for Getting user info if ($this->header) { diff --git a/AmazonPay/HttpCurlInterface.php b/AmazonPay/HttpCurlInterface.php index 2d9d34c..ee7ae95 100644 --- a/AmazonPay/HttpCurlInterface.php +++ b/AmazonPay/HttpCurlInterface.php @@ -4,27 +4,27 @@ /* Interface for HttpCurl.php */ interface HttpCurlInterface -{ +{ /* Set Http header for Access token for the GetUserInfo call */ - + public function setHttpHeader(); - + /* Setter for Access token to get the user info */ - + public function setAccessToken($accesstoken); - + /* POST using curl for the following situations * 1. API calls * 2. IPN certificate retrieval * 3. Get User Info */ - + public function httpPost($url, $userAgent = null, $parameters = null); - + /* GET using curl for the following situations * 1. IPN certificate retrieval * 3. Get User Info */ - + public function httpGet($url, $userAgent = null); } diff --git a/AmazonPay/IpnHandler.php b/AmazonPay/IpnHandler.php index dd49823..699da29 100644 --- a/AmazonPay/IpnHandler.php +++ b/AmazonPay/IpnHandler.php @@ -9,11 +9,12 @@ require_once 'HttpCurl.php'; require_once 'IpnHandlerInterface.php'; if (!interface_exists('\Psr\Log\LoggerAwareInterface')) { - require_once(__DIR__.'/../Psr/Log/LoggerAwareInterface.php'); + require_once(__DIR__ . '/../Psr/Log/LoggerAwareInterface.php'); } if (!interface_exists('\Psr\Log\LoggerInterface')) { - require_once(__DIR__.'/../Psr/Log/LoggerInterface.php'); + require_once(__DIR__ . '/../Psr/Log/LoggerInterface.php'); } + use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; @@ -32,11 +33,13 @@ class IpnHandler implements IpnHandlerInterface, LoggerAwareInterface // Implement a logging library that utilizes the PSR 3 logger interface private $logger = null; - private $ipnConfig = array('cabundle_file' => null, - 'proxy_host' => null, - 'proxy_port' => -1, - 'proxy_username' => null, - 'proxy_password' => null); + private $ipnConfig = array( + 'cabundle_file' => null, + 'proxy_host' => null, + 'proxy_port' => -1, + 'proxy_username' => null, + 'proxy_password' => null + ); public function __construct($headers, $body, $ipnConfig = null) @@ -51,11 +54,11 @@ public function __construct($headers, $body, $ipnConfig = null) // Get the list of fields that we are interested in $this->fields = array( "Timestamp" => true, - "Message" => true, + "Message" => true, "MessageId" => true, - "Subject" => false, - "TopicArn" => true, - "Type" => true + "Subject" => false, + "TopicArn" => true, + "Type" => true ); // Validate the IPN message header [x-amz-sns-message-type] @@ -74,7 +77,7 @@ public function __construct($headers, $body, $ipnConfig = null) private function checkConfigKeys($ipnConfig) { $ipnConfig = array_change_key_case($ipnConfig, CASE_LOWER); - $ipnConfig = $this->trimArray($ipnConfig); + $ipnConfig = $this->trimArray($ipnConfig); foreach ($ipnConfig as $key => $value) { if (array_key_exists($key, $this->ipnConfig)) { @@ -86,13 +89,15 @@ private function checkConfigKeys($ipnConfig) } } - public function setLogger(LoggerInterface $logger = null) { + public function setLogger(LoggerInterface $logger = null) + { $this->logger = $logger; } - + /* Helper function to log data within the Client */ - private function logMessage($message) { + private function logMessage($message) + { if ($this->logger) { $this->logger->debug($message); } @@ -101,7 +106,7 @@ private function logMessage($message) { /* Setter function * Sets the value for the key if the key exists in ipnConfig */ - + public function __set($name, $value) { if (array_key_exists(strtolower($name), $this->ipnConfig)) { @@ -114,7 +119,7 @@ public function __set($name, $value) /* Getter function * Returns the value for the key if the key exists in ipnConfig */ - + public function __get($name) { if (array_key_exists(strtolower($name), $this->ipnConfig)) { @@ -125,16 +130,15 @@ public function __get($name) } /* Trim the input Array key values */ - + private function trimArray($array) { - foreach ($array as $key => $value) - { - $array[$key] = trim($value); - } - return $array; + foreach ($array as $key => $value) { + $array[$key] = trim($value); + } + return $array; } - + private function validateHeaders() { // Quickly check that this is a sns message @@ -165,7 +169,7 @@ private function getMessage() * * @return string error message */ - + private function getErrorMessageForJsonError($json_error) { switch ($json_error) { @@ -263,10 +267,10 @@ private function validateUrl($url) * * @return bool true if valid */ - + private function constructAndVerifySignature() { - $signature = base64_decode($this->getMandatoryField("Signature")); + $signature = base64_decode($this->getMandatoryField("Signature")); $certificatePath = $this->getMandatoryField("SigningCertURL"); $this->validateUrl($certificatePath); $this->certificate = $this->getCertificate($certificatePath); @@ -281,12 +285,12 @@ private function constructAndVerifySignature() * * gets the certificate from the $certificatePath using Curl */ - + private function getCertificate($certificatePath) { - $httpCurlRequest = new HttpCurl($this->ipnConfig); + $httpCurlRequest = new HttpCurl($this->ipnConfig); - $response = $httpCurlRequest->httpGet($certificatePath); + $response = $httpCurlRequest->httpGet($certificatePath); return $response; } @@ -302,12 +306,12 @@ public function verifySignatureIsCorrectFromCertificate($signature) { $certKey = openssl_get_publickey($this->certificate); - if ($certKey === False) { + if ($certKey === false) { throw new \Exception("Unable to extract public key from cert"); } try { - $certInfo = openssl_x509_parse($this->certificate, true); + $certInfo = openssl_x509_parse($this->certificate, true); $certSubject = $certInfo["subject"]; if (is_null($certSubject)) { @@ -340,7 +344,7 @@ public function verifySignatureIsCorrectFromCertificate($signature) * * @return string field contents if found */ - + private function getMandatoryField($fieldName) { $value = $this->getField($fieldName); @@ -356,7 +360,7 @@ private function getMandatoryField($fieldName) * * @return string field contents if found, null otherwise */ - + private function getField($fieldName) { if (array_key_exists($fieldName, $this->snsMessage)) { @@ -367,7 +371,7 @@ private function getField($fieldName) } /* returnMessage() - JSON decode the raw [Message] portion of the IPN */ - + public function returnMessage() { return json_decode($this->snsMessage['Message'], true); @@ -383,14 +387,14 @@ public function returnMessage() * Topic ARN - Topic of the IPN * @return response in JSON format */ - + public function toJson() { $response = $this->simpleXmlObject(); // Merging the remaining fields with the response $remainingFields = $this->getRemainingIpnFields(); - $responseArray = array_merge($remainingFields,(array)$response); + $responseArray = array_merge($remainingFields, (array)$response); // Converting to JSON format $response = json_encode($responseArray); @@ -401,7 +405,7 @@ public function toJson() /* toArray() - Converts IPN [Message] field to associative array * @return response in array format */ - + public function toArray() { $response = $this->simpleXmlObject(); @@ -412,7 +416,7 @@ public function toArray() // Merging the remaining fields with the response array $remainingFields = $this->getRemainingIpnFields(); - $response = array_merge($remainingFields,$response); + $response = array_merge($remainingFields, $response); return $response; } @@ -436,7 +440,7 @@ private function simpleXmlObject() $this->logMessage($this->sanitizeResponseData($ipnMessage['NotificationData'])); // Getting the Simple XML element object of the IPN XML Response Body - $response = simplexml_load_string((string) $ipnMessage['NotificationData']); + $response = simplexml_load_string((string)$ipnMessage['NotificationData']); // Adding the Type, MessageId, TopicArn details of the IPN to the Simple XML element Object $response->addChild('Type', $this->snsMessage['Type']); @@ -449,16 +453,17 @@ private function simpleXmlObject() /* getRemainingIpnFields() * Gets the remaining fields of the IPN to be later appended to the return message */ - + private function getRemainingIpnFields() { $ipnMessage = $this->returnMessage(); $remainingFields = array( - 'NotificationReferenceId' =>$ipnMessage['NotificationReferenceId'], - 'NotificationType' =>$ipnMessage['NotificationType'], - 'SellerId' =>$ipnMessage['SellerId'], - 'ReleaseEnvironment' =>$ipnMessage['ReleaseEnvironment'] ); + 'NotificationReferenceId' => $ipnMessage['NotificationReferenceId'], + 'NotificationType' => $ipnMessage['NotificationType'], + 'SellerId' => $ipnMessage['SellerId'], + 'ReleaseEnvironment' => $ipnMessage['ReleaseEnvironment'] + ); return $remainingFields; } diff --git a/AmazonPay/IpnHandlerInterface.php b/AmazonPay/IpnHandlerInterface.php index cb83080..b646ad0 100644 --- a/AmazonPay/IpnHandlerInterface.php +++ b/AmazonPay/IpnHandlerInterface.php @@ -4,9 +4,9 @@ /* Interface for IpnHandler.php */ interface IpnHandlerInterface -{ +{ /* returnMessage() - JSON decode the raw [Message] portion of the IPN */ - + public function returnMessage(); /* toJson() - Converts IPN [Message] field to JSON @@ -19,12 +19,12 @@ public function returnMessage(); * Topic ARN - Topic of the IPN * @return response in JSON format */ - + public function toJson(); /* toArray() - Converts IPN [Message] field to associative array * @return response in array format */ - + public function toArray(); } diff --git a/AmazonPay/Regions.php b/AmazonPay/Regions.php index e8b1055..6ea8a7d 100644 --- a/AmazonPay/Regions.php +++ b/AmazonPay/Regions.php @@ -7,17 +7,23 @@ class Regions { - public $mwsServiceUrls = array('eu' => 'mws-eu.amazonservices.com', - 'na' => 'mws.amazonservices.com', - 'jp' => 'mws.amazonservices.jp'); - - public $profileEndpointUrls = array('uk' => 'amazon.co.uk', - 'us' => 'amazon.com', - 'de' => 'amazon.de', - 'jp' => 'amazon.co.jp'); - - public $regionMappings = array('de' => 'eu', - 'uk' => 'eu', - 'us' => 'na', - 'jp' => 'jp'); + public $mwsServiceUrls = array( + 'eu' => 'mws-eu.amazonservices.com', + 'na' => 'mws.amazonservices.com', + 'jp' => 'mws.amazonservices.jp' + ); + + public $profileEndpointUrls = array( + 'uk' => 'amazon.co.uk', + 'us' => 'amazon.com', + 'de' => 'amazon.de', + 'jp' => 'amazon.co.jp' + ); + + public $regionMappings = array( + 'de' => 'eu', + 'uk' => 'eu', + 'us' => 'na', + 'jp' => 'jp' + ); } diff --git a/AmazonPay/ResponseInterface.php b/AmazonPay/ResponseInterface.php index 0d78768..f4756f7 100644 --- a/AmazonPay/ResponseInterface.php +++ b/AmazonPay/ResponseInterface.php @@ -4,28 +4,28 @@ /* Interface for ResponseParser.php */ interface ResponseInterface -{ +{ /* Returns the XML portion of the response */ - + public function toXml(); - + /* toJson - converts XML into Json * @param $response [XML] */ - + public function toJson(); - + /* toArray - converts XML into associative array * @param $this->_response [XML] */ - + public function toArray(); - + /* Get the status of the BillingAgreement */ - + public function getBillingAgreementDetailsStatus($response); /* Get the status of the OrderReference */ - + public function getOrderReferenceDetailsStatus($response); } diff --git a/AmazonPay/ResponseParser.php b/AmazonPay/ResponseParser.php index 8e5978b..560e86f 100644 --- a/AmazonPay/ResponseParser.php +++ b/AmazonPay/ResponseParser.php @@ -10,90 +10,90 @@ class ResponseParser implements ResponseInterface { public $response = null; - - public function __construct($response=null) + + public function __construct($response = null) { $this->response = $response; } - + /* Returns the XML portion of the response */ - + public function toXml() { return $this->response['ResponseBody']; } - + /* toJson - converts XML into Json * @param $response [XML] */ - + public function toJson() { $response = $this->simpleXmlObject(); - + return (json_encode($response)); } - + /* toArray - converts XML into associative array * @param $this->response [XML] */ - + public function toArray() { $response = $this->simpleXmlObject(); - + // Converting the SimpleXMLElement Object to array() $response = json_encode($response); - + return (json_decode($response, true)); } - + private function simpleXmlObject() { $response = $this->response; - + // Getting the HttpResponse Status code to the output as a string $status = strval($response['Status']); - + // Getting the Simple XML element object of the XML Response Body - $response = simplexml_load_string((string) $response['ResponseBody']); - + $response = simplexml_load_string((string)$response['ResponseBody']); + // Adding the HttpResponse Status code to the output as a string $response->addChild('ResponseStatus', $status); - + return $response; } - + /* Get the status of the Order Reference ID */ - + public function getOrderReferenceDetailsStatus($response) { - $oroStatus = $this->getStatus('GetORO', '//GetORO:OrderReferenceStatus', $response); - - return $oroStatus; + $oroStatus = $this->getStatus('GetORO', '//GetORO:OrderReferenceStatus', $response); + + return $oroStatus; } - + /* Get the status of the BillingAgreement */ - + public function getBillingAgreementDetailsStatus($response) { - $baStatus = $this->getStatus('GetBA', '//GetBA:BillingAgreementStatus', $response); - - return $baStatus; + $baStatus = $this->getStatus('GetBA', '//GetBA:BillingAgreementStatus', $response); + + return $baStatus; } - - private function getStatus($type, $path, $response) + + private function getStatus($type, $path, $response) { - $data= new \SimpleXMLElement($response); - $namespaces = $data->getNamespaces(true); - foreach($namespaces as $key=>$value){ - $namespace = $value; - } - $data->registerXPathNamespace($type, $namespace); - foreach ($data->xpath($path) as $value) { - $status = json_decode(json_encode((array)$value), TRUE); - } - - return $status; + $data = new \SimpleXMLElement($response); + $namespaces = $data->getNamespaces(true); + foreach ($namespaces as $key => $value) { + $namespace = $value; + } + $data->registerXPathNamespace($type, $namespace); + foreach ($data->xpath($path) as $value) { + $status = json_decode(json_encode((array)$value), TRUE); + } + + return $status; } } diff --git a/tst/unit/ClientTest.php b/tst/unit/ClientTest.php index 49e8141..6c706a7 100644 --- a/tst/unit/ClientTest.php +++ b/tst/unit/ClientTest.php @@ -8,21 +8,21 @@ class ClientTest extends \PHPUnit_Framework_TestCase { private $configParams = array( - 'merchant_id' => 'test', - 'access_key' => 'test', - 'secret_key' => "test", - 'currency_code' => 'usd', - 'client_id' => 'test', - 'region' => 'us', - 'sandbox' => true, - 'platform_id' => 'test', - 'application_name' => 'sdk testing', - 'application_version' => '1.0', - 'proxy_host' => null, - 'proxy_port' => -1, - 'proxy_username' => null, - 'proxy_Password' => null - ); + 'merchant_id' => 'test', + 'access_key' => 'test', + 'secret_key' => "test", + 'currency_code' => 'usd', + 'client_id' => 'test', + 'region' => 'us', + 'sandbox' => true, + 'platform_id' => 'test', + 'application_name' => 'sdk testing', + 'application_version' => '1.0', + 'proxy_host' => null, + 'proxy_port' => -1, + 'proxy_username' => null, + 'proxy_Password' => null + ); public function testConfigArray() { @@ -36,7 +36,7 @@ public function testConfigArray() $this->assertFalse((bool)$client->__get('sandbox')); try { - $client = new Client(array('sandbox' => 'false')); + $client = new Client(array('sandbox' => 'false')); } catch (\Exception $expected) { $this->assertRegExp('/should be a boolean value/i', strval($expected)); } @@ -158,11 +158,11 @@ public function testGetOrderReferenceDetails() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_order_reference_id' => 'AmazonOrderReferenceId', - 'address_consent_token' => 'AddressConsentToken', - 'access_token' => 'AccessToken', - 'mws_auth_token' => 'MWSAuthToken' + 'address_consent_token' => 'AddressConsentToken', + 'access_token' => 'AccessToken', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'GetOrderReferenceDetails'; @@ -225,7 +225,7 @@ public function testSetOrderAttributesBeforeConfirm() 'store_name' => 'OrderAttributes.SellerOrderAttributes.StoreName', 'custom_information' => 'OrderAttributes.SellerOrderAttributes.CustomInformation', 'request_payment_authorization' => 'OrderAttributes.RequestPaymentAuthorization', - 'payment_service_provider_id' => 'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId', + 'payment_service_provider_id' => 'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId', 'payment_service_provider_order_id' => 'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId', 'order_item_categories' => array(), 'mws_auth_token' => 'MWSAuthToken' @@ -262,7 +262,7 @@ public function testSetOrderAttributesAfterConfirm() 'store_name' => 'OrderAttributes.SellerOrderAttributes.StoreName', 'custom_information' => 'OrderAttributes.SellerOrderAttributes.CustomInformation', 'request_payment_authorization' => 'OrderAttributes.RequestPaymentAuthorization', - 'payment_service_provider_id' => 'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId', + 'payment_service_provider_id' => 'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId', 'payment_service_provider_order_id' => 'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId', 'order_item_categories' => array(), 'mws_auth_token' => 'MWSAuthToken' @@ -289,9 +289,9 @@ public function testConfirmOrderReference() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_order_reference_id' => 'AmazonOrderReferenceId', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'ConfirmOrderReference'; @@ -313,10 +313,10 @@ public function testCancelOrderReference() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_order_reference_id' => 'AmazonOrderReferenceId', - 'cancelation_reason' => 'CancelationReason', - 'mws_auth_token' => 'MWSAuthToken' + 'cancelation_reason' => 'CancelationReason', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'CancelOrderReference'; @@ -338,10 +338,10 @@ public function testCloseOrderReference() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_order_reference_id' => 'AmazonOrderReferenceId', 'closure_reason' => 'ClosureReason', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'CloseOrderReference'; @@ -388,16 +388,16 @@ public function testAuthorize() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_order_reference_id' => 'AmazonOrderReferenceId', - 'authorization_amount' => 'AuthorizationAmount.Amount', - 'currency_code' => 'AuthorizationAmount.CurrencyCode', + 'authorization_amount' => 'AuthorizationAmount.Amount', + 'currency_code' => 'AuthorizationAmount.CurrencyCode', 'authorization_reference_id' => 'AuthorizationReferenceId', - 'capture_now' => 'CaptureNow', + 'capture_now' => 'CaptureNow', 'seller_authorization_note' => 'SellerAuthorizationNote', - 'transaction_timeout' => 'TransactionTimeout', - 'soft_descriptor' => 'SoftDescriptor', - 'mws_auth_token' => 'MWSAuthToken' + 'transaction_timeout' => 'TransactionTimeout', + 'soft_descriptor' => 'SoftDescriptor', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'Authorize'; @@ -418,9 +418,9 @@ public function testGetAuthorizationDetails() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_authorization_id' => 'AmazonAuthorizationId', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'GetAuthorizationDetails'; @@ -442,14 +442,14 @@ public function testCapture() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', - 'amazon_authorization_id' => 'AmazonAuthorizationId', - 'capture_amount' => 'CaptureAmount.Amount', - 'currency_code' => 'CaptureAmount.CurrencyCode', - 'capture_reference_id' => 'CaptureReferenceId', - 'seller_capture_note' => 'SellerCaptureNote', - 'soft_descriptor' => 'SoftDescriptor', - 'mws_auth_token' => 'MWSAuthToken' + 'merchant_id' => 'SellerId', + 'amazon_authorization_id' => 'AmazonAuthorizationId', + 'capture_amount' => 'CaptureAmount.Amount', + 'currency_code' => 'CaptureAmount.CurrencyCode', + 'capture_reference_id' => 'CaptureReferenceId', + 'seller_capture_note' => 'SellerCaptureNote', + 'soft_descriptor' => 'SoftDescriptor', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'Capture'; @@ -471,9 +471,9 @@ public function testGetCaptureDetails() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_capture_id' => 'AmazonCaptureId', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'GetCaptureDetails'; @@ -495,14 +495,14 @@ public function testRefund() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_capture_id' => 'AmazonCaptureId', 'refund_reference_id' => 'RefundReferenceId', - 'refund_amount' => 'RefundAmount.Amount', - 'currency_code' => 'RefundAmount.CurrencyCode', + 'refund_amount' => 'RefundAmount.Amount', + 'currency_code' => 'RefundAmount.CurrencyCode', 'seller_refund_note' => 'SellerRefundNote', - 'soft_descriptor' => 'SoftDescriptor', - 'mws_auth_token' => 'MWSAuthToken' + 'soft_descriptor' => 'SoftDescriptor', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'Refund'; @@ -524,9 +524,9 @@ public function testGetRefundDetails() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', - 'amazon_refund_id' => 'AmazonRefundId', - 'mws_auth_token' => 'MWSAuthToken' + 'merchant_id' => 'SellerId', + 'amazon_refund_id' => 'AmazonRefundId', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'GetRefundDetails'; @@ -571,19 +571,19 @@ public function testCreateOrderReferenceForId() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', - 'id' => 'Id', - 'id_type' => 'IdType', - 'inherit_shipping_address' => 'InheritShippingAddress', - 'confirm_now' => 'ConfirmNow', - 'amount' => 'OrderReferenceAttributes.OrderTotal.Amount', - 'currency_code' => 'OrderReferenceAttributes.OrderTotal.CurrencyCode', - 'platform_id' => 'OrderReferenceAttributes.PlatformId', - 'seller_note' => 'OrderReferenceAttributes.SellerNote', - 'seller_order_id' => 'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId', - 'store_name' => 'OrderReferenceAttributes.SellerOrderAttributes.StoreName', - 'custom_information' => 'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation', - 'mws_auth_token' => 'MWSAuthToken' + 'merchant_id' => 'SellerId', + 'id' => 'Id', + 'id_type' => 'IdType', + 'inherit_shipping_address' => 'InheritShippingAddress', + 'confirm_now' => 'ConfirmNow', + 'amount' => 'OrderReferenceAttributes.OrderTotal.Amount', + 'currency_code' => 'OrderReferenceAttributes.OrderTotal.CurrencyCode', + 'platform_id' => 'OrderReferenceAttributes.PlatformId', + 'seller_note' => 'OrderReferenceAttributes.SellerNote', + 'seller_order_id' => 'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId', + 'store_name' => 'OrderReferenceAttributes.SellerOrderAttributes.StoreName', + 'custom_information' => 'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'CreateOrderReferenceForId'; @@ -605,11 +605,11 @@ public function testGetBillingAgreementDetails() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', - 'address_consent_token' => 'AddressConsentToken', - 'access_token' => 'AccessToken', - 'mws_auth_token' => 'MWSAuthToken' + 'address_consent_token' => 'AddressConsentToken', + 'access_token' => 'AccessToken', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'GetBillingAgreementDetails'; @@ -631,14 +631,14 @@ public function testSetBillingAgreementDetails() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', - 'platform_id' => 'BillingAgreementAttributes.PlatformId', - 'seller_note' => 'BillingAgreementAttributes.SellerNote', + 'platform_id' => 'BillingAgreementAttributes.PlatformId', + 'seller_note' => 'BillingAgreementAttributes.SellerNote', 'seller_billing_agreement_id' => 'BillingAgreementAttributes.SellerBillingAgreementAttributes.SellerBillingAgreementId', - 'custom_information' => 'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation', - 'store_name' => 'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName', - 'mws_auth_token' => 'MWSAuthToken' + 'custom_information' => 'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation', + 'store_name' => 'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'SetBillingAgreementDetails'; @@ -660,9 +660,9 @@ public function testConfirmBillingAgreement() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'ConfirmBillingAgreement'; @@ -684,9 +684,9 @@ public function testValidateBillingAgreement() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', - 'mws_auth_token' => 'MWSAuthToken' + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'ValidateBillingAgreement'; @@ -708,22 +708,22 @@ public function testAuthorizeOnBillingAgreement() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', - 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', - 'authorization_reference_id' => 'AuthorizationReferenceId', - 'authorization_amount' => 'AuthorizationAmount.Amount', - 'currency_code' => 'AuthorizationAmount.CurrencyCode', - 'seller_authorization_note' => 'SellerAuthorizationNote', - 'transaction_timeout' => 'TransactionTimeout', - 'capture_now' => 'CaptureNow', - 'soft_descriptor' => 'SoftDescriptor', - 'seller_note' => 'SellerNote', - 'platform_id' => 'PlatformId', - 'custom_information' => 'SellerOrderAttributes.CustomInformation', - 'seller_order_id' => 'SellerOrderAttributes.SellerOrderId', - 'store_name' => 'SellerOrderAttributes.StoreName', - 'inherit_shipping_address' => 'InheritShippingAddress', - 'mws_auth_token' => 'MWSAuthToken' + 'merchant_id' => 'SellerId', + 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', + 'authorization_reference_id' => 'AuthorizationReferenceId', + 'authorization_amount' => 'AuthorizationAmount.Amount', + 'currency_code' => 'AuthorizationAmount.CurrencyCode', + 'seller_authorization_note' => 'SellerAuthorizationNote', + 'transaction_timeout' => 'TransactionTimeout', + 'capture_now' => 'CaptureNow', + 'soft_descriptor' => 'SoftDescriptor', + 'seller_note' => 'SellerNote', + 'platform_id' => 'PlatformId', + 'custom_information' => 'SellerOrderAttributes.CustomInformation', + 'seller_order_id' => 'SellerOrderAttributes.SellerOrderId', + 'store_name' => 'SellerOrderAttributes.StoreName', + 'inherit_shipping_address' => 'InheritShippingAddress', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'AuthorizeOnBillingAgreement'; @@ -745,10 +745,10 @@ public function testCloseBillingAgreement() { $client = new Client($this->configParams); $fieldMappings = array( - 'merchant_id' => 'SellerId', + 'merchant_id' => 'SellerId', 'amazon_billing_agreement_id' => 'AmazonBillingAgreementId', - 'closure_reason' => 'ClosureReason', - 'mws_auth_token' => 'MWSAuthToken' + 'closure_reason' => 'ClosureReason', + 'mws_auth_token' => 'MWSAuthToken' ); $action = 'CloseBillingAgreement'; @@ -813,27 +813,27 @@ public function testSignature() { $client = new Client($this->configParams); - $parameters['SellerId'] = $this->configParams['merchant_id']; - $parameters['AWSAccessKeyId'] = $this->configParams['access_key']; - $parameters['Version'] = 'test'; - $parameters['SignatureMethod'] = 'HmacSHA256'; + $parameters['SellerId'] = $this->configParams['merchant_id']; + $parameters['AWSAccessKeyId'] = $this->configParams['access_key']; + $parameters['Version'] = 'test'; + $parameters['SignatureMethod'] = 'HmacSHA256'; $parameters['SignatureVersion'] = 2; - $parameters['Timestamp'] = $this->getFormattedTimestamp(); + $parameters['Timestamp'] = $this->getFormattedTimestamp(); uksort($parameters, 'strcmp'); - $signatureObj = new Signature($this->configParams,$parameters); + $signatureObj = new Signature($this->configParams, $parameters); $expectedSignature = $signatureObj->getSignature(); - $this->callPrivateMethod($client,'createServiceUrl', null); + $this->callPrivateMethod($client, 'createServiceUrl', null); - $signature = $this->callPrivateMethod($client,'signParameters', $parameters); + $signature = $this->callPrivateMethod($client, 'signParameters', $parameters); $this->assertEquals($signature, $expectedSignature); } public function test500or503() { - try { + try { $client = new Client($this->configParams); $url = 'https://www.amazon.com/OffAmazonPayments_Sandbox/2013-01-01'; @@ -850,7 +850,7 @@ public function testXmlResponse() { $response = array(); $response['ResponseBody'] = - ' + ' S01-5806490-2147504 2015-09-27T02:18:33.408Z This is testing API call @@ -866,14 +866,14 @@ public function testJsonResponse() { $response = array('Status' => '200'); $response['ResponseBody'] = - ' + ' S01-5806490-2147504 2015-09-27T02:18:33.408Z This is testing API call '; $json = - '{"AmazonOrderReferenceId":"S01-5806490-2147504","ExpirationTimestamp":"2015-09-27T02:18:33.408Z","SellerNote":"This is testing API call","ResponseStatus":"200"}'; + '{"AmazonOrderReferenceId":"S01-5806490-2147504","ExpirationTimestamp":"2015-09-27T02:18:33.408Z","SellerNote":"This is testing API call","ResponseStatus":"200"}'; $responseObj = new ResponseParser($response); $jsonResponse = $responseObj->toJson(); @@ -885,16 +885,18 @@ public function testArrayResponse() { $response = array('Status' => '200'); $response['ResponseBody'] = - ' + ' S01-5806490-2147504 2015-09-27T02:18:33.408Z This is testing API call '; - $array = array('AmazonOrderReferenceId' => 'S01-5806490-2147504', - 'ExpirationTimestamp' => '2015-09-27T02:18:33.408Z', - 'SellerNote' => 'This is testing API call', - 'ResponseStatus' => '200'); + $array = array( + 'AmazonOrderReferenceId' => 'S01-5806490-2147504', + 'ExpirationTimestamp' => '2015-09-27T02:18:33.408Z', + 'SellerNote' => 'This is testing API call', + 'ResponseStatus' => '200' + ); $responseObj = new ResponseParser($response); $arrayResponse = $responseObj->toArray(); @@ -936,17 +938,19 @@ private function setDefaultValues($fieldMappings) $apiCallParams = array(); if (array_key_exists('platform_id', $fieldMappings)) { - $expectedParameters[$fieldMappings['platform_id']] = $this->configParams['platform_id']; + $expectedParameters[$fieldMappings['platform_id']] = $this->configParams['platform_id']; $apiCallParams['platform_id'] = $this->configParams['platform_id']; - } + } if (array_key_exists('currency_code', $fieldMappings)) { - $expectedParameters[$fieldMappings['currency_code']] = 'TEST'; + $expectedParameters[$fieldMappings['currency_code']] = 'TEST'; $apiCallParams['currency_code'] = 'TEST'; } - return array('expectedParameters' => $expectedParameters, - 'apiCallParams' => $apiCallParams); + return array( + 'expectedParameters' => $expectedParameters, + 'apiCallParams' => $apiCallParams + ); } /* Formats date as ISO 8601 timestamp */ diff --git a/tst/unit/IpnHandlerTest.php b/tst/unit/IpnHandlerTest.php index 5c5cea4..a0f7cb5 100644 --- a/tst/unit/IpnHandlerTest.php +++ b/tst/unit/IpnHandlerTest.php @@ -6,21 +6,21 @@ class IpnHandlertest extends \PHPUnit_Framework_TestCase { private $configParams = array( - 'cabundle_file' => null, - 'proxy_host' => null, - 'proxy_port' => -1, - 'proxy_username' => null, - 'proxy_Password' => null - ); + 'cabundle_file' => null, + 'proxy_host' => null, + 'proxy_port' => -1, + 'proxy_username' => null, + 'proxy_Password' => null + ); public function testConstructor() { try { $headers = array(); - $headers = array('ab'=>'abc'); + $headers = array('ab' => 'abc'); $body = 'abctest'; - $ipnHandler = new IpnHandler($headers,$body,$this->configParams); + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); } catch (\Exception $expected) { $this->assertRegExp('/Error with message - header./i', strval($expected)); @@ -29,7 +29,7 @@ public function testConstructor() $headers['x-amz-sns-message-type'] = 'Notification'; $body = 'abctest'; - $ipnHandler = new IpnHandler($headers,$body,$this->configParams); + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); } catch (\Exception $expected) { $this->assertRegExp('/Error with message - content is not in json format./i', strval($expected)); @@ -40,7 +40,7 @@ public function testConstructor() 'b' => 'B' ); - $ipnHandler = new IpnHandler(array(),null,$ConfigParams); + $ipnHandler = new IpnHandler(array(), null, $ConfigParams); } catch (\Exception $expected) { $this->assertRegExp('/is either not part of the configuration or has incorrect Key name./i', strval($expected)); @@ -49,47 +49,47 @@ public function testConstructor() public function testValidateUrl() { - $headers = array('x-amz-sns-message-type' => 'Notification'); - try { - $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"http://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; - $ipnHandler = new IpnHandler($headers, $body, $this->configParams); - } catch (\Exception $expected) { - $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); - } + $headers = array('x-amz-sns-message-type' => 'Notification'); + try { + $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"http://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); + } catch (\Exception $expected) { + $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); + } - try { - $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.exe"}'; - $ipnHandler = new IpnHandler($headers, $body, $this->configParams); - } catch (\Exception $expected) { - $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); - } + try { + $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.exe"}'; + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); + } catch (\Exception $expected) { + $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); + } - try { - $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us-east-1.example.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; - $ipnHandler = new IpnHandler($headers, $body, $this->configParams); - } catch (\Exception $expected) { - $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); - } + try { + $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us-east-1.example.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); + } catch (\Exception $expected) { + $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); + } - try { - $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sni.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; - $ipnHandler = new IpnHandler($headers, $body, $this->configParams); - } catch (\Exception $expected) { - $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); - } + try { + $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sni.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); + } catch (\Exception $expected) { + $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); + } - try { - $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; - $ipnHandler = new IpnHandler($headers, $body, $this->configParams); - } catch (\Exception $expected) { - $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); - } + try { + $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); + } catch (\Exception $expected) { + $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); + } - try { - $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us-east-1.amazonaws.com.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; - $ipnHandler = new IpnHandler($headers, $body, $this->configParams); - } catch (\Exception $expected) { - $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); - } + try { + $body = '{"Type":"Notification", "Message":"Test", "MessageId":"Test", "Timestamp":"Test", "Subject":"Test", "TopicArn":"Test", "Signature":"Test", "SigningCertURL":"https://sns.us-east-1.amazonaws.com.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"}'; + $ipnHandler = new IpnHandler($headers, $body, $this->configParams); + } catch (\Exception $expected) { + $this->assertRegExp('/The certificate is located on an invalid domain./i', strval($expected)); + } } } diff --git a/tst/unit/Signature.php b/tst/unit/Signature.php index 02a6727..01fe91e 100644 --- a/tst/unit/Signature.php +++ b/tst/unit/Signature.php @@ -6,34 +6,38 @@ class Signature const MWS_VERSION = '2013-01-01'; private $config = array(); private $signature = null; - + private $mwsEndpointPath = null; private $mwsEndpointUrl = null; private $modePath = null; - + private $mwsServiceUrl = null; - - private $mwsServiceUrls = array('eu' => 'mws-eu.amazonservices.com', - 'na' => 'mws.amazonservices.com', - 'jp' => 'mws.amazonservices.jp'); - - private $regionMappings = array('de' => 'eu', - 'uk' => 'eu', - 'us' => 'na', - 'jp' => 'jp'); - - public function __construct($config = array(),$parameters = array()) + + private $mwsServiceUrls = array( + 'eu' => 'mws-eu.amazonservices.com', + 'na' => 'mws.amazonservices.com', + 'jp' => 'mws.amazonservices.jp' + ); + + private $regionMappings = array( + 'de' => 'eu', + 'uk' => 'eu', + 'us' => 'na', + 'jp' => 'jp' + ); + + public function __construct($config = array(), $parameters = array()) { $config = array_change_key_case($config, CASE_LOWER); $this->config = $config; $this->signature = $this->calculateSignature($parameters); } - + public function getSignature() { - return trim($this->signature); + return trim($this->signature); } - + /* Create an Array of required parameters, sort them * Calculate signature and invoke the POST them to the MWS Service URL * @@ -43,14 +47,14 @@ public function getSignature() * @param Timestamp [String] * @param Signature [String] */ - + private function calculateSignature($parameters) { - $this->createServiceUrl(); - $signature = $this->signParameters($parameters); - return $signature; + $this->createServiceUrl(); + $signature = $this->signParameters($parameters); + return $signature; } - + /* Computes RFC 2104-compliant HMAC signature for request parameters * Implements AWS Signature, as per following spec: * @@ -80,28 +84,28 @@ private function calculateSignature($parameters) * Pairs of parameter and values are separated by the '&' character (ASCII code 38). * */ - + private function signParameters(array $parameters) { $signatureVersion = $parameters['SignatureVersion']; - $algorithm = "HmacSHA1"; - $stringToSign = null; + $algorithm = "HmacSHA1"; + $stringToSign = null; if (2 === $signatureVersion) { - $algorithm = "HmacSHA256"; + $algorithm = "HmacSHA256"; $parameters['SignatureMethod'] = $algorithm; - $stringToSign = $this->calculateStringToSignV2($parameters); + $stringToSign = $this->calculateStringToSignV2($parameters); } else { throw new \Exception("Invalid Signature Version specified"); } - + return $this->sign($stringToSign, $algorithm); } - + /* Calculate String to Sign for SignatureVersion 2 * @param array $parameters request parameters * @return String to Sign */ - + private function calculateStringToSignV2(array $parameters) { $data = 'POST'; @@ -113,55 +117,55 @@ private function calculateStringToSignV2(array $parameters) $data .= $this->getParametersAsString($parameters); return $data; } - + /* Convert paremeters to Url encoded query string */ - + private function getParametersAsString(array $parameters) { $queryParameters = array(); foreach ($parameters as $key => $value) { $queryParameters[] = $key . '=' . $this->urlEncode($value); } - + return implode('&', $queryParameters); } - + private function urlEncode($value) { return str_replace('%7E', '~', rawurlencode($value)); } - + /* Computes RFC 2104-compliant HMAC signature.*/ - + private function sign($data, $algorithm) { if ($algorithm === 'HmacSHA1') { $hash = 'sha1'; - } else if ($algorithm === 'HmacSHA256') { + } elseif ($algorithm === 'HmacSHA256') { $hash = 'sha256'; } else { throw new \Exception("Non-supported signing method specified"); } - + return base64_encode(hash_hmac($hash, $data, $this->config['secret_key'], true)); } - + /* Formats date as ISO 8601 timestamp */ - + private function getFormattedTimestamp() { return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()); } - + private function createServiceUrl() { $this->modePath = strtolower($this->config['sandbox']) ? 'OffAmazonPayments_Sandbox' : 'OffAmazonPayments'; - + if (!empty($this->config['region'])) { $region = strtolower($this->config['region']); if (array_key_exists($region, $this->regionMappings)) { - $this->mwsEndpointUrl = $this->mwsServiceUrls[$this->regionMappings[$region]]; - $this->mwsServiceUrl = 'https://' . $this->mwsEndpointUrl . '/' . $this->modePath . '/' . self::MWS_VERSION; + $this->mwsEndpointUrl = $this->mwsServiceUrls[$this->regionMappings[$region]]; + $this->mwsServiceUrl = 'https://' . $this->mwsEndpointUrl . '/' . $this->modePath . '/' . self::MWS_VERSION; $this->mwsEndpointPath = '/' . $this->modePath . '/' . self::MWS_VERSION; } else { throw new \Exception($region . ' is not a valid region');