Giter Site home page Giter Site logo

flutterwave / react-v3 Goto Github PK

View Code? Open in Web Editor NEW
10.0 1.0 9.0 626 KB

React Library for Flutterwave v3 payment APIs.

Home Page: https://developer.flutterwave.com/

License: MIT License

JavaScript 19.97% HTML 10.17% CSS 5.48% TypeScript 64.38%
payment payment-gateway payments react v3 flutterwave-react

react-v3's Introduction

Flutterwave v3 React Library

Publish React Package npm npm NPM

Introduction

The React SDK helps you create seamless payment experiences in your React mobile or web app. By connecting to our modal, you can start collecting payment in no time.

Available features include:

  • Collections: Card, Account, Mobile money, Bank Transfers, USSD, Barter, NQR.
  • Recurring payments: Tokenization and Subscriptions.
  • Split payments

Table of Contents

  1. Requirements
  2. Installation
  3. Initialization
  4. Usage
  5. Support
  6. Contribution Guidelines
  7. License
  8. Contributors
  9. Changelog

Requirements

  1. Flutterwave version 3 API keys
  2. Node version >= 6.9.x and npm >= 3.x.x
  3. React version >= 14

Installation

Install the SDK

$ npm install flutterwave-react-v3

# or
$ yarn add flutterwave-react-v3

Initialization

Import useFlutterwave to any component in your application and pass your config

import { useFlutterwave } from 'flutterwave-react-v3';
 const config = {
    public_key: 'FLWPUBK-**************************-X',
    tx_ref: Date.now(),
    amount: 100,
    currency: 'NGN',
    payment_options: 'card,mobilemoney,ussd',
    customer: {
      email: '[email protected]',
      phone_number: '070********',
      name: 'john doe',
    },
    customizations: {
      title: 'my Payment Title',
      description: 'Payment for items in cart',
      logo: 'https://st2.depositphotos.com/4403291/7418/v/450/depositphotos_74189661-stock-illustration-online-shop-log.jpg',
    },
  };

 useFlutterwave(config)

Usage

Add Flutterwave to your projects as a component or a react hook:

  1. As a Component
  2. Directly in your code
  3. Making recurrent payments

Components

import React from 'react';
import { FlutterWaveButton, closePaymentModal } from 'flutterwave-react-v3';

export default function App() {
   const config = {
    public_key: 'FLWPUBK-**************************-X',
    tx_ref: Date.now(),
    amount: 100,
    currency: 'NGN',
    payment_options: 'card,mobilemoney,ussd',
    customer: {
      email: '[email protected]',
      phone_number: '070********',
      name: 'john doe',
    },
    customizations: {
      title: 'My store',
      description: 'Payment for items in cart',
      logo: 'https://st2.depositphotos.com/4403291/7418/v/450/depositphotos_74189661-stock-illustration-online-shop-log.jpg',
    },
  };

  const fwConfig = {
    ...config,
    text: 'Pay with Flutterwave!',
    callback: (response) => {
       console.log(response);
      closePaymentModal() // this will close the modal programmatically
    },
    onClose: () => {},
  };

  return (
    <div className="App">
     <h1>Hello Test user</h1>
      <FlutterWaveButton {...fwConfig} />
    </div>
  );
}

Hooks

import React from 'react';
import { useFlutterwave, closePaymentModal } from 'flutterwave-react-v3';

export default function App() {
  const config = {
    public_key: 'FLWPUBK-**************************-X',
    tx_ref: Date.now(),
    amount: 100,
    currency: 'NGN',
    payment_options: 'card,mobilemoney,ussd',
    customer: {
      email: '[email protected]',
       phone_number: '070********',
      name: 'john doe',
    },
    customizations: {
      title: 'my Payment Title',
      description: 'Payment for items in cart',
      logo: 'https://st2.depositphotos.com/4403291/7418/v/450/depositphotos_74189661-stock-illustration-online-shop-log.jpg',
    },
  };

  const handleFlutterPayment = useFlutterwave(config);

  return (
    <div className="App">
     <h1>Hello Test user</h1>

      <button
        onClick={() => {
          handleFlutterPayment({
            callback: (response) => {
               console.log(response);
                closePaymentModal() // this will close the modal programmatically
            },
            onClose: () => {},
          });
        }}
      >
        Payment with React hooks
      </button>
    </div>
  );
}

Recurring Payments

Pass the payment plan ID into your payload to make recurring payments.

import React from 'react';
import { useFlutterwave, closePaymentModal } from 'flutterwave-react-v3';

