API Reference

React Native

React-Native EdfaPay SoftPos SDK

npm version

https://www.npmjs.com/package/react-native-edfapay-softpos-sdk

Installation

[!IMPORTANT]

Configure Repository

It is important to add the gradlePluginPortal and maven jitpack with authorization repositories to your project-level build.gradle file. This allows Gradle to download the EdfaPay plugin from gradlePluginPortal and native dependencies from jitpack.

Place the below code snippet in your ./android/build.gradle file:

allprojects {
  repositories {
    maven {
      url "https://jitpack.io"
      credentials {
        username "jp_i9ed2av1lj1kjnqpgobpeh0e7k"
      }
    }
  }
}

[!IMPORTANT]

Configure Partner Code

The partner code, provided by EdfaPay, must be set as a permanent EDFAPAY_PARTNER environment variable at the system or user level of your operating system.

Developers can set up the partner code in two ways:

  1. Gradle Properties
  2. Environment Variable

Setup by Gradle Properties

Add the EDFAPAY_PARTNER property to your ~/.gradle/gradle.properties file:

EDFAPAY_PARTNER=Your_Partner_Code

Setup by Environment Variable

MacOS/Linux

Permanent environment variables should be added to the .bash_profile file:

  1. Open the .bash_profile file with a text editor of your choice (create the file if it does not exist).
  2. Scroll down to the end of the .bash_profile file.
  3. Copy and paste the text below to a new line (replace your partner code with the actual value received from EdfaPay):
    • export EDFAPAY_PARTNER=your partner code
  4. Save changes made to the .bash_profile file.
  5. Execute the new .bash_profile by either restarting the machine or running the command below:
    • source ~/.bash-profile
Windows
  1. Open the link below for instructions:
  2. Ensure the following:
    • Variable name should be EDFAPAY_PARTNER
    • Variable value should be your partner code received from EdfaPay

[!IMPORTANT]

Install or Update React Native SDK

To install the SDK, run the following command in your project directory:

npm install react-native-edfapay-softpos-sdk

To update the SDK, run the following command in your project directory:

npm update react-native-edfapay-softpos-sdk

Make sure the latest version is installed by comparing the version in package.json with the latest available on npm.

Usage

Import

Import the EdfaPay SoftPos SDK into your project:

import * as EdfaPayPlugin from 'react-native-edfapay-softpos-sdk';

Initialization

Initialize the SDK with your authentication code.

const authCode = "Your_Sdk_Login_Auth_Code"; // Replace with your actual SDK Login Auth Code

EdfaPayPlugin.initiate(authCode, EdfaPayPlugin.Env.UAT).then(async (value) => {
  if (value === false) {
    // Handle initialization failure (e.g., inform the developer/user)
    console.error("EdfaPay SDK initialization failed.");
  } else {
    // SDK initialized successfully, allow user to proceed with payment
    console.log("EdfaPay SDK initialized successfully.");
  }
});

Setting Theme (Optional)

You can customize the theme of the payment interface using the setButtonBackgroundColor, setButtonTextColor, setPoweredByImage, and setHeaderImage methods.

const logo = "base64 of image"; // Your base64 encoded image string for logo

EdfaPayPlugin.theme
    .setButtonBackgroundColor("#06E59F")
    .setButtonTextColor("#000000")
    .setPoweredByImage(logo)
    .setHeaderImage(logo);

Pay

Initiate a payment transaction using EdfaPayPlugin.pay(). This method requires transaction parameters and several callback functions to handle different payment scenarios.

First, define your transaction parameters:

var params = new EdfaPayPlugin.TxnParams("10.00", EdfaPayPlugin.TxnType.PURCHASE);

Next, define the callback functions to handle payment events:

const onPaymentProcessComplete = (status: boolean, code: string, transaction: Transaction) => {
  console.log(`>>> Payment Process Complete`);
  if (status) {
    console.log(` >>> [ Success ]`);
    console.log(` >>> [ ${JSON.stringify(transaction)} ]`);
  } else {
    console.log(` >>> [ Failed ]`);
    console.log(` >>> [ ${JSON.stringify(transaction)} ]`);
  }
};

const onServerTimeOut = () => {
  console.log(`>>> Server Timeout`);
  console.log(` >>> The request timed out while performing the transaction at the backend.`);
};

const onScanCardTimeOut = () => {
  console.log(`>>> Scan Card Timeout`);
  console.log(` >>> The scan card timed out; no card was tapped on the device.`);
};

const onCancelByUser = () => {
  console.log(`>>> Canceled By User`);
  console.log(` >>> User canceled the scanning/payment process.`);
};

const onError = (error: Error) => {
  console.error(`>>> Exception`);
  console.error(` >>> Scanning/Payment process threw an exception. Check console logs.`);
  console.error(`  >>> ${error.message}`);
  console.error(`  >>> ${error.cause}`);
  console.error(`  >>> ${error.stack}`);
};

Finally, call the pay method with the defined parameters and callbacks:

