A blog all about iOS development, Swift tutorials, Xcode tutorials, and other technology related news and updates.


Wednesday, 13 September 2017

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

Hey everyone, In today's post, we'll learn about how to integrate PayPal SDK in iOS apps. These days, there's a huge increase in the eCommerce business. With this increase, there's also getting a high demand of eCommerce mobile apps. The most important part of any eCommerce mobile app is the payment processing through a secure payment gateway. Without any secure payment gateway, no user will trust on your mobile app and hence no one wants to use their payment methods with your app. So, a secure and reliable payment gateway is must for every eCommerce mobile app. And when it comes to reliability and security who can ever forget PayPal ???
So, In this tutorial, I'll guide you through a step by step approach to integrate PayPal Payment Gateway into any iOS application using Swift as the language. I hope you'll like it.

And Yes, Bring yourself a cup of coffee, this tutorial is going to take some of your time & efforts too. 😊

We'll follow a Step By Step Process to integrate PayPal as Payment Gateway in our iOS app. So, below are steps which we'll cover one by one for PayPal integration:
  1. Setup Xcode Project
  2. Install PayPal Pods
  3. Configuring PayPal Developer Account
  4. Write Some Code
  5. Run Your App and Start Accepting Payments
That's all to follow..

So, without any delay, let's start with Step number 1.

STEP 1: Setup Xcode Project

First of all, open your Xcode project and create a single view application. Give some name to your project and click Next. 

Once you're in your project environment, drag and drop a button on your storyboard and give it some name like "Proceed To Payment". Add some constraint on this button and create its action as shown in the picture below:

So, once our Xcode project setup is done. We can proceed to our next step which is installing PayPal Pods into our project.

STEP 2: Install PayPal Pods

For installing PayPal pods into our project, we need to open our terminal and write some commands there. First open up the terminal and go to your project directory by giving following command in the terminal:

cd <path of your project> 

Example: cd /users/Bhanu/Desktop/Projects/PayPalDemoApp

After giving this command, you need to give one more command

pod init

This command will create a podfile in your project folder. So, first close your open project and open this podfile. Here, you need to write this line below < target 'PayPalDemoApp' do >:

pod 'PayPal-iOS-SDK'

Your file will look like this:

Now, run this command in your terminal:

pod install

After giving this command, it will take some time to install the PayPal pods in your project. So, wait for some time. Once pods got installed, your terminal screen will look like this:

After this setup, close the terminal and go to your projects folder. Reopen your project but make sure to open .xcworkspace and not the .xcodeproj  

Now, In your project's Build Phases, link your project with these 9 libraries:
  • Accelerate.framework
  • AudioToolBox.framework
  • AVFoundation.framework
  • CoreLocation.framework
  • CoreMedia.framework
  • MessageUI.framework
  • MobileCoreServices.framework
  • SystemConfiguration.framework
  • SafariServices.framework
After adding these libraries, your build phase screen will look like this:

Since, PayPal is written in Objective C, so we need to include Objective C Bridging Header. To do this, Add a new Objective C file in your project. Make sure to add Bridging Header file as well when its asked by Xcode. It populates automatically when you create your objective C file.

After adding, delete the .m file and open your bridging header (.h) file. copy and paste the following line in this file:

#import "PayPalMobile.h"

Rest, leave it blank.

Now, open your AppDelegate.swift file and add this line of code in its first application function i.e.:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //TODO: - Enter your credentials
        PayPalMobile .initializeWithClientIds(forEnvironments: [PayPalEnvironmentProduction: "YOUR_CLIENT_ID_FOR_PRODUCTION",
                                                                PayPalEnvironmentSandbox: "YOUR_CLIENT_ID_FOR_SANDBOX"])

        return true

Here, we need to add client ID for production and sandbox environments. And this is where our Step 3 starts. 

STEP 3: Configuring PayPal Developer Account

So here in this step, first we need to signup for PayPal’s Developer Account using this link: https://developer.paypal.com

Once you’re logged into your PayPal account. Go to your dashboard and scroll down until you found Rest API Apps. Click on Create App.

Here, Write your app name and click on Create App.

Once you click on Create App button, it will take you to other screen where you can get your sandbox account and client ID.

Now, copy the Sandbox Account & Client ID and paste it in your AppDelegate.swift file as shown in picture below:

After this, let's do some coding stuff. 

STEP 4: Write Some Code

Now, let's jump into the coding part. So, open your ViewController.swift file and add following lines of code in it:

var environment:String = PayPalEnvironmentNoNetwork {
        willSet(newEnvironment) {
            if (newEnvironment != environment) {
                PayPalMobile.preconnect(withEnvironment: newEnvironment)


Also, add one PayPal variable here:

var payPalConfig = PayPalConfiguration()

Now, in your viewDidLoad() method, add following code:

    override func viewDidLoad() {
        // Set up payPalConfig
        payPalConfig.acceptCreditCards = false
        payPalConfig.merchantName = "BREWIT 9"  //Give your company name here.
        payPalConfig.merchantPrivacyPolicyURL = URL(string: "https://www.paypal.com/webapps/mpp/ua/privacy-full")
        payPalConfig.merchantUserAgreementURL = URL(string: "https://www.paypal.com/webapps/mpp/ua/useragreement-full")
        //This is the language in which your paypal sdk will be shown to users.
        payPalConfig.languageOrLocale = Locale.preferredLanguages[0]
        //Here you can set the shipping address. You can choose either the address associated with PayPal account or different address. We'll use .both here.
        payPalConfig.payPalShippingAddressOption = .both;

Now, add following lines of code under your Payment button function:

@IBAction func paymentBtn(_ sender: Any) {
        //These are the items choosen by user, for example
        let item1 = PayPalItem(name: "Old jeans with holes", withQuantity: 2, withPrice: NSDecimalNumber(string: "84.99"), withCurrency: "USD", withSku: "Hip-0037")
        let item2 = PayPalItem(name: "Free rainbow patch", withQuantity: 1, withPrice: NSDecimalNumber(string: "0.00"), withCurrency: "USD", withSku: "Hip-00066")
        let item3 = PayPalItem(name: "Long-sleeve plaid shirt (mustache not included)", withQuantity: 1, withPrice: NSDecimalNumber(string: "37.99"), withCurrency: "USD", withSku: "Hip-00291")
        let items = [item1, item2, item3]
        let subtotal = PayPalItem.totalPrice(forItems: items) //This is the total price of all the items
        // Optional: include payment details
        let shipping = NSDecimalNumber(string: "5.99")
        let tax = NSDecimalNumber(string: "2.50")
        let paymentDetails = PayPalPaymentDetails(subtotal: subtotal, withShipping: shipping, withTax: tax)
        let total = subtotal.adding(shipping).adding(tax) //This is the total price including shipping and tax
        let payment = PayPalPayment(amount: total, currencyCode: "USD", shortDescription: "BREWIT 9", intent: .sale)
        payment.items = items
        payment.paymentDetails = paymentDetails
        if (payment.processable) {
            let paymentViewController = PayPalPaymentViewController(payment: payment, configuration: payPalConfig, delegate: self)
            present(paymentViewController!, animated: true, completion: nil)
        else {
            // This particular payment will always be processable. If, for
            // example, the amount was negative or the shortDescription was
            // empty, this payment wouldn't be processable, and you'd want
            // to handle that here.
            print("Payment not processalbe: \(payment)")


After this, don't forget to add PayPalPaymentDelegate in your ViewController class declaration. Also add this delegate function in your code:

// PayPalPaymentDelegate
    func payPalPaymentDidCancel(_ paymentViewController: PayPalPaymentViewController) {
        print("PayPal Payment Cancelled")
        paymentViewController.dismiss(animated: true, completion: nil)
    func payPalPaymentViewController(_ paymentViewController: PayPalPaymentViewController, didComplete completedPayment: PayPalPayment) {
        print("PayPal Payment Success !")
        paymentViewController.dismiss(animated: true, completion: { () -> Void in
            // send completed confirmaion to your server
            print("Here is your proof of payment:\n\n\(completedPayment.confirmation)\n\nSend this to your server for confirmation and fulfillment.")


Now, add viewWillAppear() method in the code:

    override func viewWillAppear(_ animated: Bool) {
        PayPalMobile.preconnect(withEnvironment: environment)


Once all this done. Its time for our final step.

STEP 5: Run Your App

Now just run your app and you'll get following screen on your simulator.

Click on 'Proceed To Payment' button and it will take you to the Payment screen. Here, It will be showing the company name and total payable amount along with PayPal Login.

Now, Just click on PayPal Log In and enter your PayPal credentials for login to your PayPal account. Once you successfully login, you can choose your preferred Payment method and also the shipping address.


Click on Pay Button to proceed with the Payment and Its DONE!!!

You can also pay by scanning your card if you'll be testing it on your real device.

After successful payment you'll also get the response in your console which you can use as per your own app requirements. Below is the screenshot of the same:

That's all about integrating PayPal in iOS using swift. You can now also try with some other Payment Gateways using the same approach. PayPal Payment Gateway is the most trusted, secure, reliable and widely used payment processor. So in most of the cases, this post is enough for adding payment processing in your iOS apps.

Here’s the full code for your reference:

If you've any doubts or need any further help, then do message me in the comments section below and I'll try to respond you as soon as possible.

If this tutorial helped you anyhow or you really liked it, Send Me One Coffee ☕️ ☺️

Thanks for your time. Keep coding.. 👨‍💻


  1. Very informative and easy to understand.
    Thanks for sharing..

    1. Thanks for appreciating the work. Stay in touch.. 😊

  2. Replies
    1. Thank you for liking the code. Stay in touch, many more to come! 😊 👨‍💻

  3. Can we remove the shipping address label when we logged in to paypal?

  4. Why this code is giving me all errors i dont know why ?