export default function App() {
  const config = {
    public_key: 'FLWPUBK-**************************-X',
    tx_ref: Date.now(),
    amount: 100,
    currency: 'NGN',
     payment_options="card",
    payment_plan="3341",
    customer: {
      email: '[email protected]',
      phone_number: '070********',
      name: 'john doe',
    },
    meta = { counsumer_id: "7898", consumer_mac: "kjs9s8ss7dd" },
    customizations: {
      title: 'my Payment Title',
      description: 'Payment for items in cart',
      logo: 'https://st2.depositphotos.com/4403291/7418/v/450/depositphotos_74189661-stock-illustration-online-shop-log.jpg',
    },
  };

  const handleFlutterPayment = useFlutterwave(config);

  return (
    <div className="App">
     <h1>Hello Test user</h1>

      <button
        onClick={() => {
          handleFlutterPayment({
            callback: (response) => {
               console.log(response);
                closePaymentModal() // this will close the modal programmatically
            },
            onClose: () => {},
          });
        }}
      >
        Payment with React hooks
      </button>
    </div>
  );
}

Parameters

Read more about our parameters and how they can be used here.

Parameter Always Required ? Description
public_key True Your API public key
tx_ref True Your transaction reference. This MUST be unique for every transaction
amount True Amount to charge the customer.
currency False currency to charge in. Defaults to NGN
integrity_hash False This is a sha256 hash of your FlutterwaveCheckout values, it is used for passing secured values to the payment gateway.
payment_options True This specifies the payment options to be displayed e.g - card, mobilemoney, ussd and so on.
payment_plan False This is the payment plan ID used for Recurring billing
redirect_url False 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.
customer True This is an object that can contains your customer details: e.g - 'customer': {'email': '[email protected]','phone_number': '08012345678','name': 'Takeshi Kovacs' }
subaccounts False This is an array of objects containing the subaccount IDs to split the payment into. Check our Split Payment page for more info
meta False 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 True 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' }
callback (function) False This is the function that runs after payment is completed
close (function) False This is the function that runs after payment modal is closed

Other methods and descriptions:

Methods provided by the React SDK:

Method Name Parameters Returns Description
closePaymentModal Null Null This methods allows you to close the payment modal via code.

Please checkout Flutterwave Documentation for other available options you can add to the tag.

Debugging Errors

We understand that you may run into some errors while integrating our library. You can read more about our error messages here.

For authorization and validation error responses, double-check your API keys and request. If you get a server error, kindly engage the team for support.

Support

For additional assistance using this library, please create an issue on the Github repo or contact the developer experience (DX) team via email or on slack.

You can also follow us @FlutterwaveEng and let us know what you think 😊.

Contribution Guidelines

We welcome contributions from the community. Read more about our community contribution guidelines here.

License

By contributing to this library, you agree that your contributions will be licensed under its MIT license.

Copyright (c) Flutterwave Inc.

Contributors

react-v3's People

Contributors

chijiokeflw avatar corneliusyaovi avatar cynthiailojeme avatar ekene-eze avatar korneliosyaovi avatar ugwumadu116 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

react-v3's Issues

React Modal mobile money test payment not going through

Hi,
I am trying to test the flutterwave react package. Credit card tests go through just fine but the Mobile Money ones fail. I pass in all the appropriate params as defined in the documentation. But when I choose the mobile money payment option, fill in the phone number (MTN Zambia). I just get the OTP SMS (12345) on my phone but nothing happens on the modal. It just stays on the same page (see below). Furthermore, on my flutterwave dashboard, no mobile money transactions show up. Again, only the credit card test transactions go through. I also don't get a callback in my code. Why is this?
Capture

Serious bug! UseFlutterwave caches previous callbacks and repeats them

After a transaction is successful a callback is triggered as usual, but if the user does not refresh the page and then decides to make another payment, the callback for the second transaction plus that of the first transaction are triggered. And when a third transaction is done the callbacks for the first, second and third transactions are triggered thereby sending the request to the server 3 times. A fourth transaction triggers 4 times, and so on, until the page is refreshed. It seems the previous callbacks are cached in memory and then run all over again before running the callback of the latest. This is a very dangerous issue and it should be looked at very urgently.

