【问题标题】:Unable to instantiate paypal sdk for multiple configurations无法为多个配置实例化 paypal sdk
【发布时间】:2021-03-15 05:40:27
【问题描述】:

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

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

我想为每个用户实例化一个 paypal 并返回对象

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 循环中,它将覆盖旧配置。

【问题讨论】:

    标签: node.js paypal-rest-sdk


    【解决方案1】:

    你可以包装到你自己的模块中并导出它,这里的关键是将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 */ })
    

    【讨论】:

    • 在函数中使用 require 是个好方法吗?
    【解决方案2】:

    嗯,我自己想出来的。

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

    此代码取自官方paypal-rest-sdk,原链接here

    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);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 2015-06-29
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多