Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift How to get Stripe token?

I want to implement Stripe Payment gateway. And need to generate token and pass it to backend.

private func getToken(){
        let cardParams = STPCardParams()
        cardParams.number = paymentCardTextField?.cardNumber
        cardParams.expMonth = (paymentCardTextField?.expirationMonth)!
        cardParams.expYear = (paymentCardTextField?.expirationYear)!
        cardParams.cvc = paymentCardTextField?.cvc
        STPAPIClient.shared().createToken(withCard: cardParams) { (token: STPToken?, error: Error?) in
            guard let token = token, error == nil else {
                // Present error to user...
                return
            }
            self.dictPayData["stripe_token"] = token.tokenId
            print(self.dictPayData)


        }
    }
like image 553
Rishil Patel Avatar asked Mar 23 '18 06:03

Rishil Patel


1 Answers

Make sure you need to add your Stripe publishableKey (live/test)

in AppDelegate.swift

     import Stripe
       class AppDelegate: UIResponder, UIApplicationDelegate{

       // var navCon: UINavigationController?
        var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application la
             STPPaymentConfiguration.shared().publishableKey = "pk_test_DSFDSFSDFDFSDFSDFDSDSF"

            return true
        }
}

in my PaymentView.swift

Note: Use STPPaymentCardTextFieldDelegate for card validation.

class PaymentView: UIViewController,STPPaymentCardTextFieldDelegate {
    @IBOutlet weak var paymentCardTextField = STPPaymentCardTextField()
}

private func getToken(){
        let cardParams = STPCardParams()
        cardParams.number = paymentCardTextField?.cardNumber
        cardParams.expMonth = (paymentCardTextField?.expirationMonth)!
        cardParams.expYear = (paymentCardTextField?.expirationYear)!
        cardParams.cvc = paymentCardTextField?.cvc
        STPAPIClient.shared().createToken(withCard: cardParams) { (token: STPToken?, error: Error?) in
            guard let token = token, error == nil else {
                // Present error to user...
                return
            }
            self.dictPayData["stripe_token"] = token.tokenId
            print(self.dictPayData)

        }
    }
like image 178
Rishil Patel Avatar answered Nov 11 '22 02:11

Rishil Patel