const [resetConfigKey, setResetConfigKey] = useState(0);
  const [paymentConfig, setpPaymentConfig] = useState({
    public_key: process.env.REACT_APP_FLUTTERWAVE_PUBLIC_KEY,
    payment_options: "all",
    customizations: {
      // title: 'my Payment Title',
      // description: 'Payment for items in cart',
      logo: process.env.REACT_APP_FAVICON_URL,
    },
  });

  const handleFlutterPayment = useFlutterwave(paymentConfig, [resetConfigKey]);

 const handleUpdatePaymentConfig = (values) => {
    setpPaymentConfig({
      ...paymentConfig,
      tx_ref: transaction_ref,
      amount: values.amount,
      currency: values.currency,
      customer: {
        email: values.email,
        // phonenumber: '07064586146',
        name: `${values.first_name} ${values.last_name}`,
      },
    });

    // Reset the config key to reload UseFlutterwave
    setResetConfigKey(() => {
      const k = resetConfigKey;
      return k + 1;
    });
  };
const handlePayment = ()=>{
handleFlutterPayment({
        callback: (resp) => {
          dispatch(
            sendToServer({
              email: values.email,
              first_name: values.first_name,
              last_name: values.last_name,
            })
          ).then((res) => {
            closePaymentModal();

            if (res.error) {
            } else {
              if (res.success == true) {
                NotificationManager.success(res.message, "Success!")
              }
            }
              }
            }
          });
        },
        onClose: () => {

        },
      });
}

useFlutterwave hooks throws uncaught exception if network error

I don't believe this hook should throw errors. It is hard to handle since a hook must be top-level.

I suggest, an implementation that sets the error in state and returns it from the useFlutterwave hook.

The user can display fallback UI or use error boundaries to avoid crushing our apps.

React component not calling webhook

So I am try to test this component with webhook on the backend but when i make payment, the webhook isn't called, therefore db isn't updated. This is what my config looks like

{
    tx_ref: 'ref',
    customer: {
      email: userData?.email,
      phonenumber: userData?.phoneNumber,
      name: `${userData?.firstName} ${userData?.lastName}`,
    },
    amount: 0,
    public_key: process.env.REACT_APP_FLUTTERWAVE_PUBLIC_KEY!,
    payment_options: 'card,mobilemoney,ussd',
    customizations: {
      title: 'Top up balance',
      description: `Fund top up for ${currentBalance}`,
      logo: '',
    },
  })

I am using the useFlutterwave method this way

  const handleFlutterPayment = useFlutterwave(config);

  useEffect(() => {
    if (trxRef.paymentReference && data.channel === 'rave') {
      handleFlutterPayment({
        callback: (response) => {
          console.log(response);
          closePaymentModal();
        },
        onClose: () => {},
      });
    }
  }, [trxRef.paymentReference, data.channel, handleFlutterPayment]);

Payment works but webhook isn't called

Not able to close programmatically.

I'm having a blogging site and implemented the flutterwave payment gateway.
After successful payment I need to close the payment gateway modal programmatically from callback function. I could not find any documentation to achieve this.

flutterwave-react-v3 payment pop-up throwing 414 Request-URI Too Large in prod

Description

We are getting 414 Request-URI Too Large in Live Mode while loading the payment popup with flutterwave-react-v3 plugin.

image

Configuration

  • API Version: v3
  • Environment: live mode
  • Browser: all

Additional Information

By inspecting a bit I figured out this is due to an internal request made by the plugin to :

https://checkout-v3-ui-prod.tls-flutterwave.com/?__=LONG_TOKEN

Would suggest to check the maximum number and size of buffers used for reading large client request header.

Thanks! 🙏

Customizations object

Not really an issue. But why is the customizations object required to initialize a transaction? I was previously using the standard API and I didn't need to specify any customization object but my nextjs (TS) project keeps telling me its important (what for pls).. it should be optional. we shouldn't have to use ts-ignore just to get rid of the TS error

HALLY

Have you read our Code of Conduct? By filing an Issue, you are expected to comply with it, including treating everyone with respect

Do you want to ask a question? Are you looking for support? The developer slack is the best place for getting support

Description

Steps to Reproduce

Expected behaviour:

Actual behaviour:

Reproduces how often:

Configuration

  • API Version:
  • Environment:
  • Browser:
  • Language:

Additional Information

Cannot install flutterwave-react-v3 for react version 17.0.2

Steps to replicate.

Create a new react project using the latest react version (17.02)

install flutterwave-react-v3 using "npm install flutterwave-react-v3"

ERROR MESSAGE:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"^17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^15.0.0 || ^16.0.0" from [email protected]
npm ERR! node_modules/flutterwave-react-v3
npm ERR! flutterwave-react-v3@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/heyphord/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! /XXX/.npm/_logs/2021-08-06T23_59_07_267Z-debug.log

