无法为多个配置实例化 paypal sdk

Unable to instantiate paypal sdk for multiple configurations

我有多个 paypal 配置~15 个用户

[
  ...,
  { environment: "sandbox", accKey: "xxxxx", secretKey: "xxxxxxx" },
  ....  
]

我想为每个用户和return对象实例化一个贝宝

nodejs 的问题是 paypal-rest-sdk 导出默认对象,不像 stripe 导出 stripe

// paypal
const paypal = require("paypal-rest-sdk")
paypal.config({ 
// config goes here
})


// stripe
const { Stripe } = require("stripe")
const stripe = new Stripe("secret key")

问题:如果我将 paypal.configure 包装在 for 循环中,它将覆盖旧配置。

您可以包装到您自己的模块中并导出它,这里的关键是将 paypal 包装到它自己的范围内

// my-paypal-module.js
module.exports = config => {
  const paypal = require("paypal-rest-sdk")
  paypal.configure(config)
  
  return paypal
}


// main-file.js
const Paypal = require('./my-paypal-module')
const paypal = new Paypal({ /* config */ })

嗯,我只是自己想出来的。

在执行任何请求时,函数中有可选的第二个参数,传入新的配置对象将覆盖 .configure 函数设置的旧配置。

此代码取自paypal-rest-sdk官方,原创linkhere

var first_config = {
    'mode': 'sandbox',
    'client_id': '<FIRST_CLIENT_ID>',
    'client_secret': '<FIRST_CLIENT_SECRET>'
};

var second_config = {
    'mode': 'sandbox',
    'client_id': '<SECOND_CLIENT_ID>',
    'client_secret': '<SECOND_CLIENT_SECRET>'
};

//This sets up client id and secret globally
//to FIRST_CLIENT_ID and FIRST_CLIENT_SECRET
paypal.configure(first_config);

var create_payment_json = {
    "intent": "authorize",
    "payer": {
        "payment_method": "paypal"
    },
    "redirect_urls": {
        "return_url": "http://return.url",
        "cancel_url": "http://cancel.url"
    },
    "transactions": [{
        "item_list": {
            "items": [{
                "name": "item",
                "sku": "item",
                "price": "1.00",
                "currency": "USD",
                "quantity": 1
            }]
        },
        "amount": {
            "currency": "USD",
            "total": "1.00"
        },
        "description": "This is the payment description."
    }]
};

// Overriding the default configuration with "second_config"
paypal.payment.create(create_payment_json, second_config, function (error, payment) {
    if (error) {
        throw error;
    } else {
        console.log("Create Payment Response");
        console.log(payment);
    }
});