Integrating Stripe in Swift with custom view

In this tutorial I am gonna integrate with Stripe without using STPView.

1) Start a new project

new-proj new-proj2

Make sure you select Swift as Language.

2) Add Stripe Framework to your Project

Follow the instructions provided by stripe to add framework to your project using Cocoapods.

If you decided not to use pods follow these instructions

Clone the iOS library repository directly:


git clone https://github.com/stripe/stripe-ios.git
  • In the menubar, click on ‘File’ then ‘Add files to “Project”…’.
  • Select the ‘Stripe’ directory in the downloaded repository.
  • Make sure ‘Copy items into destination group’s folder (if needed)’ is checked.
  • Click ‘Add’.
  • In your project settings, go to the “Build Phases” tab, and make sure Foundation.framework, Security.framework, and PassKit.framework are included in the “Link Binary With Libraries” section. If you’re targeting versions of iOS before iOS8, make sure PassKit.framework is listed as “Optional.”

copy-stripeadd-framework  setpasskit

 

Since Stripe framework is written in Objective-c we need to add Bridging-Header file to import files into project.

Create new file by selecting source as header file.header

 

Name the file YourProject-Bridging-Header, once file is created delete everything in that file and replace it with following code.


#import "Stripe.h"
@import Foundation;

 

After that switch to your project Build Settings and find Swift Compiler – Code Generation, and next to Objective-C Bridging Header add the path to your bridging header file, from the project’s root folder. So it will be YourProject/YourProject-Bridging-Header.h
brheader

 

3) Setup Stripe Account 

If you already don’t have a stripe account then create one at stripe.com, and get your publishable API key.

4) Create your credit card view

Build this using Interface builder.

creditcardview

 

Add following outlets in your ViewController file and hook it up with the view. Also hookup getStripeToken function with payButton.


    @IBOutlet var email: UITextField!
    @IBOutlet var cardNum: UITextField!
    @IBOutlet var exp: UITextField!
    @IBOutlet var cvc: UITextField!
    @IBOutlet var payButton: UIButton!
    
    @IBAction func getStripeToken(sender: AnyObject){

    }

Now let goto AppDelegate.swift file and add following lines and update application didFinishLaunchingWithOptions function



    
    let StripePublishableKey = "pk_test_your_key"


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            Stripe.setDefaultPublishableKey(StripePublishableKey)

        return true
    }

5) Get token from stripe

Lets update getStripeToken method to send data to stripe


@IBAction func getStripeToken(sender: AnyObject){
        let creditCard = STPCard() //creating a stripe card object
        creditCard.number = cardNum.text
        creditCard.cvc = cvc.text
        
        //extracting month and year values from expiry date 
        if (!exp.text.isEmpty){
            let expArr = exp.text.componentsSeparatedByString("/")
            if (expArr.count > 1)
            {
                var expMonth: NSNumber = expArr[0].toInt()!
                var expYear: NSNumber = expArr[1].toInt()!
                
                creditCard.expMonth = expMonth.unsignedLongValue 
                creditCard.expYear = expYear.unsignedLongValue
            }
        }
        
        var error: NSError?
        if (creditCard.validateCardReturningError(&error)){
            var stripeError: NSError!
            Stripe.createTokenWithCard(creditCard, completion: { (token, stripeError) -> Void in
                if (stripeError != nil){
                    println("there is error");
                }
                else{
                    self.cardNum.text = ""
                    self.exp.text = ""
                    self.cvc.text = ""
                    self.email.text = ""
                    
                     //shows your stripe token 
                    var alert = UIAlertController(title: "Your stripe token is: " + token.tokenId, message: "", preferredStyle: UIAlertControllerStyle.Alert)
                    var defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
                    alert.addAction(defaultAction)
                    self.presentViewController(alert, animated: true, completion: nil)
                }
            })
        }else{
           //shows alert if information is not correct
            var alert = UIAlertController(title: "Please enter valid credit card details", message: "", preferredStyle: UIAlertControllerStyle.Alert)
            var defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
            alert.addAction(defaultAction)
            self.presentViewController(alert, animated: true, completion: nil)
            
        }

        
    }

iOS Simulator Screen Shot Jan 3, 2015, 11.19.26 PM

iOS Simulator Screen Shot Jan 3, 2015, 11.19.41 PM

So now you have your stripe token, you can send it some backend to process the payment.

You can download this project from github

Advertisements

6 thoughts on “Integrating Stripe in Swift with custom view

  1. Hi Megha,
    Great tutorial, I have followed every step in this tutorial, but I am getting one error – In create token with card function completion is unavailable. Can you please give some advice on this?

    Thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s