installed plugin Easy Digital Downloads version 3.1.0.3

This commit is contained in:
2022-11-27 15:03:07 +00:00
committed by Gitium
parent 555673545b
commit c5dce2cec6
1200 changed files with 238970 additions and 0 deletions

View File

@ -0,0 +1,129 @@
<?php
namespace PayWithAmazon;
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/* Class HttpCurl
* Handles Curl POST function for all requests
*/
require_once 'Interface.php';
class HttpCurl implements HttpCurlInterface
{
private $config = array();
private $header = false;
private $accessToken = null;
/* Takes user configuration array as input
* Takes configuration for API call or IPN config
*/
public function __construct($config = null)
{
$this->config = $config;
}
/* Setter for boolean header to get the user info */
public function setHttpHeader()
{
$this->header = true;
}
/* Setter for Access token to get the user info */
public function setAccessToken($accesstoken)
{
$this->accessToken = $accesstoken;
}
/* Add the common Curl Parameters to the curl handler $ch
* Also checks for optional parameters if provided in the config
* config['cabundle_file']
* config['proxy_port']
* config['proxy_host']
* config['proxy_username']
* config['proxy_password']
*/
private function commonCurlParams($url,$userAgent)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (!is_null($this->config['cabundle_file'])) {
curl_setopt($ch, CURLOPT_CAINFO, $this->config['cabundle_file']);
}
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']);
}
if ($this->config['proxy_username'] != null && $this->config['proxy_password'] != null) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->config['proxy_username'] . ':' . $this->config['proxy_password']);
}
return $ch;
}
/* 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)
{
$ch = $this->commonCurlParams($url,$userAgent);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = $this->execute($ch);
return $response;
}
/* GET using curl for the following situations
* 1. IPN certificate retrieval
* 2. Get User Info
*/
public function httpGet($url, $userAgent = null)
{
$ch = $this->commonCurlParams($url,$userAgent);
// Setting the HTTP header with the Access Token only for Getting user info
if ($this->header) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: bearer ' . $this->accessToken
));
}
$response = $this->execute($ch);
return $response;
}
/* Execute Curl request */
private function execute($ch)
{
$response = '';
if (!$response = curl_exec($ch)) {
$error_msg = "Unable to post request, underlying exception of " . curl_error($ch);
curl_close($ch);
throw new \Exception($error_msg);
}
curl_close($ch);
return $response;
}
}

View File

