Skip to content

Latest commit

 

History

History
411 lines (321 loc) · 15.9 KB

File metadata and controls

411 lines (321 loc) · 15.9 KB

React Native Flutterwave

Easily integrate Flutterwave for payment collection in your React Native application. This library is compatible with both Android and iOS and utilizes Flutterwave's V3 API.

V2 API Commitizen friendly

ios-preview android-preview

Table Of Contents

What's Inside?

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

⚠️ If Using Version 2 API ⚠️

This section of the library documentation focuses on use cases for Version 3 of the Flutterwave API. If you are still using Version 2 of the API, please refer to this documentation instead.

Installation

This library is available on npm. You can install it by running the following command:

npm install --save flutterwave-react-native

or

yarn add flutterwave-react-native

Dependencies

To render the Flutterwave checkout screen, this library requires the installation of react-native-webview. Please ensure that this library is installed correctly before proceeding.

Activity Indicator (only needed for Android)

To display the Flutterwave-styled activity indicator when the checkout screen is loading on Android, you will need to add a few modules to your android/app/build.gradle file. Skip this step if your app is already set up to support GIF images.

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

  // Add this for animated GIF support.
  implementation 'com.facebook.fresco:animated-gif:2.0.0'
}

🔥 MERCHANT PUBLIC KEY 🔥

To use this library, you are required to use your merchant public key instead of the secret key. Learn how to retrieve your API Keys here.

🔥 IMPORTANT INFORMATION 🔥

If the options property on PayWithFlutterwave changes, the next time your customer taps on the button, a new payment will be initialized, regardless of whether the previous transaction was successful or not.

Kindly note that you cannot use the same transaction reference for two different payments. Make sure you generate a new transaction reference before allowing your customer to start a new payment.

Usage

Below are some examples demonstrating how to implement payment features in your React Native application.

PayWithFlutterwave

preview

View All Props

Import PayWithFlutterwave from flutterwave-react-native and use it as follows:

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 the 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 as follows:

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 the 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 as follows:

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 that either resolves to a string on success or rejects if an error occurs. See all config options.

Import FlutterwaveInit from flutterwave-react-native and use it as follows:

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! There may be cases where you've already initiated a payment using FlutterwaveInit, but you might want the option of cancelling the payment initiation. This could be necessary if your component is being unmounted or if you want to allow customers to cancel the action before the payment is initialized. We have provided a method for you to accomplish this. Continue reading here.

Props

FlutterwaveInitOptions

See Interface

Name Required Type Default Description
authorization Yes string REQUIRED Your merchant public key. Learn how to retrieve your key here.
tx_ref Yes string REQUIRED Your transaction reference. This must be unique for each transaction.
amount Yes string REQUIRED The amount to charge your customer.
currency No string NGN The 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 displayed to your customers e.g - card, mobilemoney, ussd, and so on.
payment_plan No number undefined This is the payment plan ID used for recurring payments. You can learn more by visiting here.
redirect_url Yes string REQUIRED The URL where you want to redirect customers after a completed transaction. This is useful for 3DSecure payments, allowing us to send your customer to a custom page you wish to display. IMPORTANT This is 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 for splitting payments. Find more information by visiting our Split Payment Page.
meta No FlutterwavePaymentMeta undefined This object is used to include additional payment information for your request. E.g.. { 'consumer_id': 23, 'consumer_mac': '92a3-912ba-1192a' }
customizations No FlutterwaveInitCustomizations undefined This object contains a title, logo, and description 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 This property is used to apply styling to the button.
onRedirect Yes function REQUIRED This function is called when a payment is either completed successfully or cancelled. It receives redirect params as an argument.
onWillInitialize No function undefined This function is called before a payment link is generated.
onDidInitialize No function undefined This function is called when a new payment link has been successfully initialized.
onInitializeError No function undefined This function is called if an error occurs while initializing a new payment link. It will receive FlutterwaveInitError.
onAbort No function undefined This function is called if a customer aborts a transaction. A customer can abort a transaction when they click on the dialog's backdrop and choose cancel when prompted to cancel the transaction.
options Yes FlutterwaveInitOptions REQUIRED The option passed here is used to initialize a payment.
customButton No function undefined This function is used to render a custom button. It accepts a prop argument structured like CustomButtonProps. This function should return a valid React node.
alignLeft No boolean undefined This property aligns the content of the button to the left.

FlutterwaveButton Props

See Interface

Name Required Type Default Description
style No ViewStyle undefined This component accepts the same style properties applicable to the React-Native View component.
onPress Yes function undefined This property receives a function that is called when the button is pressed.
disabled No boolean undefined This disables the button, preventing the onPress function from being triggered.
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 to contribute to this repo, visit here. All contributions are greatly appreciated.

With love from Flutterwave. 💛