天天看點

other|2019最新PayPal二代支付接口Smart Payment Buttons開發

在2018年的時候PayPal推出了新一代的支付接口,去年開始測試然後今年正式上線,接着就是市場推廣,幫助老客戶更新及推廣新客戶。新的接口版本是v2 checkout,名字叫smart payment button,簡稱spb。對比v1接口最大的差別主要集中在兩點,一是簡化了支付流程,更便捷。二是優化了信用卡通道,改變了過去信用卡複雜的方式。

這邊接到任務需要開發機遇mangeto1.9和magento2的插件,以便于幫助老客戶更新。于是就花了幾天時間開始研究這個問題,具體過程如下:

1、官方文檔示範及說明:https://developer.paypal.com/docs/checkout/,可以看到大體流程就是通過前台點選請求create api生成訂單然後跳轉登陸客戶授權,授權成功後傳回到api,通過capture擷取交易詳細資訊并入庫;

2、通過composer下載下傳sdk,composer require paypal/paypal-checkout-sdk 1.0.0

github位址:https://github.com/paypal/Checkout-PHP-SDK,建議通過composer下載下傳,下載下傳後的檔案夾是一個vendor,自帶自動加載方法,而git裡面clone下來的之後PayPal的檔案夾。

3、v2 checkou api接口文檔:https://developer.paypal.com/docs/api/orders/v2/

目前通過研究發現,大緻流程基本上是三步,一建立訂單,create order ,二、使用者授權後capture訂單,三、驗證訂單execute并擷取詳細資訊寫入資料庫。

代碼示範如下:

a、html頁面,通過js sdk 建立訂單并capture訂單資訊,傳遞orderId到背景程式:

<!DOCTYPE html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <script
            src="https://www.paypal.com/sdk/js?client-id=*****">
    </script>

</head>
<body>

<div id="paypal-button-container"></div>

<script>
  paypal.Buttons({
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(details) {
        alert('Transaction completed by ' + details.payer.name.given_name);
        // Call your server to save the transaction
        return fetch('execute.php', {
          method: 'post',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify({
            orderID: data.orderID
          })
        });
      });
    }
  }).render('#paypal-button-container');
</script>
 
</body>
           

b、背景接收orderId,并驗證訂單資訊擷取訂單資訊寫入資料庫;

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/28
 * Time: 14:31
 */
namespace Sample;

require __DIR__ . '/vendor/autoload.php';
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
// Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders
// $response->result->id gives the orderId of the order created above
$clientId = "*****";
$clientSecret = "***********";

$environment = new SandBoxEnvironment($clientId, $clientSecret);
$client = new PayPalHttpClient($environment);
$content=file_get_contents("php://input");
$json=json_decode($content,true);
$orderID=$json['orderID'];
file_put_contents("1.txt",$orderID,FILE_APPEND);
$request = new OrdersCaptureRequest($orderID);
$request->prefer('return=representation');
try {
    // Call API with your client and get a response for your call
    $response = $client->execute($request);

    // If call returns body in response, you can get the deserialized version from the result attribute of the response
    print_r($response);
    //驗證通過擷取到訂單的詳細資訊可以寫入到資料庫
}catch (HttpException $ex) {
    echo $ex->statusCode;
    print_r($ex->getMessage());
}
           

通過以上步驟基本就走完了一個訂單的流程。這裡特别說明,前端js和背景程式打通的時候本地測試可能會報錯,出現如下提示:

SSL certificate: unable to get local issuer certificate

解決辦法:

到http://curl.haxx.se/ca/cacert.pem下載下傳pem檔案,并将檔案拷貝到D:\phpStudy\PHPTutorial\cacert.pem

在php.ini

增加

curl.cainfo = "D:\phpStudy\PHPTutorial\cacert.pem"

通過測試發現,spb的主要功能是把create和capture方法通過js sdk的方式內建到了一起,這樣前端可以直接生成訂單,後續隻需要進行驗證即可。以上代碼就是采用這種方式,其實還有另外兩種方式,結合起來彙總如下:

A、create和capture全都通過js sdk實作,然後後端隻需要execute并入庫即可。

B、cteate通過ajax請求php實作并傳回臨時資訊給js,前端接收資訊後跳轉登陸并授權,然後通過js檢測授權後capture訂單Id并傳遞給後端,後端根據Id execute入庫。

C、不走前端,全部後端執行,先create,然後跳轉網址授權,傳回後capture,接着execute。

前端或者後端傳遞的訂單組合參數清單:https://developer.paypal.com/docs/checkout/reference/server-integration/set-up-transaction/#on-the-server,但其中沒有訂單号。

現在依舊存在的幾個問題如下:

1、訂單号的參數怎麼傳遞;

2、消息通知如何擷取,狀态變更;

3、特殊狀态如預授權訂單等設定及處理;