npm package: @fawry_pay/rn-fawry-pay-registered-sdk
Description: This is the only official Fawrypay Registered SDK package for React Native
Author: Milad Metias
Latest version: 0.0.5

# FawryPay React Native Registered SDK Sample Guide

Welcome to the FawryPay React Native SDK Sample Guide. This comprehensive guide will walk you through every step of integrating the FawryPay Registered SDK into your React Native application, allowing for seamless payment methods , card management and address management.

## Table of Contents

- [Introduction](#introduction)
- [Installation](#installation)
- [Getting Started](#getting-started)
  - [Step 1: Create a FawryPay Account](#step-1-create-a-fawrypay-account)
  - [Step 2: Initialize the SDK](#step-2-initialize-the-sdk)
  - [Step 3: Present Payment Options](#step-3-present-payment-options)
  - [Step 4: Present Card Manager](#step-4-present-card-manager)
  - [Step 5: Present Address Manager](#step-5-present-address-manager)
  - [Step 6: Callbacks](#step-6-callbacks)
- [Platform-specific Notes](#platform-specific-notes)
  - [Android](#android)
  - [iOS](#ios)
- [Customizing UI Colors](#customizing-ui-colors)
- [Parameters Explained](#parameters-explained)
- [Sample Project](#sample-project)

## Introduction

The FawryPay React Native SDK provides seamless integration for processing payments and managing cards within your React Native application. This guide will walk you through the steps needed to integrate the SDK into your project.

**Note**: Currently, the FawryPay React Native SDK does not support EXPO projects. Please use Vanilla React Native for integration.

#### How it works

![Fawrypay SDK Explained](https://raw.githubusercontent.com/FawryPay/Android-Fawrypay-Anonymous-sample/master/Docs/4.jpg)

## Installation

To get started with the FawryPay SDK, follow these installation steps:

### Step 1: Install the FawryPay SDK

To install the FawryPay SDK, use npm:

```bash
npm install @fawry_pay/rn-fawry-pay-registered-sdk --save
```

For React Native versions prior to 0.60, link the package using `react-native link`:

```bash
react-native link @fawry_pay/rn-fawry-pay-registered-sdk
```

For React Native versions 0.60 and above, autolinking will handle linking.

## Getting Started

### Step 1: Create a FawryPay Account

Before utilizing the FawryPay SDK, you must have a FawryPay account. Visit the FawryPay website to create an account if you don't already have one.

### Step 2: Initialize the SDK

In your React Native project, import the necessary components and configure the FawryPay SDK with your items, merchant and customer information:

```javascript
import * as Fawry from '@fawry_pay/rn-fawry-pay-registered-sdk';
import uuid from 'react-native-uuid';

const cartItems: Fawry.BillItems[] = [
  {
    itemId: 'product123',
    description: 'Smartphone Model X',
    quantity: '1',
    price: '800',
    originalPrice: '1000',
    tax: 12.5
  },
  {
    itemId: 'laptop456',
    description: 'Laptop Model Y',
    quantity: '1',
    price: '1200',
    originalPrice: '1500',
    tax: 9.8
  },
  {
    itemId: 'camera789',
    description: 'Digital Camera Z',
    quantity: '2',
    price: '400',
    originalPrice: '600',
    tax: 8.5
  },
];

const merchant: Fawry.MerchantInfo = {
  merchantCode: "YOUR_REAL_MERCHANT_CODE",
  subMerchantCode: "YOUR_REAL_SUBMERCHANT_CODE",
  merchantSecretCode: "YOUR_REAL_SECURE_KEY",
  merchantRefNum: uuid.v4().toString(),
};

const customer: Fawry.CustomerInfo = {
  customerName: 'Ahmed Kamal',
  customerMobile: '+1234567890',
  customerEmail: 'ahmed@example.com',
  customerProfileId: 'profile123',
  customerCif: 'cif456',
  customerToken: "token789",
};

const shippingAddress: Fawry.Address = {
  buildingNumber: '20',
  floorNumber: 5,
  apartmentNumber: '15',
  receiverName: 'John Doe',
  receiverMobile: '+9876543210',
};

const fawryConfig: Fawry.FawryLaunchModel = {
  addressHierarchy: Fawry.AddressHierarchy.MATRIX,
  allow3DPayment: true,
  apiPath: '',
  baseUrl: '',
  beid: '',
  branchCode: '',
  branchName: '',
  customerInfo: customer,
  items: cartItems,
  lang: Fawry.FawryLanguages.ENGLISH,
  merchantInfo: merchant,
  scheduledTime: new Date().getTime().toString(),
  serviceTypeCode: '',
  shippingAddress: shippingAddress,
  showLoyaltyContainer: true,
  showTipsView: false,
  showVoucherContainer: true,
  skipReceipt: false,
  tableId: 1,
};
// Continue with the code...

```

### Step 3: Present Payment Options

To initiate the payment process, use the `startPayment` function to open the payment flow.

```javascript
// Launch the payment flow
const updatedMerchant = { ...merchant, merchantRefNum: uuid.v4().toString() };
Fawry.startPayment(
    fawryConfig.addressHierarchy,
    fawryConfig.allow3DPayment,
    fawryConfig.apiPath,
    fawryConfig.baseUrl,
    fawryConfig.customerInfo,
    fawryConfig.items,
    fawryConfig.lang,
    updatedMerchant,
    fawryConfig.showLoyaltyContainer,
    fawryConfig.showTipsView,
    fawryConfig.showVoucherContainer,
    fawryConfig.skipReceipt,
    fawryConfig.beid,
    fawryConfig.branchCode,
    fawryConfig.branchName,
    fawryConfig.scheduledTime,
    fawryConfig.serviceTypeCode,
    fawryConfig.shippingAddress,
    fawryConfig.tableId
);
```

### Step 4: Present Card Manager

If you want to allow your users to manage their saved cards, you can use the `openCardsManager` function:

```javascript
// Open the card manager flow
Fawry.openCardsManager(
  fawryConfig.baseUrl,
  fawryConfig.lang,
  fawryConfig.merchantInfo,
  fawryConfig.customerInfo
);
```

### Step 5: Present Address Manager

If you want to allow your users to manage their saved addresses, you can use the `openAddressManager` function:

```javascript
// Open the address manager flow
Fawry.openAddressManager(
    fawryConfig.baseUrl,
    fawryConfig.lang,
    fawryConfig.merchantInfo,
    fawryConfig.customerInfo,
    fawryConfig.beid,
    fawryConfig.addressHierarchy
);
```

### Step 6: Callbacks

The FawryPay SDK provides event listeners that you can use to receive payment and card manager status. Here's how to set up event listeners:

```javascript
// Define event listeners for payment and card manager events
const eventListeners = [
  {
    eventName: Fawry.FawryCallbacks.FAWRY_EVENT_PAYMENT_COMPLETED,
    listener: (data: any) =>
      console.log(Fawry.FawryCallbacks.FAWRY_EVENT_PAYMENT_COMPLETED, data),
  },
  {
    eventName: Fawry.FawryCallbacks.FAWRY_EVENT_ON_SUCCESS,
    listener: (data: any) =>
      console.log(Fawry.FawryCallbacks.FAWRY_EVENT_ON_SUCCESS, data),
  },
  {
    eventName: Fawry.FawryCallbacks.FAWRY_EVENT_ON_FAIL,
    listener: (error: any) =>
      console.log(Fawry.FawryCallbacks.FAWRY_EVENT_ON_FAIL, error),

  },
  {
    eventName: Fawry.FawryCallbacks.FAWRY_EVENT_CARD_MANAGER_FAIL,
    listener: (error: any) =>
      console.log(Fawry.FawryCallbacks.FAWRY_EVENT_CARD_MANAGER_FAIL, error),
  },
  {
    eventName: Fawry.FawryCallbacks.FAWRY_EVENT_ADDRESS_MANAGER_FAIL,
    listener: (error: any) =>
      console.log(Fawry.FawryCallbacks.FAWRY_EVENT_ADDRESS_MANAGER_FAIL, error),
  },
];

// Attach event listeners
const attachEventListeners = () => eventListeners.forEach(({ eventName, listener }) => Fawry.FawryCallbacks.FawryEmitter.addListener(eventName, listener));


// Detach event listeners when the component unmounts
const detachEventListeners = () => eventListeners.forEach(({ eventName }) => Fawry.FawryCallbacks.FawryEmitter.removeAllListeners(eventName));


useEffect(() => {
  attachEventListeners();

  // Clean up event listeners when the component unmounts
  return detachEventListeners;
}, []);
```

## Platform-specific Notes

### Android

For Android integration, follow these additional steps:

1. Open the `build.gradle` file located in the root of your Android project (named `android/build.gradle`).

2. Find the `buildscript` block and add the following code in it:

   ```gradle
   allprojects {
       repositories {
         google()
         mavenCentral()
         maven { url "https://nexus.mobile.fawry.io/repository/maven-releases/" }
         maven { url "https://maven.google.com" }
         jcenter()
       }
     }
   ```

These changes enable your Android project to resolve dependencies from the specified repositories, facilitating the installation and usage of the `@fawry_pay/rn-fawry-pay-registered-sdk` package in your React Native application.

### iOS

For iOS integration, ensure that you follow these steps:

1. Open the `Podfile` file located in the root of your iOS project.

2. Delete the following code block:

   ```ruby
   flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled

   linkage = ENV['USE_FRAMEWORKS']
   if linkage != nil
     Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
     use_frameworks! :linkage => linkage.to_sym
   end
   ```

3. Replace the removed code with:

   ```ruby
   use_frameworks!
   ```

4. Disable Hermes Engine by changing:

   ```ruby
   :hermes_enabled => flags[:hermes_enabled],
   ```

   to:

   ```ruby
   :hermes_enabled => false,
   ```

5. Disable Flipper by changing:

   ```ruby
   :flipper_configuration => flipper_config,
   ```

   to:

   ```ruby
   :flipper_configuration => FlipperConfiguration.disabled,
   ```

6. In your iOS directory , run the command `pod install`

**Note for Xcode 15 Users:**

If you are using Xcode 15, it's important to follow these additional steps for proper integration:

```ruby
post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
      xcconfig_path = config.base_configuration_reference.real_path
      xcconfig = File.read(xcconfig_path)
      xcconfig_mod = xcconfig.gsub(/DT_TOOLCHAIN_DIR/, "TOOLCHAIN_DIR")
      File.open(xcconfig_path, "w") { |file| file << xcconfig_mod }
    end
  end
  react_native_post_install(
    installer,
    config[:reactNativePath],
    :mac_catalyst_enabled => false
  )
  __apply_Xcode_12_5_M1_post_install_workaround(installer)
end
```

After adding this code snippet, remember to run `pod update` in your iOS directory to ensure that the changes are properly applied.

---

These changes enable your iOS project to integrate the latest podfile without issues, facilitating the installation and usage of the `@fawry_pay/rn-fawry-pay-registered-sdk` package in your React Native application.

**Important Reminder:** If you're conducting tests on an Apple Silicon Mac, make sure that you're using the iPhone simulator with Rosetta. To do this, follow these steps: Open Xcode, go to `Product > Destination > Destination Architectures > Show Rosetta Destination`, and then select a Rosetta iPhone Simulator for running the application.

## Customizing UI Colors

### Android

To customize UI colors for Android:

1. Navigate to `android > app > src > main > res > values`.

2. Create a new file named `colors.xml`.

3. Add color values to `colors.xml`:

   ```xml
   <?xml version="1.0" encoding="utf-8"?>
   <resources>
       <color name="fawry_blue">#6F61C0</color>
       <color name="fawry_yellow">#A084E8</color>
   </resources>
   ```

### iOS

For iOS UI color customization:

1. In your project, navigate to `ios > YourAppNampe`.

2. Create a new file named `Style.plist`.

3. Add color values to `Style.plist`:

   ```xml
   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
    <key>primaryColorHex</key>
    <string>#6F61C0</string> <!-- Set your primary color hex code -->
    <key>secondaryColorHex</key>
    <string>#A084E8</string> <!-- Set your secondary color hex code -->
    <key>tertiaryColorHex</key>
    <string>#8BE8E5</string> <!-- Set your tertiary color hex code -->
    <key>headerColorHex</key>
    <string>#6F61C0</string> <!-- Set your header color hex code -->
   </dict>
   </plist>
   ```

   Then, add the `Style.plist` file to your Xcode project.

## Parameters Explained

<br/>CustomerInfo

| **PARAMETER**     | **TYPE** | **REQUIRED** | **DESCRIPTION**                                                                  | **EXAMPLE**                                           |
| ----------------- | -------- | ------------ | -------------------------------------------------------------------------------- | ----------------------------------------------------- |
| customerName      | string   | required     | The name of the customer.                                                        | Ahmed Kamal                                           |
| customerEmail     | string   | required     | The email address of the customer.                                               | [email@example.com](mailto:email@example.com){.email} |
| customerMobile    | string   | required     | The mobile number of the customer.                                               | +01012345678                                          |
| customerProfileId | string   | required     | The profile ID of the customer. Mandatory in case of payments using saved cards. | 11111                                                 |
| customerCif       | string   | required     | The CIF of the customer.                                                         | -                                                     |
| customerToken     | string   | required     | The authentication token of the customer.                                        | -                                                     |

<br/>MerchantInfo

| **PARAMETER**      | **TYPE** | **REQUIRED** | **DESCRIPTION**                                                 | **EXAMPLE**                                   |
| ------------------ | -------- | ------------ | --------------------------------------------------------------- | --------------------------------------------- |
| merchantCode       | string   | required     | Merchant ID provided during FawryPay account setup.             | -                                             |
| subMerchantCode    | string   | optional     | Sub-merchant code if applicable.                                | -                                             |
| merchantSecretCode | string   | required     | Merchant secret code provided by support.                       | -                                             |
| merchantRefNum     | string   | required     | Merchant's transaction reference number, generated dynamically. | Could be generated using uuid.v4().toString() |

<br/>BillItems

| **PARAMETER**  | **TYPE** | **REQUIRED** | **DESCRIPTION**                                                   | **EXAMPLE**        |
| -------------- | -------- | ------------ | ----------------------------------------------------------------- | ------------------ |
| itemId         | string   | required     | Unique identifier for the item.                                   | item1              |
| description    | string   | required     | Description of the item.                                          | Item 1 Description |
| price          | string   | required     | Price of the item.                                                | 300                |
| quantity       | string   | required     | Quantity of the item.                                             | 1                  |
| originalPrice  | string   | required     | Original price of the item.                                       | 500                |
| width          | string   | optional     | Width of the item.                                                | -                  |
| length         | string   | optional     | Length of the item.                                               | -                  |
| height         | string   | optional     | Height of the item.                                               | -                  |
| weight         | string   | optional     | Weight of the item.                                               | -                  |
| variantCode    | string   | optional     | Variant code of the item.                                         | -                  |
| earningRuleId  | string   | optional     | Earning rule identifier for the item.                             | -                  |
| imageUrl       | string   | optional     | URL for the item's image.                                         | -                  |
| specialRequest | string   | optional     | Special request or additional information for the item.           | -                  |
| tax            | number   | required     | Tax Amount ( notice that this is not a percentage ) for the item. | 8.5                |

<br/>FawryLaunchModel

| **PARAMETER**        | **TYPE**         | **REQUIRED** | **DESCRIPTION**                                           | **EXAMPLE**                                                                            |
| -------------------- | ---------------- | ------------ | --------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| customerInfo         | CustomerInfo     | required     | Customer information.                                     | -                                                                                      |
| merchantInfo         | MerchantInfo     | required     | Merchant information.                                     | -                                                                                      |
| items                | BillItems[]      | required     | Array of items which the user will buy.                   | -                                                                                      |
| addressHierarchy     | AddressHierarchy | required     | Type of address hierarchy (MATRIX or GEOLOCATION).        | MATRIX                                                                                 |
| allow3DPayment       | Boolean          | required     | True if 3D secure payment is allowed.                     | true                                                                                   |
| apiPath              | String           | required     | The API path for FawryPay.                                | fawrypay-api/api/                                                                      |
| baseUrl              | String           | required     | Fawry base URL.                                           | https://atfawry.fawrystaging.com (staging) <br/><br/> https://atfawry.com (production) |
| beid                 | String           | required     | Business Entity ID.                                       | -                                                                                      |
| branchCode           | String           | required     | Branch code.                                              | -                                                                                      |
| branchName           | String           | required     | Branch name.                                              | -                                                                                      |
| lang                 | FawryLanguages   | required     | SDK language which will affect SDK's interface languages. | Fawry.FawryLanguages.ENGLISH                                                           |
| scheduledTime        | String           | required     | Scheduled time for the payment.                           | -                                                                                      |
| serviceTypeCode      | String           | required     | Service type code.                                        | PICKUP                                                                                 |
| shippingAddress      | Address          | required     | Shipping address details.                                 | -                                                                                      |
| showLoyaltyContainer | Boolean          | required     | Show loyalty container.                                   | true                                                                                   |
| showTipsView         | Boolean          | required     | Show tips view.                                           | false                                                                                  |
| showVoucherContainer | Boolean          | required     | Show voucher container.                                   | true                                                                                   |
| skipReceipt          | Boolean          | required     | Skip receipt after payment.                               | false                                                                                  |
| tableId              | Number           | required     | Table ID.                                                 | 1                                                                                      |

## Sample Project

For a hands-on demonstration of Fawry SDK integration in a React Native app, explore our GitHub sample project:

[**React Native Fawrypay Registered Sample**](https://github.com/FawryPay/ReactNative-Fawrypay-Registered-Sample)

Feel free to explore the sample project and leverage the guide to effortlessly integrate the Fawry SDK into your React Native application.