MYFatrooh Payment Gateway in Swift
In this blog, we are going to learn how to integrate MYFatrooh Payment Gateway in Swift. However, in today’s world, we need to create the transaction from our mobile, for which we need to integrate the payment gateway which is available in that particular country.
MYFatrooh Payment gateway provides a bundle of payment gateway. In addition, it used in the countries mention below.
- Kuwait.
- Saudi.
- Uae.
- Bahrain.
- Qatar.
- Oman.
- Egypt.
Steps to integrate
After that, please follow the below steps to integrate the MYFatrooh Payment gateway in your iOS project.
Step – 1
Please install the MYFatrooh pod in your iOS project.
1 |
pod 'MyFatoorah' |
Step – 2
Now import the MFSDK in your View Controller.
1 |
import MFSDK |
Step – 3
Now create your account in MYFatrroh Payment gateway using the link and generate the token key and base URL. After that initialize the MyFatrooh payment using token Key and Base Url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
override func viewDidLoad() { super.viewDidLoad() // This is for initialization MFSettings.shared.configure(token: token, baseURL: baseURL) // you can change color and title of navigation bar let them = MFTheme(navigationTintColor: .white, navigationBarTintColor: .lightGray, navigationTitle: "Payment", cancelButtonTitle: "Cancel") MFSettings.shared.setTheme(theme: them) self.navigationItem.hidesBackButton = true payButton.isEnabled = false setCardInfo() initiatePayment() } |
Step – 4
We can now call the function to initiate the payment gateway.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 |
extension MyFatoorahPaymentViewController { func initiatePayment() { let request = generateInitiatePaymentModel() startLoading() MFPaymentRequest.shared.initiatePayment(request: request, apiLanguage: .english, completion: { [weak self] (result) in self?.stopLoading() switch result { case .success(let initiatePaymentResponse): self?.paymentMethods = initiatePaymentResponse.paymentMethods //initiatePaymentResponse.paymentMethods![0 self?.collectionView.reloadData() self?.showSuccess("Success") case .failure(let failError): self?.callBackFail!(true) self?.showFailError(failError) } }) } func executePayment(paymentMethodId: Int) { let request = getExecutePaymentRequest(paymentMethodId: paymentMethodId) startLoading() MFPaymentRequest.shared.executePayment(request: request, apiLanguage: MFAPILanguage(rawValue: Language!)!) { [weak self] response, invoiceId in self?.stopLoading() switch response { case .success(let executePaymentResponse): if let invoiceStatus = executePaymentResponse.invoiceStatus { // You will get success of the payment gateway here self?.showSuccess(invoiceStatus) } case .failure(let failError): // You will get failure of your payment self?.showFailError(failError) } } } } |
Step – 5
Now we have to set up the function for setting up the card, payment gateway result, and generate an invoice.
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 34 35 36 37 38 39 40 41 42 |
extension MyFatoorahPaymentViewController { func startSendPaymentLoading() { errorCodeLabel.text = "Status:" resultTextView.text = "Result:" sendPaymentButton.setTitle("", for: .normal) sendPaymentActivityIndicator.startAnimating() } func stopSendPaymentLoading() { sendPaymentButton.setTitle("Send Payment", for: .normal) sendPaymentActivityIndicator.stopAnimating() } func startLoading() { errorCodeLabel.text = "Status:" resultTextView.text = "Result:" payButton.setTitle("", for: .normal) activityIndicator.startAnimating() } func stopLoading() { payButton.setTitle("Pay", for: .normal) activityIndicator.stopAnimating() } func showSuccess(_ message: String) { errorCodeLabel.text = "Succes" resultTextView.text = "result: \(message)" // This is for Success print("Success") } func showFailError(_ error: MFFailResponse) { errorCodeLabel.text = "responseCode: \(error.statusCode)" resultTextView.text = "Error: \(error.errorDescription)" fail = true // This is for Failure print("fail") } } |
However, please use the below code to set up the card info.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
extension MyFatoorahPaymentViewController { func hideCardInfoStacksView(isHidden: Bool) { for stackView in cardInfoStackViews { stackView.isHidden = isHidden } } private func setCardInfo() { cardNumberTextField.text = "" cardHolderNameTextField.text = "" monthTextField.text = "" yearTextField.text = "" secureCodeTextField.text = "" } } extension MyFatoorahPaymentViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let paymentMethods = paymentMethods else { return 0 } return paymentMethods.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PaymentMethodCollectionViewCell if let paymentMethods = paymentMethods, !paymentMethods.isEmpty { let selectedIndex = selectedPaymentMethodIndex ?? -1 cell.configure(paymentMethod: paymentMethods[indexPath.row], selected: selectedIndex == indexPath.row) } return cell } } extension MyFatoorahPaymentViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedPaymentMethodIndex = indexPath.row payButton.isEnabled = true if let paymentMethods = paymentMethods { print("Payment Method is \(paymentMethods[selectedPaymentMethodIndex ?? 0])") } collectionView.reloadData() } } |
After that, we can use the below code for generating the invoice and navigating after the success and failure of the payment gateway.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
extension MyFatoorahPaymentViewController { private func generateInitiatePaymentModel() -> MFInitiatePaymentRequest { let request = MFInitiatePaymentRequest() return request } private func getCardInfo() -> MFCardInfo { let cardNumber = cardNumberTextField.text ?? "" let cardExpiryMonth = monthTextField.text ?? "" let cardExpiryYear = yearTextField.text ?? "" let cardSecureCode = secureCodeTextField.text ?? "" let cardHolderName = cardHolderNameTextField.text ?? "" let card = MFCardInfo(cardNumber: cardNumber, cardExpiryMonth: cardExpiryMonth, cardExpiryYear: cardExpiryYear, cardHolderName: cardHolderName, cardSecurityCode: cardSecureCode, saveToken: false) return card } private func getExecutePaymentRequest(paymentMethodId: Int) -> MFExecutePaymentRequest { let invoiceValue = Decimal(string: amount ?? "0") ?? 0 let request = MFExecutePaymentRequest(invoiceValue: invoiceValue , paymentMethod: paymentMethodId) // request.customerEmail = CustomerEmail! request.customerName = CustomerName! request.displayCurrencyIso = MFCurrencyISO(rawValue: currency!)! return request } func getSendPaymentRequest() -> MFSendPaymentRequest { let invoiceValue = Decimal(string: amount ?? "") ?? 0 let request = MFSendPaymentRequest(invoiceValue: invoiceValue, notificationOption: .all, customerName: "test") request.customerEmail = CustomerEmail ?? "test12@webkul.com" request.customerMobile = "9999999999"//Required request.customerCivilId = "" request.mobileCountryIsoCode = MFMobileCountryCodeISO.kuwait.rawValue request.customerReference = "" request.language = .english let address = MFCustomerAddress(block: "ddd", street: "sss", houseBuildingNo: "sss", address: "sss", addressInstructions: "sss") request.customerAddress = address request.language = .english request.displayCurrencyIso = .kuwait_KWD let date = Date().addingTimeInterval(1000) request.expiryDate = date return request } } // MARK: - Recurring Payment extension MyFatoorahPaymentViewController { func executeRecurringPayment(paymentMethodId: Int) { let request = MFExecutePaymentRequest(invoiceValue: 5.000 , paymentMethod: paymentMethodId) let card = MFCardInfo(cardNumber: "", cardExpiryMonth: "", cardExpiryYear: "", cardHolderName: "", cardSecurityCode: "") MFPaymentRequest.shared.executeRecurringPayment(request: request, cardInfo: card, recurringIntervalDays: 10, apiLanguage: .english) { (response, invoiceId) in switch response { case .success(let directPaymentResponse): if let cardInfoResponse = directPaymentResponse.cardInfoResponse, let card = cardInfoResponse.cardInfo { print("Status: with card number: \(card.number)") print("Status: with recurring Id: \(cardInfoResponse.recurringId ?? "")") } if let invoiceId = invoiceId { print("Success with invoice id \(invoiceId)") } else { print("Success") } case .failure(let failError): print("Error: \(failError.errorDescription)") if let invoiceId = invoiceId { print("Fail: \(failError.statusCode) with invoice id \(invoiceId)") } else { print("Fail: \(failError.statusCode)") } } } } func executeRecurringPayment(recurringId: String) { MFPaymentRequest.shared.cancelRecurringPayment(recurringId: recurringId, apiLanguage: .english) { [weak self] (result) in switch result { case .success(let isCanceled): if isCanceled { print("Success") } case .failure(let failError): self?.showFailError(failError) } } } } |
In Conclusion
We have integrated the payment gateway into our iOS application.
In addition, now you can use a wide variety of payment gateway methods in your iOS application with only one payment gateway integration. For more information on integration please refer to the MYFatrooh official website from here.
Please read my other blog from here.