@ -0,0 +1,482 @@
<?php
namespace PayWithAmazon;
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/* Interface class to showcase the public API methods for Pay With Amazon */
interface ClientInterface
{
/* Takes user configuration array from the user as input
* Takes JSON file path with configuration information as input
* Validates the user configuation array against existing config array
*/
public function __construct($config = null);
/* Setter for sandbox
* Sets the boolean value for config['sandbox'] variable
*/
public function setSandbox($value);
/* Setter for config['client_id']
* Sets the value for config['client_id'] variable
*/
public function setClientId($value);
/* Setter for Proxy
* input $proxy [array]
* @param $proxy['proxy_user_host'] - hostname for the proxy
* @param $proxy['proxy_user_port'] - hostname for the proxy
* @param $proxy['proxy_user_name'] - if your proxy required a username
* @param $proxy['proxy_user_password'] - if your proxy required a passowrd
*/
public function setProxy($proxy);
/* Setter for $_mwsServiceUrl
* Set the URL to which the post request has to be made for unit testing
*/
public function setMwsServiceUrl($url);
/* Getter
* Gets the value for the key if the key exists in config
*/
public function __get($name);
/* Getter for parameters string
* Gets the value for the parameters string for unit testing
*/
public function getParameters();
/* GetUserInfo convenience funtion - Returns user's profile information from Amazon using the access token returned by the Button widget.
*
* @see http://docs.developer.amazonservices.com/en_US/apa_guide/APAGuide_ObtainProfile.html
* @param $access_token [String]
*/
public function getUserInfo($access_token);
/* GetOrderReferenceDetails API call - Returns details about the Order Reference object and its current state.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_GetOrderReferenceDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_order_reference_id'] - [String]
* @optional requestParameters['address_consent_token'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function getOrderReferenceDetails($requestParameters = array());
/* SetOrderReferenceDetails API call - Sets order reference details such as the order total and a description for the order.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_SetOrderReferenceDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_order_reference_id'] - [String]
* @param requestParameters['amount'] - [String]
* @param requestParameters['currency_code'] - [String]
* @optional requestParameters['platform_id'] - [String]
* @optional requestParameters['seller_note'] - [String]
* @optional requestParameters['seller_order_id'] - [String]
* @optional requestParameters['store_name'] - [String]
* @optional requestParameters['custom_information'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function setOrderReferenceDetails($requestParameters = array());
/* ConfirmOrderReferenceDetails API call - Confirms that the order reference is free of constraints and all required information has been set on the order reference.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_ConfirmOrderReference.html
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_order_reference_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function confirmOrderReference($requestParameters = array());
/* CancelOrderReferenceDetails API call - Cancels a previously confirmed order reference.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_CancelOrderReference.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_order_reference_id'] - [String]
* @optional requestParameters['cancelation_reason'] [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function cancelOrderReference($requestParameters = array());
/* CloseOrderReferenceDetails 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 http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_CloseOrderReference.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_order_reference_id'] - [String]
* @optional requestParameters['closure_reason'] [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function closeOrderReference($requestParameters = array());
/* CloseAuthorization API call - Closes an authorization.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_CloseOrderReference.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_authorization_id'] - [String]
* @optional requestParameters['closure_reason'] [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function closeAuthorization($requestParameters = array());
/* Authorize API call - Reserves a specified amount against the payment method(s) stored in the order reference.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_Authorize.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_order_reference_id'] - [String]
* @param requestParameters['authorization_amount'] [String]
* @param requestParameters['currency_code'] - [String]
* @param requestParameters['authorization_reference_id'] [String]
* @optional requestParameters['capture_now'] [String]
* @optional requestParameters['provider_credit_details'] - [array (array())]
* @optional requestParameters['seller_authorization_note'] [String]
* @optional requestParameters['transaction_timeout'] [String] - Defaults to 1440 minutes
* @optional requestParameters['soft_descriptor'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function authorize($requestParameters = array());
/* GetAuthorizationDetails API call - Returns the status of a particular authorization and the total amount captured on the authorization.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_GetAuthorizationDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_authorization_id'] [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function getAuthorizationDetails($requestParameters = array());
/* Capture API call - Captures funds from an authorized payment instrument.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_Capture.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_authorization_id'] - [String]
* @param requestParameters['capture_amount'] - [String]
* @param requestParameters['currency_code'] - [String]
* @param requestParameters['capture_reference_id'] - [String]
* @optional requestParameters['provider_credit_details'] - [array (array())]
* @optional requestParameters['seller_capture_note'] - [String]
* @optional requestParameters['soft_descriptor'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function capture($requestParameters = array());
/* GetCaptureDetails API call - Returns the status of a particular capture and the total amount refunded on the capture.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_GetCaptureDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_capture_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function getCaptureDetails($requestParameters = array());
/* Refund API call - Refunds a previously captured amount.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_Refund.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_capture_id'] - [String]
* @param requestParameters['refund_reference_id'] - [String]
* @param requestParameters['refund_amount'] - [String]
* @param requestParameters['currency_code'] - [String]
* @optional requestParameters['provider_credit_reversal_details'] - [array(array())]
* @optional requestParameters['seller_refund_note'] [String]
* @optional requestParameters['soft_descriptor'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function refund($requestParameters = array());
/* GetRefundDetails API call - Returns the status of a particular refund.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_GetRefundDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_refund_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function getRefundDetails($requestParameters = array());
/* GetServiceStatus API Call - Returns the operational status of the Off-Amazon Payments API section
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_GetServiceStatus.html
*
* The GetServiceStatus operation returns the operational status of the Off-Amazon Payments API
* section of Amazon Marketplace Web Service (Amazon MWS).
* Status values are GREEN, GREEN_I, YELLOW, and RED.
*
* @param requestParameters['merchant_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function getServiceStatus($requestParameters = array());
/* CreateOrderReferenceForId API Call - Creates an order reference for the given object
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_CreateOrderReferenceForId.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['Id'] - [String]
* @optional requestParameters['inherit_shipping_address'] [Boolean]
* @optional requestParameters['ConfirmNow'] - [Boolean]
* @optional Amount (required when confirm_now is set to true) [String]
* @optional requestParameters['currency_code'] - [String]
* @optional requestParameters['seller_note'] - [String]
* @optional requestParameters['seller_order_id'] - [String]
* @optional requestParameters['store_name'] - [String]
* @optional requestParameters['custom_information'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function createOrderReferenceForId($requestParameters = array());
/* GetBillingAgreementDetails API Call - Returns details about the Billing Agreement object and its current state.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_GetBillingAgreementDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_billing_agreement_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function getBillingAgreementDetails($requestParameters = array());
/* SetBillingAgreementDetails API call - Sets Billing Agreement details such as a description of the agreement and other information about the seller.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_SetBillingAgreementDetails.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_billing_agreement_id'] - [String]
* @param requestParameters['amount'] - [String]
* @param requestParameters['currency_code'] - [String]
* @optional requestParameters['platform_id'] - [String]
* @optional requestParameters['seller_note'] - [String]
* @optional requestParameters['seller_billing_agreement_id'] - [String]
* @optional requestParameters['store_name'] - [String]
* @optional requestParameters['custom_information'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function setBillingAgreementDetails($requestParameters = array());
/* ConfirmBillingAgreement API Call - Confirms that the Billing Agreement is free of constraints and all required information has been set on the Billing Agreement.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_ConfirmBillingAgreement.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_billing_agreement_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function confirmBillingAgreement($requestParameters = array());
/* ValidateBillingAgreement API Call - Validates the status of the Billing Agreement object and the payment method associated with it.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_ValidateBillignAgreement.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_billing_agreement_id'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function validateBillingAgreement($requestParameters = array());
/* AuthorizeOnBillingAgreement API call - Reserves a specified amount against the payment method(s) stored in the Billing Agreement.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_AuthorizeOnBillingAgreement.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_billing_agreement_id'] - [String]
* @param requestParameters['authorization_reference_id'] [String]
* @param requestParameters['authorization_amount'] [String]
* @param requestParameters['currency_code'] - [String]
* @optional requestParameters['seller_authorization_note'] [String]
* @optional requestParameters['transaction_timeout'] - Defaults to 1440 minutes
* @optional requestParameters['capture_now'] [String]
* @optional requestParameters['soft_descriptor'] - - [String]
* @optional requestParameters['seller_note'] - [String]
* @optional requestParameters['platform_id'] - [String]
* @optional requestParameters['custom_information'] - [String]
* @optional requestParameters['seller_order_id'] - [String]
* @optional requestParameters['store_name'] - [String]
* @optional requestParameters['inherit_shipping_address'] [Boolean] - Defaults to true
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function authorizeOnBillingAgreement($requestParameters = array());
/* CloseBillingAgreement API Call - Returns details about the Billing Agreement object and its current state.
* @see http://docs.developer.amazonservices.com/en_US/off_amazon_payments/OffAmazonPayments_CloseBillingAgreement.html
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_billing_agreement_id'] - [String]
* @optional requestParameters['closure_reason'] [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function closeBillingAgreement($requestParameters = array());
/* charge convenience method
* Performs the API calls
* 1. SetOrderReferenceDetails / SetBillingAgreementDetails
* 2. ConfirmOrderReference / ConfirmBillingAgreement
* 3. Authorize (with Capture) / AuthorizeOnBillingAgreeemnt (with Capture)
*
* @param requestParameters['merchant_id'] - [String]
*
* @param requestParameters['amazon_reference_id'] - [String] : Order Reference ID /Billing Agreement ID
* If requestParameters['amazon_reference_id'] is empty then the following is required,
* @param requestParameters['amazon_order_reference_id'] - [String] : Order Reference ID
* or,
* @param requestParameters['amazon_billing_agreement_id'] - [String] : Billing Agreement ID
*
* @param $requestParameters['charge_amount'] - [String] : Amount value to be captured
* @param requestParameters['currency_code'] - [String] : Currency Code for the Amount
* @param requestParameters['authorization_reference_id'] - [String]- Any unique string that needs to be passed
* @optional requestParameters['charge_note'] - [String] : Seller Note sent to the buyer
* @optional requestParameters['transaction_timeout'] - [String] : Defaults to 1440 minutes
* @optional requestParameters['charge_order_id'] - [String] : Custom Order ID provided
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function charge($requestParameters = array());
/* 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());
/* 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());
/* ReverseProviderCredit API Call - Reverse the Provider Credit.
*
* @param requestParameters['merchant_id'] - [String]
* @param requestParameters['amazon_provider_credit_id'] - [String]
* @optional requestParameters['credit_reversal_reference_id'] - [String]
* @param requestParameters['credit_reversal_amount'] - [String]
* @optional requestParameters['currency_code'] - [String]
* @optional requestParameters['credit_reversal_note'] - [String]
* @optional requestParameters['mws_auth_token'] - [String]
*/
public function reverseProviderCredit($requestParameters = array());
}
/* Interface for IpnHandler.php */
interface IpnHandlerInterface
{
/* Takes headers and body of the IPN message as input in the constructor
* verifies that the IPN is from the right resource and has the valid data
*/
public function __construct($headers, $body, $ipnConfig = null);
/* returnMessage() - JSON decode the raw [Message] portion of the IPN */
public function returnMessage();
/* toJson() - Converts IPN [Message] field to JSON
*
* Has child elements
* ['NotificationData'] [XML] - API call XML notification data
* @param remainingFields - consists of remaining IPN array fields that are merged
* Type - Notification
* MessageId - ID of the Notification
* 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();
}
/* Interface for HttpCurl.php */
interface HttpCurlInterface
{
/* Takes user configuration array as input
* Takes configuration for API call or IPN config
*/
public function __construct($config = null);
/* 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);
}
/* Interface for ResponseParser.php */
interface ResponseInterface
{
/* Takes response from the API call */
public function __construct($response = null);
/* 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);
}

View File

@ -0,0 +1,421 @@
<?php
namespace PayWithAmazon;
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/* Class IPN_Handler
* Takes headers and body of the IPN message as input in the constructor
* verifies that the IPN is from the right resource and has the valid data
*/
require_once 'HttpCurl.php';
require_once 'Interface.php';
class IpnHandler implements IpnHandlerInterface
{
private $headers = null;
private $body = null;
private $snsMessage = null;
private $fields = array();
private $signatureFields = array();
private $certificate = null;
private $expectedCnName = 'sns.amazonaws.com';
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)
{
$this->headers = array_change_key_case($headers, CASE_LOWER);
$this->body = $body;
if ($ipnConfig != null) {
$this->checkConfigKeys($ipnConfig);
}
// Get the list of fields that we are interested in
$this->fields = array(
"Timestamp" => true,
"Message" => true,
"MessageId" => true,
"Subject" => false,
"TopicArn" => true,
"Type" => true
);
// Validate the IPN message header [x-amz-sns-message-type]
$this->validateHeaders();
// Converts the IPN [Message] to Notification object
$this->getMessage();
// Checks if the notification [Type] is Notification and constructs the signature fields
$this->checkForCorrectMessageType();
// Verifies the signature against the provided pem file in the IPN
$this->constructAndVerifySignature();
}
private function checkConfigKeys($ipnConfig)
{
$ipnConfig = array_change_key_case($ipnConfig, CASE_LOWER);
$ipnConfig = trimArray($ipnConfig);
foreach ($ipnConfig as $key => $value) {
if (array_key_exists($key, $this->ipnConfig)) {
$this->ipnConfig[$key] = $value;
} else {
throw new \Exception('Key ' . $key . ' is either not part of the configuration or has incorrect Key name.
check the ipnConfig array key names to match your key names of your config array ', 1);
}
}
}
/* 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)) {
$this->ipnConfig[$name] = $value;
} else {
throw new \Exception("Key " . $name . " is not part of the configuration", 1);
}
}
/* 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)) {
return $this->ipnConfig[$name];
} else {
throw new \Exception("Key " . $name . " was not found in the configuration", 1);
}
}
/* Trim the input Array key values */
private function trimArray($array)
{
foreach ($array as $key => $value)
{
$array[$key] = trim($value);
}
return $array;
}
private function validateHeaders()
{
// Quickly check that this is a sns message
if (!array_key_exists('x-amz-sns-message-type', $this->headers)) {
throw new \Exception("Error with message - header " . "does not contain x-amz-sns-message-type header");
}
if ($this->headers['x-amz-sns-message-type'] !== 'Notification') {
throw new \Exception("Error with message - header x-amz-sns-message-type is not " . "Notification, is " . $this->headers['x-amz-sns-message-type']);
}
}
private function getMessage()
{
$this->snsMessage = json_decode($this->body, true);
$json_error = json_last_error();
if ($json_error != 0) {
$errorMsg = "Error with message - content is not in json format" . $this->getErrorMessageForJsonError($json_error) . " " . $this->snsMessage;
throw new \Exception($errorMsg);
}
}
/* Convert a json error code to a descriptive error message
*
* @param int $json_error message code
*
* @return string error message
*/
private function getErrorMessageForJsonError($json_error)
{
switch ($json_error) {
case JSON_ERROR_DEPTH:
return " - maximum stack depth exceeded.";
break;
case JSON_ERROR_STATE_MISMATCH:
return " - invalid or malformed JSON.";
break;
case JSON_ERROR_CTRL_CHAR:
return " - control character error.";
break;
case JSON_ERROR_SYNTAX:
return " - syntax error.";
break;
default:
return ".";
break;
}
}
/* checkForCorrectMessageType()
*
* Checks if the Field [Type] is set to ['Notification']
* Gets the value for the fields marked true in the fields array
* Constructs the signature string
*/
private function checkForCorrectMessageType()
{
$type = $this->getMandatoryField("Type");
if (strcasecmp($type, "Notification") != 0) {
throw new \Exception("Error with SNS Notification - unexpected message with Type of " . $type);
}
if (strcmp($this->getMandatoryField("Type"), "Notification") != 0) {
throw new \Exception("Error with signature verification - unable to verify " . $this->getMandatoryField("Type") . " message");
} else {
// Sort the fields into byte order based on the key name(A-Za-z)
ksort($this->fields);
// Extract the key value pairs and sort in byte order
$signatureFields = array();
foreach ($this->fields as $fieldName => $mandatoryField) {
if ($mandatoryField) {
$value = $this->getMandatoryField($fieldName);
} else {
$value = $this->getField($fieldName);
}
if (!is_null($value)) {
array_push($signatureFields, $fieldName);
array_push($signatureFields, $value);
}
}
/* Create the signature string - key / value in byte order
* delimited by newline character + ending with a new line character
*/
$this->signatureFields = implode("\n", $signatureFields) . "\n";
}
}
/* Verify that the signature is correct for the given data and
* public key
*
* @param string $data data to validate
* @param string $signature decoded signature to compare against
* @param string $certificatePath path to certificate, can be file or url
*
* @throws Exception if there is an error with the call
*
* @return bool true if valid
*/
private function constructAndVerifySignature()
{
$signature = base64_decode($this->getMandatoryField("Signature"));
$certificatePath = $this->getMandatoryField("SigningCertURL");
$this->certificate = $this->getCertificate($certificatePath);
$result = $this->verifySignatureIsCorrectFromCertificate($signature);
if (!$result) {
throw new \Exception("Unable to match signature from remote server: signature of " . $this->getCertificate($certificatePath) . " , SigningCertURL of " . $this->getMandatoryField("SigningCertURL") . " , SignatureOf " . $this->getMandatoryField("Signature"));
}
}
/* getCertificate($certificatePath)
*
* gets the certificate from the $certificatePath using Curl
*/
private function getCertificate($certificatePath)
{
$httpCurlRequest = new HttpCurl($this->ipnConfig);
$response = $httpCurlRequest->httpGet($certificatePath);
return $response;
}
/* Verify that the signature is correct for the given data and public key
*
* @param string $data data to validate
* @param string $signature decoded signature to compare against
* @param string $certificate certificate object defined in Certificate.php
*/
public function verifySignatureIsCorrectFromCertificate($signature)
{
$certKey = openssl_get_publickey($this->certificate);
if ($certKey === False) {
throw new \Exception("Unable to extract public key from cert");
}
try {
$certInfo = openssl_x509_parse($this->certificate, true);
$certSubject = $certInfo["subject"];
if (is_null($certSubject)) {
throw new \Exception("Error with certificate - subject cannot be found");
}
} catch (\Exception $ex) {
throw new \Exception("Unable to verify certificate - error with the certificate subject", null, $ex);
}
if (strcmp($certSubject["CN"], $this->expectedCnName)) {
throw new \Exception("Unable to verify certificate issued by Amazon - error with certificate subject");
}
$result = -1;
try {
$result = openssl_verify($this->signatureFields, $signature, $certKey, OPENSSL_ALGO_SHA1);
} catch (\Exception $ex) {
throw new \Exception("Unable to verify signature - error with the verification algorithm", null, $ex);
}
return ($result > 0);
}
/* Extract the mandatory field from the message and return the contents
*
* @param string $fieldName name of the field to extract
*
* @throws Exception if not found
*
* @return string field contents if found
*/
private function getMandatoryField($fieldName)
{
$value = $this->getField($fieldName);
if (is_null($value)) {
throw new \Exception("Error with json message - mandatory field " . $fieldName . " cannot be found");
}
return $value;
}
/* Extract the field if present, return null if not defined
*
* @param string $fieldName name of the field to extract
*
* @return string field contents if found, null otherwise
*/
private function getField($fieldName)
{
if (array_key_exists($fieldName, $this->snsMessage)) {
return $this->snsMessage[$fieldName];
} else {
return null;
}
}
/* returnMessage() - JSON decode the raw [Message] portion of the IPN */
public function returnMessage()
{
return json_decode($this->snsMessage['Message'], true);
}
/* toJson() - Converts IPN [Message] field to JSON
*
* Has child elements
* ['NotificationData'] [XML] - API call XML notification data
* @param remainingFields - consists of remaining IPN array fields that are merged
* Type - Notification
* MessageId - ID of the Notification
* 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);
// Converting to JSON format
$response = json_encode($responseArray);
return $response;
}
/* toArray() - Converts IPN [Message] field to associative array
* @return response in array format
*/
public function toArray()
{
$response = $this->simpleXmlObject();
// Converting the SimpleXMLElement Object to array()
$response = json_encode($response);
$response = json_decode($response, true);
// Merging the remaining fields with the response array
$remainingFields = $this->getRemainingIpnFields();
$response = array_merge($remainingFields,$response);
return $response;
}
/* addRemainingFields() - Add remaining fields to the datatype
*
* Has child elements
* ['NotificationData'] [XML] - API call XML response data
* Convert to SimpleXML element object
* Type - Notification
* MessageId - ID of the Notification
* Topic ARN - Topic of the IPN
* @return response in array format
*/
private function simpleXmlObject()
{
$ipnMessage = $this->returnMessage();
// Getting the Simple XML element object of the IPN XML Response Body
$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']);
$response->addChild('MessageId', $this->snsMessage['MessageId']);
$response->addChild('TopicArn', $this->snsMessage['TopicArn']);
return $response;
}
/* 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'],
'IsSample' =>$ipnMessage['IsSample'],
'SellerId' =>$ipnMessage['SellerId'],
'ReleaseEnvironment' =>$ipnMessage['ReleaseEnvironment'],
'Version' =>$ipnMessage['Version']);
return $remainingFields;
}
}

View File

@ -0,0 +1,86 @@
<?php
namespace PayWithAmazon;
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/* ResponseParser
* Methods provided to convert the Response from the POST to XML, Array or JSON
*/
require_once 'Interface.php';
class ResponseParser implements ResponseInterface
{
public $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']);
// Adding the HttpResponse Status code to the output as a string
$response->addChild('ResponseStatus', $status);
return $response;
}
/* Get the status of the BillingAgreement */
public function getBillingAgreementDetailsStatus($response)
{
$data= new \SimpleXMLElement($response);
$namespaces = $data->getNamespaces(true);
foreach($namespaces as $key=>$value){
$namespace = $value;
}
$data->registerXPathNamespace('GetBA', $namespace);
foreach ($data->xpath('//GetBA:BillingAgreementStatus') as $value) {
$baStatus = json_decode(json_encode((array)$value), TRUE);
}
return $baStatus ;
}
}