TypeError: __webpack_require__.i(...) is not a function

TypeError: webpack_require.i(...) is not a function
useFWScript
webpack:////flutterwave-react-v3/dist/index.es.js:90
useFlutterwave
webpack:///
/flutterwave-react-v3/dist/index.es.js:138
PaymentForm.render
webpack:///src/components/Booking/Payment/PaymentForm.js:490
finishClassComponent
webpack:////react-dom/cjs/react-dom.development.js:13194
updateClassComponent
webpack:///
/react-dom/cjs/react-dom.development.js:13156
beginWork
webpack:////react-dom/cjs/react-dom.development.js:13825
performUnitOfWork
webpack:///
/react-dom/cjs/react-dom.development.js:15864
workLoop
webpack:////react-dom/cjs/react-dom.development.js:15903
renderRoot
webpack:///
/react-dom/cjs/react-dom.development.js:15943
performWorkOnRoot
webpack:///~/react-dom/cjs/react-dom.development.js:16561

Can't find variable: document

I keep getting the error Can't find variable: document when ever I initialise
const handleFlutterPayment = useFlutterwave(config);

Nothing seems to be working on pop-up.

I'm trying to test the flutterwave-react-v3 package and nothing seems to be working. And all steps were followed according to the documentation.

E.g tried to add a card but the input test doesn't focus. I also tried to select a bank but the options seem not to be showing.

Could this be because I'm in a test mode. I don't this though

Checkout plugin theme-ing

Have you read our Code of Conduct? By filing an Issue, you are expected to comply with it, including treating everyone with respect

Do you want to ask a question? Are you looking for support? The developer slack is the best place for getting support

Description

Add a config to theme the plugin with one's platform's theme colors.

Expected behaviour:
A config property to pass a theme so that the plugin GUI theme matches one's platform theme

flutterwave-react-v3 payment pop-up does not load on production server but loads on local host

Issue :
The payment dialog/pop works normally when working on localhost but when I deployed the pop does not show when I click the button that triggers the pop-up, hence I cannot test the payment flow :putting card details and all card related information.

This is occurring on the latest version which is 1.2.0 . I haven't tested on the prior versions if the issue is present.

I can't provide the screenshot since the pop is not showing at all.

Can't Install Flutterwave-React-v3 on react v17.0.1

I was trying to install Flutterwave-React-v3 on a react native project with react version 17.0.1 and i was receiving this error

Please Help

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"17.0.1" from the root project
npm ERR! peer react@"^15.0.0 || ^17.0.0" from [email protected]
npm ERR! node_modules/flutterwave-react-v3
npm ERR! flutterwave-react-v3@"" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"17.0.2" from [email protected]
npm ERR! node_modules/react-dom
npm ERR! peer react-dom@"^15.0.0 || ^17.0.0" from [email protected]
npm ERR! node_modules/flutterwave-react-v3
npm ERR! flutterwave-react-v3@"
" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/oluwaferanmi/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/oluwaferanmi/.npm/_logs/2021-11-16T12_12_06_443Z-debug.log

Using hooks doesn't make so much sense

Using hooks doesn't make so much sense because it assume you have all the values needed to integrate already, however what if we fetch some data from the database, how do we then dynamically call the hook knowing fully well you cannot call a hook from within a function?

Invalid public key passed

Hi,

I am trying to integrate this package into a React v17 project using hooks. I have done exactly as described in the README file, created an account at https://ravesandbox.flutterwave.com/ and got a public key from the dashboard settings. But i keep getting an error response of Invalid public key passed in the payment modal.

Kindly assist.

Ready for Production?

Is this library ready to be used in a production environment? If it is not, is there a timeline of when it will be

pakage requirements outdated

Flutterwave version 3 API keys
Node version >= 6.9.x and npm >= 3.x.x
React version >= 14

requirement out dated not performing well on updated technoloJesus

Issues implementing the payment hook in Next Js

I am unable to successfully implement the library in my Next Js project.

Issue:
When a payment is initialized, when the input for card details are clicked or the select drop down for banks, they focus and loose focus in split seconds making it impossible to type in or select anything. This also happens when you click on the Pay button in the modal, it does nothing.
However, these clicks events create network requests to fw-events-ge.herokuapp.com and nothing happens after.

I don't notice this issue with CRA React project, seems it's peculiar to Next JS.
Attached is a screen shot of the network requests from the clicks.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.