/React-Native

React Native library for Flutterwave for Business (F4B) v2 and v3 APIs.

Primary LanguageTypeScriptMIT LicenseMIT

React Native Flutterwave

Easily implement Flutterwave for payments in your React Native appliction. This library supports both Android and iOS, and use the Flutterwave's V3 API.

V2 API Commitizen friendly

ios-preview android-preview

Table Of Content

What's Inside?

  • Pay with Flutterwave button and checkout dialog.
  • Standard payment initialization function.
  • Flutterwave designed button.

⚠️ If Using Version 2 API ⚠️

This version of the library's docs focuses on use cases with the Version 3 of Flutterwaves API, if you are still using the Version 2 API please use this documentation instead.

Installation

This library is available on npm, you can install it by running npm install --save flutterwave-react-native or yarn add flutterwave-react-native

Dependencies

In order to render the Flutterwave checkout screen this library depends on react-native-webview ensure you properly install this library before continuing.

Activity Indicator (only needed for android)

To display the Flutterwave styled activity indicator when the checkout screen is being loaded on Android you will need to add some modules in android/app/build.gradle. Skip this if you already have setup your app to support gif images.

dependencies {
  // If your app supports Android versions before Ice Cream Sandwich (API level 14)
  implementation 'com.facebook.fresco:animated-base-support:1.3.0'

  // For animated GIF support
  implementation 'com.facebook.fresco:animated-gif:2.0.0'
}

🔥 MERCHANT PUBLIC KEY 🔥

In order to use this library you are required to use your merchant public key and not the secret key. See how to get your API Keys here

🔥 IMPORTANT INFORMATION 🔥

If the options property on PayWithFlutterwave changes, when next the user taps on the button a new payment will be initialized whether the last one was successful or not.

Remember you cannot use the same transaction reference for two different payments, also remember to recreate the transaction reference before allowing the user initiate a new payment.

Usage

Below are a few examples showcasing how you can use the library to implement payment in your React Native app.

PayWithFlutterwave

preview

View All Props

Import PayWithFlutterwave from flutterwave-react-native and use it like so.

import {PayWithFlutterwave} from 'flutterwave-react-native';
// or import PayWithFlutterwave from 'flutterwave-react-native';

interface RedirectParams {
    status: 'successful' | 'cancelled';
    transaction_id?: string;
    tx_ref: string;
  }

 /* An example function called when transaction is completed successfully or canceled */
  const handleOnRedirect = (data: RedirectParams) => {
      console.log(data);
    };

/* An example function to generate a random transaction reference */
  const generateTransactionRef = (length: number) => {
    var result = '';
    var characters =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return `flw_tx_ref_${result}`;
  };

<PayWithFlutterwave
  ...
  onRedirect={handleOnRedirect}
  options={{
    tx_ref: generateTransactionRef(10)
    authorization: '[merchant public key]',
    customer: {
      email: 'customer-email@example.com'
    },
    amount: 2000,
    currency: 'NGN',
    payment_options: 'card'
  }}
/>

PayWithFlutterwave (with custom render)

preview

View All Props

Import PayWithFlutterwave from flutterwave-react-native and use it like so.

import {PayWithFlutterwave} from 'flutterwave-react-native';
// or import PayWithFlutterwave from 'flutterwave-react-native';

interface RedirectParams {
    status: 'successful' | 'cancelled';
    transaction_id?: string;
    tx_ref: string;
  }

 /* An example function called when transaction is completed successfully or canceled */
  const handleOnRedirect = (data: RedirectParams) => {
      console.log(data);
    };

<PayWithFlutterwave
  ...
  onRedirect={handleOnRedirect}
  options={{...}}
  customButton={(props) => (
    <TouchableOpacity
      style={styles.paymentButton}
      onPress={props.onPress}
      isBusy={props.isInitializing}
      disabled={props.disabled}>
        <Text style={styles.paymentButtonText}>Pay $500</Text>
    </TouchableOpacity>
  )}
/>

FlutterwaveButton (Flutterwave styled button)

preview

View All Props

Import FlutterwaveButton from flutterwave-react-native and use it like so.

import {FlutterwaveButton} from 'flutterwave-react-native';

<FlutterwaveButton
  style={styles.paymentButton}
  onPress={onPress}
  disabled={disabled}>
  <Text style={styles.paymentButtonText}>Pay $500</Text>
</FlutterwaveButton>;

FlutterwaveInit

When called, this function returns a Promise which resolves to a string on success and rejects if an error occurs. See all config options

Import FlutterwaveInit from flutterwave-react-native and use it like so.

import {FlutterwaveInit} from 'flutterwave-react-native';

try {
  // initialize payment
  const paymentLink = await FlutterwaveInit({
    tx_ref: generateTransactionRef(),
    authorization: '[your merchant public Key]',
    amount: 100,
    currency: 'USD',
    customer: {
      email: 'customer-email@example.com',
    },
    payment_options: 'card',
  });
  // use payment link
  usePaymentLink(paymentLink);
} catch (error) {
  // handle payment error
  displayError(error.message);
}

Aborting Payment Initialization

👋 Hi, so there are cases where you have already initialized a payment with FlutterwaveInit but might also want to be able to cancel the payment initialization should in case your component is being unmounted or you want to allow users cancel the action before the payment is initialized, we have provided a way for you to do this... continue reading

Props

FlutterwaveInitOptions

See Interface

