amzn / login-and-pay-with-amazon-sdk-php
Requires
- php: >=5.5.0
- ext-curl: *
Requires (Dev)
- phpunit/phpunit: ^4
README
Amazon Pay API 集成
要求
PHP 5.3 和 5.4 的支持正在被弃用。SDK 在这些旧环境中可以正常工作,但未来的版本可能不支持。我们鼓励商家尽快迁移到 PHP 的新版本。
文档
集成步骤如下
示例
快速入门
客户端以以下格式接收参数
- 关联数组
- 配置信息的 JSON 文件路径。
使用 Composer 安装
composer require amzn/amazon-pay-sdk-php
目录结构
.
├── composer.json - Configuration for composer
├── LICENSE.txt
├── NOTICE.txt
├── AmazonPay
│ ├── Client.php - Main class with the API calls
│ ├── ClientInterface.php - Shows the public function definitions in Client.php
│ ├── HttpCurl.php - Client class uses this file to execute the GET/POST
│ ├── HttpCurlInterface.php - Shows the public function definitions in the HttpCurl.php
│ ├── IpnHandler.php - Class handles verification of the IPN
│ ├── IpnHandlerInterface.php - Shows the public function definitions in the IpnHandler.php
│ ├── Regions.php - Defines the regions that is supported
│ ├── ResponseParser.php - Parses the API call response
│ └── ResponseInterface.php - Shows the public function definitions in the ResponseParser.php
├── README.md
└── UnitTests
├── ClientTest.php
├── config.json
├── coverage.txt
├── IpnHandlerTest.php
└── Signature.php
参数列表
必选参数
| 参数 | 变量名 | 值 |
|---|---|---|
| 商户 ID | merchant_id |
默认值: null |
| 访问密钥 | access_key |
默认值: null |
| 密钥 | secret_key |
默认值: null |
| 区域 | region |
默认值: null其他: us,de,uk,jp |
可选参数
| 参数 | 变量名 | 值 |
|---|---|---|
| 货币代码 | currency_code |
默认值: null其他: USD,EUR,GBP,JPY |
| 环境 | sandbox |
默认值: false其他: true |
| 平台 ID | platform_id |
默认值: null |
| CA 证书包文件 | cabundle_file |
默认值: null |
| 应用程序名称 | application_name |
默认值: null |
| 应用程序版本 | application_version |
默认值: null |
| 代理主机 | proxy_host |
默认值: null |
| 代理端口 | proxy_port |
默认值: -1 |
| 代理用户名 | proxy_username |
默认值: null |
| 代理密码 | proxy_password |
默认值: null |
| LWA 客户端 ID | client_id |
默认值: null |
| 处理节流 | handle_throttle |
默认值: true其他: false |
设置配置
您的 Amazon Pay 密钥可在您的卖家中心账户中找到
在创建客户端对象时设置配置
<?php namespace AmazonPay; require_once 'Client.php'; // or, instead of using require_once, you can use the phar file instead // include 'amazon-pay.phar'; // PHP Associative array $config = array( 'merchant_id' => 'YOUR_MERCHANT_ID', 'access_key' => 'YOUR_ACCESS_KEY', 'secret_key' => 'YOUR_SECRET_KEY', 'client_id' => 'YOUR_LOGIN_WITH_AMAZON_CLIENT_ID', 'region' => 'REGION'); // or, instead of setting the array in the code, you can // initialze the Client by specifying a JSON file // $config = 'PATH_TO_JSON_FILE'; // Instantiate the client class with the config type $client = new Client($config);
在沙盒模式下测试
如果没有指定,沙盒参数默认为false
<?php namespace AmazonPay; $config = array( 'merchant_id' => 'YOUR_MERCHANT_ID', 'access_key' => 'YOUR_ACCESS_KEY', 'secret_key' => 'YOUR_SECRET_KEY', 'client_id' => 'YOUR_LOGIN_WITH_AMAZON_CLIENT_ID', 'region' => 'REGION', 'sandbox' => true); $client = new Client($config); // Also you can set the sandbox variable in the config() array of the Client class by $client->setSandbox(true);
设置代理值
可以使用以下setter在实例化客户端对象后设置代理参数
$proxy = array(); $proxy['proxy_user_host'] // Hostname for the proxy $proxy['proxy_user_port'] // Hostname for the proxy $proxy['proxy_user_name'] // If your proxy requires a username $proxy['proxy_user_password'] // If your proxy requires a password $client->setProxy($proxy);
发起API调用
以下是如何发起GetOrderReferenceDetails API调用的示例
<?php namespace AmazonPay; $requestParameters = array(); // AMAZON_ORDER_REFERENCE_ID is obtained from the Amazon Pay Address/Wallet widgets // ACCESS_TOKEN is obtained from the GET parameter from the URL. // Required Parameter $requestParameters['amazon_order_reference_id'] = 'AMAZON_ORDER_REFERENCE_ID'; // Optional Parameter $requestParameters['address_consent_token'] = 'ACCESS_TOKEN'; $requestParameters['mws_auth_token'] = 'MWS_AUTH_TOKEN'; $response = $client->getOrderReferenceDetails($requestParameters);
有关解析API响应的信息,请参阅API响应部分。
以下是如何发起GetMerchantAccountStatus API调用的示例
$requestParameters = array(); // Optional Parameter $requestParameters['mws_auth_token'] = 'MWS_AUTH_TOKEN'; $response = $client->getMerchantAccountStatus($requestParameters); echo $response->toXml() . "\n"; // Sample Response <GetMerchantAccountStatusResponse xmlns="http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01"> <GetMerchantAccountStatusResult> <AccountStatus>ACTIVE</AccountStatus> </GetMerchantAccountStatusResult> <ResponseMetadata> <RequestId>b0a141f7-712a-4830-8014-2aa0c446b04e</RequestId> </ResponseMetadata> </GetMerchantAccountStatusResponse>
有关解析API响应的信息,请参阅API响应部分。
以下是如何发起ListOrderReference API调用的示例
$requestParameters = array(); // Required Parameter $configArray['query_id'] = 'SELLER_ORDER_ID'; $configArray['query_id_type'] = 'SellerOrderId'; // Optional Parameter $requestParameters['mws_auth_token'] = 'MWS_AUTH_TOKEN'; $configArray['page_size'] = "1"; $response = $client->listOrderReference($requestParameters); echo $response->toXml() . "\n"; // Sample Response <ListOrderReferenceResponse xmlns="http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01"> <ListOrderReferenceResult> <OrderReferenceList> <OrderReference> <ReleaseEnvironment>Sandbox</ReleaseEnvironment> <OrderReferenceStatus> <LastUpdateTimestamp>2018-08-06T22:45:37.314Z</LastUpdateTimestamp> <State>Open</State> </OrderReferenceStatus> <AmazonOrderReferenceId>S01-6649662-0708590</AmazonOrderReferenceId> <CreationTimestamp>2018-08-06T22:45:28.203Z</CreationTimestamp> <SellerOrderAttributes> <StoreName>PHP SDK Test goGetOrderReferenceDetails</StoreName> <CustomInformation>PHP SDK Custom Information Testing</CustomInformation> <SellerOrderId>PHP SDK ID# 12345</SellerOrderId> </SellerOrderAttributes> <OrderTotal> <CurrencyCode>USD</CurrencyCode> <Amount>0.01</Amount> </OrderTotal> </OrderReference> </OrderReferenceList> <NextPageToken>eyJuZXh0UGFn...=</NextPageToken> </ListOrderReferenceResult> <ResponseMetadata> <RequestId>5749768d-307b-493b-90b0-8b5b9f2ea436</RequestId> </ResponseMetadata> </ListOrderReferenceResponse>
有关解析API响应的信息,请参阅API响应部分。
以下是如何发起ListOrderReferenceByNextToken API调用的示例
$requestParameters = array(); // Required Parameter $configArray['next_page_token'] = "NEXT_PAGE_TOKEN"; $response = $client->listOrderReferenceByNextToken($requestParameters); echo $response->toXml() . "\n"; // Sample Response <ListOrderReferenceByNextTokenResponse xmlns="http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01"> <ListOrderReferenceByNextTokenResult> <OrderReferenceList> <OrderReference> <ReleaseEnvironment>Sandbox</ReleaseEnvironment> <OrderReferenceStatus> <LastUpdateTimestamp>2018-08-06T22:42:50.191Z</LastUpdateTimestamp> <State>Open</State> </OrderReferenceStatus> <AmazonOrderReferenceId>S01-1662310-7599388</AmazonOrderReferenceId> <CreationTimestamp>2018-08-06T22:42:35.904Z</CreationTimestamp> <SellerOrderAttributes> <StoreName>PHP SDK Test goGetOrderReferenceDetails</StoreName> <CustomInformation>PHP SDK Custom Information Testing</CustomInformation> <SellerOrderId>PHP SDK ID# 12345</SellerOrderId> </SellerOrderAttributes> <OrderTotal> <CurrencyCode>USD</CurrencyCode> <Amount>0.01</Amount> </OrderTotal> </OrderReference> </OrderReferenceList> <NextPageToken>eyJuZXh0UGFnZVRva2VuIjoiQUFBQUFBQUFBQ...</NextPageToken> </ListOrderReferenceByNextTokenResult> <ResponseMetadata> <RequestId>8e06c852-4072-4cfb-99a3-060ec1ef7be8</RequestId> </ResponseMetadata> </ListOrderReferenceByNextTokenResponse>
有关解析API响应的信息,请参阅API响应部分。
IPN处理
- 要成功接收IPN,您需要在您的域上有一个有效的SSL。
- 您可以通过以下方式设置通知端点:(a) 使用卖家中心集成设置页面中的设置选项卡,或者(b) 使用SetMerchantNotificationConfiguration API调用。
- IpnHandler.php类处理验证IPN的源和数据
将以下代码添加到任何文件中,并通过访问设置选项卡中的集成设置页面,将文件的URL设置为Merchant/Integrator URL。
<?php namespace AmazonPay; require_once 'IpnHandler.php'; // Get the IPN headers and Message body $headers = getallheaders(); $body = file_get_contents('php://input'); // Create an object($ipnHandler) of the IpnHandler class $ipnHandler = new IpnHandler($headers, $body);
有关解析IPN响应的信息,请参阅IPN响应部分。
使用SetMerchantNotificationConfiguration API设置通知端点
$client = new AmazonPay\Client($config); // possible array values: ALL, ORDER_REFERENCE, PAYMENT_AUTHORIZE, PAYMENT_CAPTURE, PAYMENT_REFUND, BILLING_AGREEMENT, CHARGEBACK_DETAILED $notificationConfiguration['https://dev.null/ipn/onetime'] = array('ORDER_REFERENCE', 'PAYMENT_AUTHORIZE', 'PAYMENT_CAPTURE'); $notificationConfiguration['https://dev.null/ipn/recurring'] = array('BILLING_AGREEMENT'); $notificationConfiguration['https://dev.null/ipn/refunds'] = array('PAYMENT_REFUND', 'CHARGEBACK_DETAILED'); $requestParameters['notification_configuration_list'] = $notificationConfiguration; // or, if you prefer all IPNs come to the same endpoint, do this one-liner instead: // $requestParameters['notification_configuration_list'] = array('https://dev.null/ipn' => array('ALL')); // if you are calling on behalf of another merhcant using delegated access, be sure to set the merchant ID and auth token: // $requestParameters['merchant_id'] = 'THE_MERCHANT_ID'; // $requestParameters['mws_auth_token'] = 'THE_MWS_AUTH_TOKEN'; $response = $client->setMerchantNotificationConfiguration($requestParameters); if ($response->toArray()['ResponseStatus'] !== '200') { print "error occured calling API"; } // to troubleshoot, you can call GetMerchantNotificationConfiguration to view current IPN settings $response = $client->getMerchantNotificationConfiguration($requestParameters); print $response->toXml();
便捷方法
计费方法
计费方法结合以下API调用
标准支付/定期支付
- SetOrderReferenceDetails / SetBillingAgreementDetails
- ConfirmOrderReference / ConfirmBillingAgreement
- Authorize / AuthorizeOnBillingAgreement
对于标准支付,第一个charge调用将发起SetOrderReferenceDetails、ConfirmOrderReference、Authorize API调用。对于同一Order Reference ID的后续charge方法调用将仅发起Authorize调用。
对于定期支付,第一个charge调用将发起SetBillingAgreementDetails、ConfirmBillingAgreement、AuthorizeOnBillingAgreement API调用。对于同一Billing Agreement ID的后续charge方法调用将仅发起AuthorizeOnBillingAgreement调用。
立即捕获对于数字商品可以设置为
true。对于实体商品,强烈建议将立即捕获设置为false,并在货物发出后通过发起captureAPI调用来捕获金额。
| 参数 | 变量名 | 必填 | 值 |
|---|---|---|---|
| 亚马逊参考ID | amazon_reference_id |
是 | OrderReference ID(以P01或S01开头)或Billing Agreement ID( 以B01或C01开头) |
| 亚马逊订单参考ID | amazon_order_reference_id |
否 | OrderReference ID(以P01或S01开头),如果没有提供亚马逊参考ID |
| 亚马逊账单协议ID | amazon_billing_agreement_id |
否 | Billing Agreement ID(以B01或C01开头),如果没有提供亚马逊参考ID |
| 商家ID | merchant_id |
否 | 从Client.php中的配置数组中获取的值 |
| 计费金额 | charge_amount |
是 | 需要捕获的金额。 对应API调用变量 amount、authorization_amount |
| 货币代码 | currency_code |
否 | 如果没有提供值,则从Client.php中的配置数组中取值 |
| 授权参考ID | authorization_reference_id |
是 | 需要传递的唯一字符串 |
| 交易超时 | transaction_timeout |
否 | 授权超时 - 默认为1440分钟 |
| 立即捕获 | capture_now |
否 | 当设置为true时,将自动捕获付款。默认为false |
| 收费备注 | charge_note |
否 | 注意将发送给买家。 对应API调用变量 seller_note、seller_authorization_note |
| 收费订单ID | charge_order_id |
否 | 提供的自定义订单ID 对应API调用变量 seller_order_id、seller_billing_agreement_id |
| 店铺名称 | store_name |
否 | 店铺名称 |
| 平台 ID | platform_id |
否 | 解决方案提供商的平台ID |
| 自定义信息 | custom_information |
否 | 任何自定义字符串 |
| MWS授权令牌 | mws_auth_token |
否 | 如果API调用代表卖家进行,则需要MWS授权令牌 |
| ExpectImmediateAuthorization | expect_immediate_authorization |
否 | 将值设置为true时,如果60分钟内没有触发授权,将自动关闭OrderReferenceObject |
// Create an array that will contain the parameters for the charge API call $requestParameters = array(); // Adding the parameters values to the respective keys in the array $requestParameters['amazon_reference_id'] = 'AMAZON_REFERENCE_ID'; // Or // If $requestParameters['amazon_reference_id'] is not provided, // either one of the following ID input is needed $requestParameters['amazon_order_reference_id'] = 'AMAZON_ORDER_REFERENCE_ID'; $requestParameters['amazon_billing_agreement_id'] = 'AMAZON_BILLING_AGREEMENT_ID'; $requestParameters['seller_id'] = null; $requestParameters['charge_amount'] = '100.50'; $requestParameters['currency_code'] = 'USD'; $requestParameters['authorization_reference_id'] = 'UNIQUE STRING'; $requestParameters['transaction_timeout'] = 0; $requestParameters['capture_now'] = false; //true for Digital goods $requestParameters['charge_note'] = 'Example item note'; $requestParameters['charge_order_id'] = '1234-Example-Order'; $requestParameters['store_name'] = 'Example Store'; $requestParameters['platform_Id'] = null; $requestParameters['custom_information'] = 'Any_Custom_String'; $requestParameters['mws_auth_token'] = null; // Get the Authorization response from the charge method $response = $client->charge($requestParameters);
有关解析API响应的信息,请参阅API响应部分。
获取配置文件信息(getUserInfo方法)
- 使用按钮小部件返回的访问令牌从亚马逊获取用户的配置文件信息。
- 当用户登录到网站时,授权服务器会授予访问令牌。
- 访问令牌针对客户端、用户和访问范围是特定的。客户端必须使用访问令牌来检索客户配置文件数据。
| 参数 | 变量名 | 必填 | 值 |
|---|---|---|---|
| 访问令牌 | access_token |
是 | 从URL中作为GET参数检索 |
| 区域 | region |
是 | 默认:null其他: us、de、uk、jp值在config['region']数组中设置 |
| LWA 客户端 ID | client_id |
是 | 默认:null 值应在配置数组中设置 |
<?php namespace AmazonPay; // config array parameters that need to be instantiated $config = array( 'client_id' => 'YOUR_LWA_CLIENT_ID', 'region' => 'REGION'); $client = new Client($config); // Client ID can also be set using the setter function setClientId($client_id) $client->setClientId(‘YOUR_LWA_CLIENT_ID’); // Get the Access Token from the URL $access_token = 'ACCESS_TOKEN'; // Calling the function getUserInfo with the access token parameter returns object $userInfo = $client->getUserInfo($access_token); // Buyer name $userInfo['name']; // Buyer Email $userInfo['email']; // Buyer User Id $userInfo['user_id'];
响应解析
响应以3种格式提供
- XML/原始响应
- 关联数组
- JSON格式
API响应
// Returns an object($response) of the class ResponseParser.php $response = $client->getOrderReferenceDetails($requestParameters); // XML response $response->toXml(); // Associative array response $response->toArray(); // JSON response $response->toJson();
IPN响应
$ipnHandler = new IpnHandler($headers, $body); // Raw message response $ipnHandler->returnMessage(); // Associative array response $ipnHandler->toArray(); // JSON response $ipnHandler->toJson();
日志记录
SDK日志记录经过清理的请求和响应可以与任何PSR-3兼容的记录器(如Monolog)一起使用。
API响应
namespace AmazonPay; require 'vendor/autoload.php'; include 'amazon-pay.phar'; use Monolog\Logger; use Monolog\Handler\StreamHandler; date_default_timezone_set('America/Los_Angeles'); $log = new Logger('TestSDK'); $log->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG)); $client = new Client('us.config'); $client->setLogger($log); $response = $client->getServiceStatus();