Integrate Payfort SDK in React native!

Integrate Payfort SDK in React native!
5 min read

In order to best help you get started with integrating PayFort into your React Native project, today we’ll cover the basics of PayFort integration using Simi Connector.

What is PayFort?

Known as the payment gate that drives e-commerce adoption in the Middle East, PayFort is your leading online payment service provider that aims to make online payment safe and secure for everyone in the Arab world.

Requirements

  • iOS version 8 and above
  • Xcode
  • Android Studio
  • A working Magento 2 site
  • Simi Connector

Configure

  • Create a project

react-native init PayfortExample

  • Create a project

npm install react-native-payfort-sdk — save

  • Library configurations for Android

  1. Extract this folder
  2. In Android Studio, choose File→ New → New Module, and then select

Import .JAR\.AAR Package

  1. Navigate to the library folder and choose the .aarfile
  2. Click on Finish when it’s all done
  3. in the next step, find the path of .aarfile in the library folder and press
  • Library configurations for iOS

  1. Extract this
  2. Drag the framework& PayFortSDK.bundle to Frameworks in Project Navigator
  3. Create a new group called Frameworks if it does not exist:
  • Choose to Create groups for any added folders.
  • Make sure to select Copy files if needed.
  1. Set -ObjCin Other Linker Flags in Target → Build Settings Tab.
  2. For Swift Projects, don’t forget to add the #importto the Bridging-Header.h

After finishing all the above steps, we need to create a bridge between the JS code and iOS. Here’s how you do it:

1. Right-click on project → New file

Integrate Payfort SDK in React native!

2. Choose Cocoa Touch Class -> Next

Integrate Payfort SDK in React native!

3. Rename class. In the Subclass dropdown, choose NSObject. And then click on Next.

Integrate Payfort SDK in React native!

4. After this, we’ll have two files Nativethod.hand NativeMethod.mas shown in the picture. In NativeMethod.h, we configure as follows:

#import <React/RCTBridgeModule.h>

And

Integrate Payfort SDK in React native!

5. Next up, we’ll need to do some configuration in NativeMethod.m:

#import "NativeMethod.h"

 
 

#include <CommonCrypto/CommonDigest.h>

 

#import <PayFortSDK/PayFortSDK.h>

   
 

@implementation NativeMethod{

 

 RCTResponseSenderBlock onDoneClick;

 

 RCTResponseSenderBlock onCancelClick;

 

 NSDictionary *data;

 

 PayFortController *payfort;

 

 UIViewController *rootViewController;

 

 NSString *udidString;

 

 BOOL asyncSuccessful;

 

 NSString *signatureString;Ï

 

}

   
 

//open payfort

 

RCT_EXPORT_METHOD(openPayfort:(NSDictionary *)indic createDialog:(RCTResponseSenderBlock)doneCallback createDialog:(RCTResponseSenderBlock)cancelCallback) {

 

 onDoneClick = doneCallback;

 

 onCancelClick = cancelCallback;

   
 

 udidString = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

   
 

 dispatch_async(dispatch_get_main_queue(), ^{

 

   data = [[NSDictionary alloc] initWithDictionary:indic];

 

   rootViewController = (UIViewController*)[UIApplication sharedApplication].delegate.window.rootViewController;

 

   NSString *sdk_token = @"";

 

   [self openPayfort:sdk_token];

   
 

 });

 

}

   
 

//get info amount, currency,... from react native. After open Payfort for payment

 