Name Required Type Default Description
authorization Yes string REQUIRED Your merchant public key, see how to get your API Keys
tx_ref Yes string REQUIRED Your transaction reference. This MUST be unique for every transaction.
amount Yes string REQUIRED Amount to charge the customer.
currency No string NGN Currency to charge in. Defaults to NGN. See accepted currencies here
integrity_hash No string undefined This is a sha256 hash of your FlutterwaveCheckout values, it is used for passing secured values to the payment gateway.
payment_options Yes string REQUIRED This specifies the payment options to be displayed e.g - card, mobilemoney, ussd and so on.
payment_plan No number undefined This is the payment plan ID used for Recurring billing.
redirect_url Yes string REQUIRED URL to redirect to when a transaction is completed. This is useful for 3DSecure payments so we can redirect your customer back to a custom page you want to show them. IMPORTANT This only required when you are directly using FlutterwaveInit
customer Yes FlutterwaveInitCustomer REQUIRED This is an object that contains your customer details. E.g.'customer': { 'email': 'example@example.com', 'phonenumber': '08012345678', 'name': 'Takeshi Kovacs' }.
subaccounts No array of FlutterwaveInitSubAccount undefined This is an array of objects containing the subaccount IDs to split the payment into. Check out the Split Payment page for more info
meta No FlutterwavePaymentMeta undefined This is an object that helps you include additional payment information to your request. E.g. { 'consumer_id': 23, 'consumer_mac': '92a3-912ba-1192a' }
customizations No FlutterwaveInitCustomizations undefined This is an object that contains title, logo, and description you want to display on the modal E.g. {'title': 'Pied Piper Payments', 'description': 'Middleout isn't free. Pay the price', 'logo': 'https://assets.piedpiper.com/logo.png'}

PayWithFlutterwaveProps

See Interface

Name Required Type Default Description
style No object undefined Used to apply styling to the button.
onRedirect Yes function REQUIRED Called when a payment is completed successfully or is canceled. The function will receive redirect params as an argument.
onWillInitialize No function undefined This will be called before a payment link is generated.
onDidInitialize No function undefined This is called when a new payment link has been successfully initialized.
onInitializeError No function undefined This is called if an error occurred while initializing a new pyment link. The function will receive FlutterwaveInitError
onAbort No function undefined This is called if a user aborts a transaction, a user can abort a transaction when they click on the dialog's backdrop and choose cancel when prompted to cancel transaction.
options Yes FlutterwaveInitOptions REQUIRED The option passed here is used to initialize a payment.
customButton No function undefined This is used to render a custom button. The function a prop argument structured like CustomButtonProps, this function should return a valid React node.
alignLeft No boolean undefined This aligns the content of the button to the left.

FlutterwaveButton Props

See Interface

Name Required Type Default Description
style No ViewStyle undefined This component uses the same style properties that are applicable to react-native's View component style.
onPress Yes function undefined This property receive a function that is called on button press.
disabled No boolean undefined This disables button, and causes onPress not to be fired.
alignLeft No boolean undefined This aligns the content of the button to the left.

Types

CustomButtonProps

interface CustomButtonProps {
  disabled: boolean;
  isInitializing: boolean;
  onPress: () => void;
}

RedirectParams

interface RedirectParams {
  status: 'successful' | 'cancelled';
  transaction_id?: string;
  tx_ref: string;
}

FlutterwaveInitError

interface FlutterwaveInitError {
  code: string;
  message: string;
  errorId?: string;
  errors?: Array<string>;
}

FlutterwavePaymentMeta

interface FlutterwavePaymentMeta {
  [k: string]: any;
}

FlutterwaveInitCustomer

interface FlutterwaveInitCustomer {
  email: string;
  phonenumber?: string;
  name?: string;
}

FlutterwaveInitCustomizations

interface FlutterwaveInitCustomizations {
  title?: string;
  logo?: string;
  description?: string;
}

FlutterwaveInitSubAccount

interface FlutterwaveInitSubAccount {
  id: string;
  transaction_split_ratio?: number;
  transaction_charge_type?: string;
  transaction_charge?: number;
}

FlutterwaveInitOptions Interface

export interface FlutterwaveInitOptions {
  authorization: string;
  tx_ref: string;
  amount: number;
  currency: string;
  integrity_hash?: string;
  payment_options?: string;
  payment_plan?: number;
  redirect_url: string;
  customer: FlutterwaveInitCustomer;
  subaccounts?: Array<FlutterwaveInitSubAccount>;
  meta?: FlutterwavePaymentMeta;
  customizations?: FlutterwaveInitCustomizations;
}

PayWithFlutterwaveProps Interface

interface PayWithFlutterwaveProps {
  style?: ViewStyle;
  onRedirect: (data: RedirectParams) => void;
  onWillInitialize?: () => void;
  onDidInitialize?: () => void;
  onInitializeError?: (error: FlutterwaveInitError) => void;
  onAbort?: () => void;
  options: Omit<FlutterwaveInitOptions, 'redirect_url'>;
  customButton?: (props: CustomButtonProps) => React.ReactNode;
  alignLeft?: 'alignLeft' | boolean;
}

FlutterwaveButtonProps Interface

interface FlutterwaveButtonProps {
  style?: StyleProp<ViewStyle>;
  disabled?: boolean;
  alignLeft?: boolean;
  onPress?: () => void;
}

Contributing

For information on how you can contribute to this repo, simply go here, all contributions are greatly appreciated.

With love from Flutterwave. 💛