Integrating Stripe in Swift for iOS development

Stripe is payment gateway that can be integrated with any website and mobile apps. In this tutorial we will see a quick and simple integration of Stripe in Swift for iOS development using Stripe documentation for iOS.

201409021233.jpg

This hands on tutorial will help you to familiarise yourself in

  • Validating and creating token using Stripe IOS SDK
  • Installing third party library using Cocoa-pods (Stripe)
  • Calling Objective-C framework in Swift (Objective-C Bridging Headers settings)

Click File menu and select New -> Project

201409021049.jpg

Select Single View Application as the template for the project.

201409021050.jpg

Provide a name for your project and select the language as Swift.

201409021110.jpg

Now close the project in Xcode and launch terminal window.

Setup Stripe using Cocoa-pods

Run the following commands on your terminal window to install Stripe.

[code language=”plain”]sudo gem install cocoapods
pod init[/code]

Edit Podfile under project directory and add pod ‘Stripe’ then execute the below command in Terminal window.

[code language=”plain”]pod install[/code]

Navigate to the project folder and launch the file with extension as workspace. Now you should see the Stripe frameworks included under Pods directory along with your default project files.

201409021131.jpg

Write code to integrate Stripe

Edit ViewController.swift and add the following IBOutlet variable for the button.

[code language=”swift”]@IBOutlet var saveButton: UIButton![/code]

Now add the following variable declaration to ViewController.swift file to hold the instance of STPView class.

[code language=”swift”]var stripeView: STPView = STPView()[/code]

Since the Stripe framework has been written in Objective-C, we need to make sure to add the implementation file as part of the Objective-C bridging Headers under Build Settings.

Select Project folder and navigate to Build Settings. Then use the search field to locate to Objective-C Bridging Header setting.

201409021153.jpg

Then drag and drop the STPView.m file to Object-C Bridging Header section.

201409021155.jpg201409021156.jpg

Update the viewDidLoad function and add the following Stripe integration code. Make sure the ViewController class conforms to STPViewDelegate protocol

[code language=”swift”]class ViewController: UIViewController, STPViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
stripeView = STPView(frame: CGRectMake(15, 20, 290, 55), andKey: )
stripeView.delegate = self
view.addSubview(stripeView)
saveButton.enabled = false
}
}[/code]

 

The above lines of code will add the Stripe control that accepts credit card number, expiry date and code. The save button is by default disabled and will be enabled only after entering valid credit card number. Implement the following function that will be triggered after entering the card details. The boolean parameter in the function will indicate whether the user has entered a valid card information. Based on this value, the save button is enabled or disabled.

[code language=”swift”]func stripeView(view: STPView!, withCard card: PKCard!, isValid valid: Bool) {
if (valid) {
saveButton.enabled = true
} else {
saveButton.enabled = false
}
}[/code]

Add the following IBAction function which will be called on tap of the button. We are using STPView’s createToken function to generate token and a successful token will be written to the console window.

