Search code examples
node.jspaypal-rest-sdk

Unable to instantiate paypal sdk for multiple configurations


I have multiple paypal configurations ~15 users

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

I want to instantiate a paypal for each user and return the object

The problem with nodejs is that paypal-rest-sdk export default object, unlike stripe that export stripe

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


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

PROBLEM: If I will wrap paypal.configure in for-loop it will overwrite the old config.


Solution

  • Well I figured it out myself only.

    While executing any request, there is optional second parameter in the functions, passing in new configuration object would override the old configuration set by .configure function.

    This code has been taken from the official paypal-rest-sdk, original link 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);
        }
    });