How to use two stripe keys in app delegate in swift ios

Viewed 425

I want to add two stripe keys to my App delegate field in Swift iOS. I have two stripe accounts and based on conditions I want to do credit/debit card payments. Thanks in advance.

For what I have done is instead of declaring the string keys in App delegate I am declaring the keys in the class itself where I am creating the token for payments like below. I have two classes in each class I am using each key.

@IBAction func submitCard(_ sender: AnyObject) {

    let cardParams = paymentTextField.cardParams
    Stripe.setDefaultPublishableKey("pk_test_1234567899875gh")// example key

    // It takes the card details and creates the token here.

    STPAPIClient.shared().createToken(withCard: cardParams) { token, error in
        guard token != nil else {

           print("Error creating token: %@", error!.localizedDescription);
           return
        }
        print(token)
    }
}

Is this write? or do I need to change the code?

Note: This is not about the environment, but two different stripe accounts.

3 Answers

You can simply create multiple STPAPIClients using different keys and then use them as needed, instead of using the shared instance.

https://stripe.dev/stripe-ios/docs/Classes/STPAPIClient.html#/c:objc(cs)STPAPIClient(im)initWithPublishableKey:

let clientA = STPAPIClient(publishableKey: "pk_123")
let clientB = STPAPIClient(publishableKey: "pk_456")

if usingClientA {
    clientA.createToken(withCard: cardParams) { ... }
} else if usingClientB {
    clientB.createToken(withCard: cardParams) { ... }
}

Also as a general point, you might want to have the public key get returned from an endpoint on your backend server rather than hardcoding into the app, as that makes it easier if you need to change the Stripe account used without going through app review.

Ideally you should use one Stripe account only. And the way you set your publishableKey in your AppDelegate depends on your current environment (i.e. development / production), like so:

let key = isProduction ? "pk_live_TYooMQauvdEDq54NiTphI7jx" : "pk_test_TYooMQauvdEDq54NiTphI7jx"
Stripe.setDefaultPublishableKey(key)

Should you need to set a new key based on "conditions" as what you've mentioned, later on, just set it with the function setDefaultPublishableKey.

You can use this condition in AppDelegate:

#if DEBUG
    Stripe.setDefaultPublishableKey(testKey)
#else
    Stripe.setDefaultPublishableKey(liveKey)
#endif

Result: if you'll use a debug environment, then Stripe will get the test key. In the case of archive and deploy to TestFlight, for example, Stripe will get live keys.

Related