[code language=”swift”]@IBAction func saveButton(sender: AnyObject) {
stripeView.createToken { (stpToken, error) -> Void in
if (error != nil) {
println(error)
} else {
println(stpToken)
}
}[/code]

Navigate to Main.storyboard and add UIButton from object library to ViewController. Centre align the button both horizontally and vertically to the View Controller.

201409021138.jpg

Then use Connection Inspector to connect the button to IBOutlet variable and saveButton function to Tap Up Inside event of the button.

201409021228.jpg

Now build and run the project on simulator and you can use dummy card number 4242 4242 4242 4242 to test your implementation. For more details refer to Stripe Testing Documentation.

Sample Output

[code language=”plain”]Successful token – tok_14YBF42eZvKYlo2CoZtuO3Md (test mode)

Error message – Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x7f9b7147b4a0 {NSUnderlyingError=0x7f9b71786ca0 "The Internet connection appears to be offline.", NSErrorFailingURLStringKey=https://pk_test_6pRNASCoBOKtIshFeQd4XMUh:@api.stripe.com/v1/tokens, NSErrorFailingURLKey=https://pk_test_6pRNASCoBOKtIshFeQd4XMUh:@api.stripe.com/v1/tokens, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=The Internet connection appears to be offline.}[/code]

Download Demo Project from GitHub


Comments

12 responses to “Integrating Stripe in Swift for iOS development”

  1. Hi Ravi,

    I tried integrating Stripe using your code. It shows “STPView.h” not available.

    Also, I was not able to drag and drop. Any other way to do it.

    Appreciate your help.

    Regards,Anand

    1. Can you pls try updating the Objective-C Bridging Header (Under Build Settings) to your currently project folder location.

      eg:- /Users/ravishankar/Downloads/SwiftStripeDemo-master/Pods/Stripe/Stripe/STPView.m

      Regards,
      Ravi

      1. Hi Ravi,

        I tried integrating Stripe using your code. and I have succeed to get a token, But problem is that what i will have to do after it for “Payment charged”

        Thanks
        Regards, Deepak

  2. Thanks Ravi, for the response.

    In the Pod directory I am not able to find STPView. Probably it has changed. Can you tell me Stripe version that you used.

    Also, how will work with PHP.

    I would appreciate if you have any sample app with swift and PHP.

    Regards,
    Anand

    1. Zach Heineman Avatar
      Zach Heineman

      STPView is now part of PaymentKit: https://github.com/stripe/PaymentKit.

  3. Hi Ravi,

    I tried to integrate using Objective C itself. But somehow if fails. I have posted my question in stack overflow. Here is the link. Would you let me know how to fix it.

    http://stackoverflow.com/questions/26823904/integration-of-stripe-with-ios-and-php

    Regards,
    Anand

    1. Can you please try giving the publishable key under Stripe.m, you can get publishable key from Stripe -> Account Settings -> API

      static NSString *defaultKey =

      Since I have used a test card starting with 4242, I get an alert message with “Payment Not Successful”

      Hope this helps.

  4. Brice Amram Avatar
    Brice Amram

    Hi Ravi,
    Many thanks for this tutorial that is helping me a lot! Thanks for putting the time to it.
    I’ve got a comment (1) and a question (2) :

    Everything worked fine 1) provided I did a small adjustment, which might be also useful to our friend Anand who posted earlier here , and 2) until the very last step which is the creation of the token and printing it to the console.

    Starting with my problem/question (2):
    The code builds and runs, I type valid card informations until the saveButton is enabled, but then NOTHING HAPPENS when I click on the saveButton. No error, no token. Nothing is printed on the console. I’ve tried a bunch of things (the action outlet does work so nothing to do with that). Do you think you can help me with that please ?

    Then, my comment (1) is that it seems that stripe has updated their stuff since then. As explained here in the ‘integration’ section (http://cocoadocs.org/docsets/Stripe/1.2/) , the STPView no longer exists and has been replaced in version 1.2.
    So, in order to make this tutorial as it is to work, you just have to replace the reference in the podfile // pod ‘Stripe’ // with // pod ‘Stripe’, ‘1.1.4’ // in order to use the former version of the API that still includes STPView.

    Hope this helps, and that I’ll be able to move on with the token issue thanks to your help on this forum!

    Brice

    1. Thanks Brice for sharing this info. Much Appreciated.

      Regarding the problem you are facing, I just tried again with my code and get a token after entering the valid card details after clicking Save Card Details button. I am using test publishable key with card number as 4242424242424242

      Regards,
      ravi

  5. Garrett M Avatar
    Garrett M

    Hey Ravi,
    I’m new to the site and have a couple questions. I was wondering if you could go over, or point me in the direction, of a peer-to-peer scenario using stripe and the transfer of funds process. Currently, I have a basic understanding of how to route the transaction/funds over to our web server via PHP. But I need to be able to take a small percentage of that transaction, and then route it back to the recipient of the initial payment.

  6. Karthik Kuppili Avatar
    Karthik Kuppili

    I want to use stripe in my project… and i am unable to follow some of the steps…. Can i have a brief description about what is happening there?

  7. Swapnesh Porwal Avatar
    Swapnesh Porwal

    Hello sir, i want to use stripe in my ios application but i am using firebase for backhand so can you please help me out for this. because i am just come to in this field and less knowledge of stripe and firebase.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.