步驟 1 使用開票計劃建立訂閱模型(節點示例)
在為使用者建立訂閱時,首先需要建立並啟用使用者隨後使用結算協議訂閱的結算方案。建立訂閱的完整過程詳見本主題的註釋。
在此示例中,我們將使用 PayPal Node SDK 。你可以使用以下命令從 NPM 獲取它:
npm install paypal-rest-sdk
在我們的 .js 檔案中,我們首先設定我們的 SDK 配置,其中包括新增 SDK 的要求,定義我們的客戶端 ID 和建立應用程式的祕密,然後為沙箱環境配置 SDK。
var paypal = require('paypal-rest-sdk');
var clientId = 'YOUR CLIENT ID';
var secret = 'YOUR SECRET';
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': clientId,
'client_secret': secret
});
接下來,我們需要設定兩個 JSON 物件。billingPlanAttribs
物件包含我們可以訂閱使用者的計費計劃的資訊和付款明細,billingPlanUpdateAttributes
物件包含用於將計費計劃設定為活動狀態的值,允許使用它。
var billingPlanAttribs = {
"name": "Food of the World Club Membership: Standard",
"description": "Monthly plan for getting the t-shirt of the month.",
"type": "fixed",
"payment_definitions": [{
"name": "Standard Plan",
"type": "REGULAR",
"frequency_interval": "1",
"frequency": "MONTH",
"cycles": "11",
"amount": {
"currency": "USD",
"value": "19.99"
}
}],
"merchant_preferences": {
"setup_fee": {
"currency": "USD",
"value": "1"
},
"cancel_url": "http://localhost:3000/cancel",
"return_url": "http://localhost:3000/processagreement",
"max_fail_attempts": "0",
"auto_bill_amount": "YES",
"initial_fail_amount_action": "CONTINUE"
}
};
var billingPlanUpdateAttributes = [{
"op": "replace",
"path": "/",
"value": {
"state": "ACTIVE"
}
}];
在 billingPlanAttribs
物件中,有一些相關的資訊:
- name / description / type :描述計劃的基本可視資訊,以及計劃的型別。
- payment_definitions :有關計劃應如何運作和計費的資訊。有關欄位的更多細節在這裡 。
- merchant_preferences :訂閱計劃的附加費用結構,重定向 URL 和設定。有關欄位的更多細節在這裡 。
有了這些物件,我們現在可以建立並啟用開票計劃。
paypal.billingPlan.create(billingPlanAttribs, function (error, billingPlan){
if (error){
console.log(error);
throw error;
} else {
// Activate the plan by changing status to Active
paypal.billingPlan.update(billingPlan.id, billingPlanUpdateAttributes, function(error, response){
if (error) {
console.log(error);
throw error;
} else {
console.log(billingPlan.id);
}
});
}
});
我們稱 billingPlan.create(...)
,傳入我們剛剛建立的 billingPlanAttribs
物件。如果成功,則返回物件將包含有關計費計劃的資訊。為了示例,我們只需要使用結算方案 ID 來啟用使用計劃。
接下來,我們呼叫 billingPlan.update(...)
,傳遞計費計劃 ID 和我們之前建立的 billingPlanUpdateAttributes
物件。如果成功,我們的結算方案現已啟用並可以使用。
為了在此計劃中為使用者(或多個使用者)建立訂閱,我們需要引用計費方案 ID(上面的 billingPlan.id
),因此將其儲存在可以輕鬆引用的位置。
在第二個訂閱步驟中,我們需要根據剛剛建立的計劃建立計費協議並執行它以開始處理使用者的訂閱。