步骤 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),因此将其存储在可以轻松引用的位置。

在第二个订阅步骤中,我们需要根据刚刚创建的计划创建计费协议并执行它以开始处理用户的订阅。