- (void)openPayfort:(NSString *)sdkToken{

 

 NSMutableDictionary *request = [[NSMutableDictionary alloc]init];

   
 

 if (data[@"amount"]) {

 

   [request setValue:data[@"amount"] forKey:@"amount"];

 

 }

 

 if (data[@"currency"]) {

 

   [request setValue:data[@"currency"] forKey:@"currency"];

 

 }

 

 if (data[@"customer_email"]) {

 

   [request setValue:data[@"customer_email"] forKey:@"customer_email"];

 

 }

 

 if (data[@"customer_name"]) {

 

   [request setValue:data[@"customer_name"] forKey:@"customer_name"];

 

 }

   
 

 if (data[@"merchant_reference"]) {

 

   [request setValue:data[@"merchant_reference"] forKey:@"merchant_reference"];

 

 }

   
 

 if (data[@"language"]) {

 

   [request setValue:data[@"language"] forKey:@"language"];

 

 }else{

 

   [request setValue:@"en" forKey:@"language"];

 

 }

   
 

 if (data[@"sdk_token"]) {

 

   [request setValue:data[@"sdk_token"] forKey:@"sdk_token"];

 

 }

   
 

 if (data[@"payment_option"]) {

 

   [request setValue:data[@"payment_option"] forKey:@"payment_option"];

 

 }else{

 

   [request setValue:@"" forKey:@"payment_option"];

 

 }

   
 

 [request setValue:@"PURCHASE" forKey:@"command"];

 

 [request setValue:@"ECOMMERCE" forKey:@"eci"];

   
 

 dispatch_async(dispatch_get_main_queue(), ^{

   
 

   if ([data[@"is_live"] isEqualToString:@"1"]) {

 

     payfort = [[PayFortController alloc] initWithEnviroment:KPayFortEnviromentProduction];

 

   }else{

 

     payfort = [[PayFortController alloc] initWithEnviroment:KPayFortEnviromentSandBox];

 

   }

 

   payfort.IsShowResponsePage = true;

   
 

   NSArray *events = @[];

 

   [payfort callPayFortWithRequest:request currentViewController:rootViewController

 

                           Success:^(NSDictionary *requestDic, NSDictionary *responeDic) {

 

                             //                              NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:responeDic];

 

                             //                              [dic setValue:signatureString forKey:@"signature"];

   
 

                             onDoneClick(@[responeDic, events]);

 

                           }

 

                          Canceled:^(NSDictionary *requestDic, NSDictionary *responeDic) {

 

                            onCancelClick(@[@"cancel", events]);

 

                          }

 

                             Faild:^(NSDictionary *requestDic, NSDictionary *responeDic, NSString *message) {

 

                               onCancelClick(@[message, events]);

 

                             }];

 

 });

 

}

   
 

@end

We can now run PayFort SDK from the JS code

  • Assuming that our current app has only one Place Order button, and by clicking on this button, we create an order on the Magento site (this is a simplified scenario, as the usual steps for order creation require a series of steps: add to cart, select shipping, payment method…). In this case, device_id needs to be added to the POST parameters when placing an order via SimiCart API:

import React from 'react';

 
 

import { NativeModules } from 'react-native';

   
 

const NativeMethod = Platform.OS === 'ios' ? NativeModules.NativeMethod : NativeModules.NativeMethodModule;

   
 

export default class Checkout extends React.Component {

   
 

  onPlaceOrder() {

 

      let PayFortMethod = Platform.OS === 'ios' ? NativeMethod: RNReactNativePayfortSdk;

 

      PayFortMethod.getDeviceID().then(rep => {

 

          this.device_id = rep

 

     

 

          fetch('https://www.simiexample.com/simiconnector/rest/v2/orders/onepage', {

 

              method: 'POST',

 

              headers: {

 

                  Accept: 'application/json',

 

                  'Content-Type': 'application/json'

 

              },

 

              body: JSON.stringify({

 

                  device_id: '14F92858.....',

 

              })

 

          })

 

              .then(function (response) {

 

                  if (response.ok) {

 

                      return response.json();

 

                  }

 

              })

 

              .then(function (data) {

 

                  //result

 

                  this.data = data

 

              }).catch((error) => {

 

                  console.log(error);

 

              });

 

      })

 

  }

 

}

  • The server side will receive a device_idand, basing on which, it’ll create a SDK token basing (for more information, visit Payfort doc).
  • According to PayFort’s requirements, you need to integrate SDK with the test account first. And it’s only after the application went through with PayFort’s review process that SDK mode can be enabled on account production.