EdfaPayPlugin.pay(
  params,
  onPaymentProcessComplete,
  onServerTimeOut,
  onScanCardTimeOut,
  onCancelByUser,
  onError
);

Example

Click to Expand/Collapse
import * as React from 'react';
import { View, Text, Image, Button, StyleSheet, Dimensions, Alert } from 'react-native';
import { Transaction } from 'react-native-edfapay-softpos-sdk';
import * as EdfaPayPlugin from 'react-native-edfapay-softpos-sdk';

const logo = require('../assets/images/edfapay_text_logo.png');
const authCode = "Your_Sdk_Login_Auth_Code"; // Replace with your actual SDK Login Auth Code
const amountToPay = "10.000";

// Simple dialog helper for the example
class Dialog {
  alert(title: string, message: string) {
    Alert.alert(
      title, message,
      [
        {
          text: 'OK',
          onPress: () => console.log('OK Pressed'),
          style: 'cancel'
        }
      ]
    );
  }
}
const dialog = new Dialog();

// Strings for UI
const Strings = {
  sdk: 'SDK',
  version: 'v0.1.2',
  message: "You\'re on your way to enabling your Android App to allow your customers to pay in a very easy and simple way just click the payment button and tap your payment card on NFC enabled Android phone."
};

// Styles for UI
const screen = Dimensions.get('window');
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  content: {
    alignItems: 'center',
  },
  logo: {
    width: screen.width / 1.5,
    resizeMode: 'contain',
  },
  heading1: {
    fontSize: 65,
    fontWeight: "700",
    color: "#000",
  },
  heading2: {
    fontSize: 30,
    fontWeight: "700",
    color: "#000",
  },
  heading3: {
    marginHorizontal: 30,
    fontSize: 13,
    fontWeight: "400",
    color: "#787878",
    marginVertical: 100,
  },
  buttonContainer: {
    position: 'absolute',
    bottom: 20,
    left: 0,
    right: 0,
    marginHorizontal: 20,
    borderRadius: 10,
    overflow: 'hidden',
  },
});

export default function App() {
  const [initResult, setInitResult] = React.useState<boolean | undefined>();

  React.useEffect(() => {
    initiateSdk(setInitResult);
  }, []);

  return (
    <View style={styles.container}>
      <View style={styles.content}>
        <Image
          source={logo}
          style={styles.logo}
        />

        <Text style={styles.heading1}>{Strings.sdk}</Text>
        <Text style={styles.heading2}>{Strings.version}</Text>
        <Text style={[styles.heading3, { textAlign: 'center' }]}>{Strings.message}</Text>
      </View>

      <View style={styles.buttonContainer}>
        <Button color="#06E59F" disabled={!initResult} title={`Pay ${amountToPay}`} onPress={() => {
          pay((status) => {
            var title = status ? "Success" : "Fail";
            dialog.alert(title, "Check the 'result/response' printed in console");
          });
        }} />
      </View>
    </View>
  );

  function initiateSdk(completion: ((status: boolean) => void)) {
    EdfaPayPlugin.initiate(authCode).then(async (value) => {
      completion(value);

      if (value === false) {
        dialog.alert("Error Initializing", "Failed to initialize 'EdfaPay SDK'");
        return;
      }

      const resLogo = await EdfaPayPlugin.setMerchantLogo(logo).catch(console.log);
      const resTheme = await EdfaPayPlugin.setTheme(
        new EdfaPayPlugin.Theme(
          "#06E59F",
          "#000"
        ).json()
      ).catch(console.log);

      if (!resLogo) {
        dialog.alert("Error Setting Logo", "Failed to set merchant logo");
      }

      if (!resTheme) {
        dialog.alert("Error Setting Theme", "Failed to set merchant Theme");
      }
    });
  }

  function pay(completion: ((status: boolean) => void)) {
    console.log(`initiate payment with amount: ${amountToPay}`);
    var params = new EdfaPayPlugin.TxnParams(amountToPay);

    const onPaymentProcessComplete = (status: boolean, transaction: Transaction) => {
      dialog.alert("Payment Process Complete", "");
      completion(status);
    };

    const onServerTimeOut = () => {
      dialog.alert("Server Timeout", "The request timed out while performing transaction at backend");
    };

    const onScanCardTimeOut = () => {
      dialog.alert("Scan Card Timeout", "The scan card timed out, no any card tap on device");
    };

    const onCancelByUser = () => {
      dialog.alert("Canceled By User", "User have cancel the scanning/payment process on its own choice");
    };

    const onError = (error: Error) => {
      dialog.alert("Exception", "Scanning/Payment process through an exception, Check the console logs");
      console.error(`>>> ${error.message}`);
      console.error(`>>> ${error.cause}`);
      console.error(`>>> ${error.stack}`);
    };

    EdfaPayPlugin.pay(
      params,
      onPaymentProcessComplete,
      onServerTimeOut,
      onScanCardTimeOut,
      onCancelByUser,
      onError
    );
  }
}

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT


Made with create-react-native-library