Hi guys, today we will learn about how to implement Paypal Payment Gateway for an iOS application in Swift.
Let us know first what is the Payment gateway.
A payment gateway bridges the gap between customers, banks and online business. It safely and securely passes all the sensitive information such as customer’s credit card numbers and so on, from one end to the other. It is used for online transactions with the customer. It is a merchant service provided by an e-commerce application service provider that authorizes credit card or direct payments processing for e-businesses, online retailers, bricks and clicks, or traditional brick and mortar.
Now we can start the steps to integrate the payment gateway.
Step To Integrate Paypal Payment Gateway
Step 1 => Add ‘PayPal-iOS-SDK’ In The Project
To integrate PayPal into your Xcode project using CocoaPods, specify it in your Podfile
:
1 |
pod 'PayPal-iOS-SDK' |
and then run this command in the terminal
1 |
pod install |
Step 2 => Setup of Paypal Environment
For testing purposes, you have to add these lines in your code it does not submit transactions to PayPal. It generates fakes successful responses that are useful for unit tests.
1 2 3 4 5 6 7 |
var environment:String = PayPalEnvironmentNoNetwork { willSet(newEnvironment) { if (newEnvironment != environment) { PayPalMobile.preconnect(withEnvironment: newEnvironment) } } } |
Step 3 => Implementation of Paypal Delegates
Then the third step is to implement the Paypal delegates. These delegates will call when payment is completed and when it is canceled.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//It specify that, the user canceled without making a payment. func payPalPaymentDidCancel(_ paymentViewController: PayPalPaymentViewController) { paymentViewController.dismiss(animated: true, completion: { () -> Void in self.dismiss(animated: true, completion: nil) }) } //when payment is completed then it is called 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.") let dict = ["order_id": self.orderId, "paypal_payment_response": ["response": completedPayment.confirmation["response"] ?? ""]] as [String : Any] let paymentDict = ["response": completedPayment.confirmation["response"] ?? ""] as [String : Any] print(dict) }) } |
Step 4 => Setup of Paypal
You have to set Paypal then you can initiate the payment. Add this code in your view controller and call this method for the setup of Paypal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
func setupPaypal(orderId: String, clientId: String, secretKey: String,totalAmount: Float, paymentMode: PaymentMode, account: String, currencyCode: String, discount: Float, shipping: Float, tax: Float) { var payPalConfig = PayPalConfiguration() //Initializaing the paypal environment with the client id. PayPalMobile.initializeWithClientIds(forEnvironments: [PayPalEnvironmentProduction: clientId, PayPalEnvironmentSandbox: clientId]) payPalConfig.acceptCreditCards = true //Client details payPalConfig.merchantName = account 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") payPalConfig.languageOrLocale = Defaults.language ?? "en"//UserDefaults.fetch(key: UserDefaults.Keys.AppLanguageKey) ?? "en" payPalConfig.payPalShippingAddressOption = .payPal; var items = [Any]() let item = PayPalItem.init(name: productName, withQuantity: 1, withPrice: NSDecimalNumber(string: String(format:"%.2f", totalAmount)), withCurrency: currencyCode, withSku: productName) items.append(item) print(items) let subtotal = PayPalItem.totalPrice(forItems: items) let shipping = NSDecimalNumber(string: String(format:"%.2f", shipping)) let tax = NSDecimalNumber(string: String(format:"%.2f", tax)) let paymentDetails = PayPalPaymentDetails(subtotal: subtotal, withShipping: shipping, withTax: tax) //let total = subtotal.adding(shipping).adding(tax) print("totallll: \(totalAmount)") let payment = PayPalPayment(amount: NSDecimalNumber(string: String(format:"%.2f", totalAmount)), currencyCode: currencyCode, shortDescription: orderId, 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 { print("Payment not processalbe: \(payment)") } } |
You can call this method by adding the following code.
1 |
self.setupPaypal(orderId: "Place Order", clientId: data["paypalData"]["clientId"].stringValue, secretKey: data["paypalData"]["secretKey"].stringValue, totalAmount: data["paypalData"]["amount"].floatValue,paymentMode: test, account: data["paypalData"]["merchantName"].stringValue, currencyCode: data["paypalData"]["currencyCode"].stringValue, discount: data["paypalData"]["discount"].floatValue, shipping: data["paypalData"]["shipping"].floatValue, tax: data["paypalData"]["tax"].floatValue) |
Conclusion
So please follow the above step to integrate the Paypal payment gateway and if you have any issue or suggestion you can leave your query/suggestion in the comment section.