Android 步驟 3 節點伺服器獲取訪問令牌程序付款

PayPal Developer Github 儲存庫中提供了此應用程式的完整示例程式碼(Android +節點伺服器)。

從步驟 2 開始,已經在/fpstore 端點向我們的伺服器發出非同步請求,並傳遞身份驗證程式碼和後設資料 ID。我們現在需要為令牌交換這些令牌以完成請求並處理將來的付款。

首先,我們設定配置變數和物件。

var bodyParser = require('body-parser'),
    http = require('http'),
    paypal = require('paypal-rest-sdk'),
    app = require('express')();

var client_id = 'YOUR APPLICATION CLIENT ID';
var secret = 'YOUR APPLICATION SECRET';

paypal.configure({
    'mode': 'sandbox',
    'client_id': client_id,
    'client_secret': secret
});

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());

現在我們設定一條 Express 路由,它將監聽從 Android 程式碼傳送到/fpstore 端點的 POST 請求。

我們在這條路線上做了很多事情:

  • 我們從 POST 正文中捕獲身份驗證程式碼和後設資料 ID。
  • 然後我們向 generateToken() 發出請求,通過程式碼物件。如果成功,我們將獲得可用於建立付款的令牌。
  • 接下來,為將來的付款建立配置物件,併傳送對 payment.create(...) 的請求,傳遞未來的付款和付款配置物件。這會產生未來的付款。
app.post('/fpstore', function(req, res){
    var code = {'authorization_code': req.body.code};
    var metadata_id = req.body.metadataId;
    
    //generate token from provided code
    paypal.generateToken(code, function (error, refresh_token) {
        if (error) {
            console.log(error);
            console.log(error.response);
        } else {
            //create future payments config 
            var fp_config = {'client_metadata_id': metadata_id, 'refresh_token': refresh_token};

            //payment details
            var payment_config = {
                "intent": "sale",
                "payer": {
                    "payment_method": "paypal"
                },
                "transactions": [{
                    "amount": {
                        "currency": "USD",
                        "total": "3.50"
                    },
                    "description": "Mesozoic era monster toy"
                }]
            };

            //process future payment
            paypal.payment.create(payment_config, fp_config, function (error, payment) {
                if (error) {
                    console.log(error.response);
                    throw error;
                } else {
                    console.log("Create Payment Response");
                    console.log(payment);
                    
                    //send payment object back to mobile
                    res.send(JSON.stringify(payment));
                }
            });
        }
    });
});

最後,我們建立伺服器以偵聽埠 3000。

//create server
http.createServer(app).listen(3000, function () {
   console.log('Server started: Listening on port 3000');
});