const ACCESS_CODE = 'YOUR_ACCESS_CODE';

 
 

  const MERCHANT_IDENTIFIER = 'YOUR_MERCHANT_IDENTIFIER';

 

  const REQUEST_PHRASE = 'YOUR_REQUEST_PHRASE';

 

  const RESPONSE_PHRASE = 'YOUR_RESPONSE_PHRASE';

   
 

protected function createSDKToken($deviceID)

 

  {

 

      $isSandbox = '0';

 

      $accessCode = self::ACCESS_CODE;

 

      $merchantIdentifier = self::MERCHANT_IDENTIFIER;

   
 

      $signature = $this->createSignature($deviceID);

 

      $url = 'https://sbpaymentservices.payfort.com/FortAPI/paymentApi';

 

      if ($isSandbox == '0') {

 

          $url = "https://paymentservices.payfort.com/FortAPI/paymentApi";

 

      }

 

      $ch = curl_init();

   
 

      $body = [

 

          'service_command' => 'SDK_TOKEN',

 

          'access_code' => $accessCode,

 

          'merchant_identifier' => $merchantIdentifier,

 

          'device_id' => $deviceID,

 

          'language' => 'en',

 

          'signature' => $signature

 

      ];

   
 

      curl_setopt($ch, CURLOPT_URL, $url);

 

      curl_setopt($ch, CURLOPT_POST, 1);

 

      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

 

      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

 

      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

   
 

      $server_output = curl_exec($ch);

   
 

      curl_close($ch);

   
 

      return json_decode($server_output);

 

  }

  • The method createSDKToken() above will return a tokenData. From the received tokenData we can generate the following information for the app:

$orderData['payfort'] = array(

 
 

          'is_sandbox' => '0',

 

          'merchant_identifier' => self::LIVE_MERCHANT_IDENTIFIER,

 

          'access_code' => self::LIVE_ACCESS_CODE,

 

          'request_phrase' => self::LIVE_REQUEST_PHRASE,

 

          'response_phrase' => self::LIVE_RESPONSE_PHRASE,

 

          'language' => 'ar',

 

          'sdk_token' => $tokenData->sdk_token,

 

          'signature' => $tokenData->signature

 

      );

  • After receiving the data, the app will use it to open a PayFort payment processing page, like so:

let data = {};

 
 

      data['access_code'] = 'abcdxyzqwerty';          // require field

 

      data['merchant_identify'] = 'poilkjyhm';        // require field

 

      data['request_phrase'] = 'tgbvfe';              // require field

 

      data['customer_email'] = '[email protected]';       // require field

 

      data['currency'] = 'USD';                       // require field

 

      data['amount'] = '10';                          // require field

 

      data['merchant_reference'] = '123456';          // require field

 

      data['customer_name'] = 'Glenn';

 

      data['customer_ip'] = '27.79.60.231';

 

      data['payment_option'] = 'VISA';

 

      data['order_description'] = 'Order for testing';

   
 

      RNReactNativePayfortSdk.openPayfort(data, (response) => {

 

          console.log(response);

 

      }, (message) => {

 

          // Message in case payment is failure or cancel

 

      });

  • With every payment completion comes a response. We’ll use this response to request to SimiPayfort API. The API handles all the payment information processing stages and updates the order’s status accordingly.

fetch('https://www.simiexample.com/simiconnector/rest/v2/simipayfort', {

 
 

          method: 'POST',

 

          headers: {

 

              Accept: 'application/json',

 

              'Content-Type': 'application/json'

 

          },

 

          body: JSON.stringify(response)

 

      });

And that’s it for integrating PayFort into your React Native project! In the next part, we’ll be discussing Apple Pay by PayFort integration so don’t forget to check it out!

If you have any questions regarding React Native Development Connect with us today!

In case you have found a mistake in the text, please send a message to the author by selecting the mistake and pressing Ctrl-Enter.
expertappdevs 0
An expert customer-centric mobile app development company that drives engagement through personalization with a team of award-winning developers. Expert App De...
Comments (0)

    No comments yet

You must be logged in to comment.

Sign In / Sign Up