├── .editorconfig ├── .env.example ├── .eslintignore ├── .eslintrc.js ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── config.yml ├── images │ ├── flutterwave-styled-button.png │ ├── github-preview-android.gif │ ├── github-preview-ios.gif │ ├── pay-with-flutterwave-custom.png │ └── pay-with-flutterwave.png └── workflows │ └── npm-publish.yml ├── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc.js ├── .releaserc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── README.v2.md ├── __tests__ ├── CustomPropTypesRules.spec.ts ├── FlutterwaveButton.spec.tsx ├── FlutterwaveCheckout.spec.tsx ├── FlutterwaveInit.spec.ts ├── FlutterwaveInitError.spec.ts ├── FlutterwaveInitV2.spec.ts ├── PayWithFlutterwave.spec.tsx ├── PayWithFlutterwaveBase.spec.tsx ├── PayWithFlutterwaveV2.spec.tsx ├── ResponseParser.spec.ts └── __snapshots__ │ ├── FlutterwaveButton.spec.tsx.snap │ ├── FlutterwaveCheckout.spec.tsx.snap │ ├── PayWithFlutterwave.spec.tsx.snap │ ├── PayWithFlutterwaveBase.spec.tsx.snap │ └── PayWithFlutterwaveV2.spec.tsx.snap ├── babel.config.js ├── dist ├── FlutterwaveButton.d.ts ├── FlutterwaveButton.d.ts.map ├── FlutterwaveButton.js ├── FlutterwaveCheckout.d.ts ├── FlutterwaveCheckout.d.ts.map ├── FlutterwaveCheckout.js ├── FlutterwaveInit.d.ts ├── FlutterwaveInit.d.ts.map ├── FlutterwaveInit.js ├── FlutterwaveInitV2.d.ts ├── FlutterwaveInitV2.d.ts.map ├── FlutterwaveInitV2.js ├── PayWithFlutterwave.d.ts ├── PayWithFlutterwave.d.ts.map ├── PayWithFlutterwave.js ├── PayWithFlutterwaveV2.d.ts ├── PayWithFlutterwaveV2.d.ts.map ├── PayWithFlutterwaveV2.js ├── PaywithFlutterwaveBase.d.ts ├── PaywithFlutterwaveBase.d.ts.map ├── PaywithFlutterwaveBase.js ├── assets │ ├── loader.gif │ └── pry-button-content.png ├── configs.d.ts ├── configs.d.ts.map ├── configs.js ├── index.d.ts ├── index.d.ts.map ├── index.js └── utils │ ├── CustomPropTypesRules.d.ts │ ├── CustomPropTypesRules.d.ts.map │ ├── CustomPropTypesRules.js │ ├── FlutterwaveInitError.d.ts │ ├── FlutterwaveInitError.d.ts.map │ ├── FlutterwaveInitError.js │ ├── ResponseParser.d.ts │ ├── ResponseParser.d.ts.map │ └── ResponseParser.js ├── docs ├── AbortingPaymentInitialization.md └── v2 │ └── AbortingPaymentInitialization.md ├── global.d.ts ├── jest.config.js ├── package.json ├── setExample.js ├── setupJest.js ├── src ├── FlutterwaveButton.tsx ├── FlutterwaveCheckout.tsx ├── FlutterwaveInit.ts ├── FlutterwaveInitV2.ts ├── PayWithFlutterwave.tsx ├── PayWithFlutterwaveV2.tsx ├── PaywithFlutterwaveBase.tsx ├── assets │ ├── loader.gif │ └── pry-button-content.png ├── configs.ts ├── index.ts └── utils │ ├── CustomPropTypesRules.ts │ ├── FlutterwaveInitError.ts │ └── ResponseParser.ts ├── timeTravel.js └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | # Unix-style newlines with a newline ending every file 5 | [*] 6 | end_of_line = lf 7 | insert_final_newline = true 8 | 9 | # Matches multiple files with brace expansion notation 10 | # Set default charset 11 | [*.{js,py,ts,tsx}] 12 | charset = utf-8 13 | 14 | # Indentation override for all JS under lib directory 15 | [*] 16 | indent_style = space 17 | indent_size = 2 18 | 19 | # Matches the exact files either package.json or .travis.yml 20 | [{package.json,.travis.yml}] 21 | indent_style = space 22 | indent_size = 2 23 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | RN_FLW_EXAMPLE_PROJECT="path-to-your-example-project" 2 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: '@react-native-community', 4 | parser: '@typescript-eslint/parser', 5 | plugins: ['@typescript-eslint'], 6 | }; 7 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Have you read our [Code of Conduct](https://github.com/Flutterwave/React-Native/blob/master/CONTRIBUTING.md)? By filing an Issue, you are expected to comply with it, including treating everyone with respect. 11 | 12 | # Description 13 | 14 | 15 | # Steps to Reproduce 16 | 17 | 1. 18 | 2. 19 | 3. 20 | 21 | ## Expected behaviour 22 | 23 | 24 | ## Actual behaviour 25 | 26 | 27 | ## Reproduces how often 28 | 29 | 30 | # Configuration 31 | - API Version: 32 | - Environment: 33 | - Browser: 34 | - Language: 35 | 36 | # Additional Information 37 | 38 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Developer Support Forum 4 | url: https://forum.flutterwave.com 5 | about: If you're having general trouble with your integration, Kindly contact our support team. 6 | -------------------------------------------------------------------------------- /.github/images/flutterwave-styled-button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/.github/images/flutterwave-styled-button.png -------------------------------------------------------------------------------- /.github/images/github-preview-android.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/.github/images/github-preview-android.gif -------------------------------------------------------------------------------- /.github/images/github-preview-ios.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/.github/images/github-preview-ios.gif -------------------------------------------------------------------------------- /.github/images/pay-with-flutterwave-custom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/.github/images/pay-with-flutterwave-custom.png -------------------------------------------------------------------------------- /.github/images/pay-with-flutterwave.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/.github/images/pay-with-flutterwave.png -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Install npm dependencies 16 | run: | 17 | npm install 18 | - uses: actions/setup-node@v1 19 | with: 20 | node-version: 12 21 | - run: npm ci 22 | 23 | publish-npm: 24 | needs: build 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v2 28 | - uses: actions/setup-node@v1 29 | with: 30 | node-version: 12 31 | registry-url: https://registry.npmjs.org/ 32 | - run: npm ci 33 | - run: npm publish 34 | env: 35 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | project.xcworkspace 24 | Pods/ 25 | 26 | # Android/IJ 27 | # 28 | .idea 29 | *.iml 30 | .gradle 31 | local.properties 32 | lib/android/src/main/gen 33 | 34 | # node.js 35 | # 36 | node_modules/ 37 | npm-debug.log 38 | yarn-error.log 39 | package-lock.json 40 | 41 | # Rubygem bundles 42 | # 43 | bundles/ 44 | 45 | # VS Code 46 | .vscode/* 47 | !.vscode/settings.json 48 | !.vscode/tasks.json 49 | !.vscode/launch.json 50 | !.vscode/extensions.json 51 | 52 | # dist/ 53 | .classpath 54 | .project 55 | .settings/ 56 | 57 | coverage/ 58 | .env 59 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | project.xcworkspace 24 | Pods/ 25 | 26 | # Android/IJ 27 | # 28 | .idea 29 | *.iml 30 | .gradle 31 | local.properties 32 | lib/android/src/main/gen 33 | 34 | # node.js 35 | # 36 | node_modules/ 37 | npm-debug.log 38 | yarn-error.log 39 | package-lock.json 40 | 41 | # Rubygem bundles 42 | # 43 | bundles/ 44 | 45 | # VS Code 46 | .vscode/* 47 | !.vscode/settings.json 48 | !.vscode/tasks.json 49 | !.vscode/launch.json 50 | !.vscode/extensions.json 51 | 52 | # dist/ 53 | .classpath 54 | .project 55 | .settings/ 56 | 57 | 58 | # devevelopment and docs related files and folders 59 | __tests__/ 60 | .github/ 61 | coverage/ 62 | docs/ 63 | src/ 64 | .editorconfig 65 | .eslintignore 66 | .eslintrc.js 67 | .gitignore 68 | .npmignore 69 | .prettierignore 70 | .prettierrc.js 71 | .releaserc 72 | .babel.config.js 73 | CONTRIBUTING.md 74 | golbal.d.ts 75 | jest.config.js 76 | README.md 77 | setupJest.js 78 | tsconfig.json 79 | 80 | .env 81 | .env.example 82 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | // https://prettier.io/docs/en/options.html 2 | 3 | module.exports = { 4 | bracketSpacing: false, 5 | jsxBracketSameLine: true, 6 | singleQuote: true, 7 | trailingComma: 'all', 8 | }; 9 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "@semantic-release/commit-analyzer", 4 | "@semantic-release/release-notes-generator", 5 | "@semantic-release/npm", 6 | "@semantic-release/github", 7 | [ 8 | "@semantic-release/git", 9 | { 10 | "assets": "package.json", 11 | "message": "chore(release): ${nextRelease.version} [skip ci] \n\n${nextRelease.notes}" 12 | } 13 | ] 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thank you for your interest in contributing! Please feel free to put up a PR for any issue or feature request. 4 | 5 | ## Creating issues 6 | 7 | If you notice any bugs in the app, see some code that can be improved, or have features you would like to be added, please create an issue! 8 | 9 | If you want to open a PR that fixes a bug or adds a feature, then we can't thank you enough! It is definitely appreciated if an issue has been created before-hand so it can be discussed first. 10 | 11 | ## Submitting pull requests 12 | 13 | ### Modifying flutterwave-react-native 14 | 1. Fork this repository 15 | 2. Clone your fork 16 | 3. Make a branch for your feature or bug fix (i.e. `git checkout -b what-im-adding`) 17 | 4. Work your magic 18 | 19 | ### Testing your changes 20 | Depending on the changes you make you might want to test to see if the feature/fix works correctly. 21 | Use the following steps to test your newly added feature/fix. 22 | 1. Set up your react-native example project or use one you already have. 23 | 2. Create a `.env` file in the root of the library (flutterwave-react-native). 24 | 3. Add **RN_FLW_EXAMPLE_PROJECT** to the `.env` file it's value should be an absolute path to the install destination in your example project. 25 | **E.g.** `RN_FLW_EXAMPLE_PROJECT="/Users/your-name/projects/example-project/src"`. 26 | 4. Run the following command `npm run set-example`. 27 | 28 | Following these steps will result in you building and copy the built version of the library in the following directory `/Users/your-name/projects/example-project/src/flutterwave-react-native`, you can then go ahead an import the library from within your example project from the location the library has been copied to. 29 | 30 | ### Writting Tests 31 | We currently don't have strict rules for writting tests but when writting one be sure to make your tests and their captions clear and coincise, test only what you added, and then follow up with the dependencies if need be. 32 | Tests are also not a prerequisite for making PRs but if you do add any for the feature you write, merging your PR will happen faster. 33 | 34 | ### Commiting 35 | This project is [Commitzen](https://github.com/commitizen/cz-cli) friendly and uses the [Angular commit conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) for creating commits, please ensure you use this when commiting your changes. 36 | To start a commit simply run the following cli command from within the project `npm run commit` this will start a wizard that will walk you through the necessary steps for creating a commit. 37 | 38 | ### Opening the Pull Request 39 | 40 | 1. Commit your changes with a message following the [Angular commit conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines). 41 | 2. Push your branch to your fork 42 | 3. Create a pull request from your branch on your fork to `master` on this repo 43 | 4. Have your branch get merged in! :white_check_mark: 44 | 45 | If you experience a problem at any point, please don't hesitate to file an issue to get some assistance! 46 | 47 | With love from Flutterwave. :yellow_heart: 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Rebecca Hughes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /__tests__/CustomPropTypesRules.spec.ts: -------------------------------------------------------------------------------- 1 | import 'react-native'; 2 | import {PaymentOptionsPropRule} from '../src/utils/CustomPropTypesRules'; 3 | const PropName = 'payment_options'; 4 | const PAYMENT_OPTIONS = ['barter', 'card', 'banktransfer'] 5 | 6 | describe('CustomPropTypes.PaymentOptionsPropRule', () => { 7 | it ('returns null if prop is not defined in props', () => { 8 | const result = PaymentOptionsPropRule(PAYMENT_OPTIONS)({}, PropName); 9 | expect(result).toBe(null); 10 | }); 11 | 12 | it ('returns error if prop is not a string', () => { 13 | const result = PaymentOptionsPropRule(PAYMENT_OPTIONS)({[PropName]: []}, PropName); 14 | expect(result !== null).toBe(true); 15 | expect(result.message).toContain('should be a string.'); 16 | }); 17 | 18 | it ('returns error if prop includes invalid payment option', () => { 19 | const result = PaymentOptionsPropRule(PAYMENT_OPTIONS)({[PropName]: 'barter, foo'}, PropName); 20 | expect(result !== null).toBe(true); 21 | expect(result.message).toContain('must be any of the following values.'); 22 | }); 23 | 24 | it ('returns null if payment options are valid', () => { 25 | const result = PaymentOptionsPropRule(PAYMENT_OPTIONS)({[PropName]: 'barter'}, PropName); 26 | expect(result).toBe(null); 27 | }); 28 | }) 29 | -------------------------------------------------------------------------------- /__tests__/FlutterwaveButton.spec.tsx: -------------------------------------------------------------------------------- 1 | import 'react-native'; 2 | import React from 'react'; 3 | import {Text} from 'react-native'; 4 | import renderer from 'react-test-renderer'; 5 | import FlutterwaveButton from '../src/FlutterwaveButton'; 6 | const testID = 'flw-button'; 7 | 8 | describe('', () => { 9 | it('renders pay with flutterwave by default', () => { 10 | // create test renderer 11 | const TestRenderer = renderer.create(); 12 | // run assertions 13 | expect(TestRenderer.toJSON()).toMatchSnapshot(); 14 | }); 15 | 16 | it('renders with overlay and inactive style of button is disabled', () => { 17 | // create test renderer 18 | const TestRenderer = renderer.create(); 19 | // run assertions 20 | expect(TestRenderer.toJSON()).toMatchSnapshot(); 21 | }); 22 | 23 | it('applies left aligned style if alignLeft prop is present', () => { 24 | // create test renderer 25 | const TestRenderer = renderer.create(); 26 | // run assertions 27 | expect(TestRenderer.toJSON()).toMatchSnapshot(); 28 | }); 29 | 30 | it('replaces pay with flutterwave image with children', () => { 31 | // create test renderer 32 | const TestRenderer = renderer.create( 33 | 34 | Hello, World! 35 | 36 | ); 37 | // run assertions 38 | expect(TestRenderer.toJSON()).toMatchSnapshot(); 39 | }); 40 | 41 | it('fires on press if set', () => { 42 | // create onPress function 43 | const onPress = jest.fn(); 44 | // create test renderer 45 | const TestRenderer = renderer.create( 46 | 47 | Hello, World! 48 | 49 | ); 50 | // fire onPress function 51 | TestRenderer.root.findByProps({testID}).props.onPress(); 52 | // run assertions 53 | expect(TestRenderer.root.findByProps({testID}).props.onPress).toBeDefined(); 54 | expect(onPress).toBeCalledTimes(1); 55 | }); 56 | }); 57 | 58 | -------------------------------------------------------------------------------- /__tests__/FlutterwaveCheckout.spec.tsx: -------------------------------------------------------------------------------- 1 | import 'react-native'; 2 | import React from 'react'; 3 | import {TouchableOpacity, Alert} from 'react-native'; 4 | import renderer from 'react-test-renderer'; 5 | import FlutterwaveCheckout, {FlutterwaveCheckoutError} from '../src/FlutterwaveCheckout'; 6 | import timeTravel, {setupTimeTravel} from '../timeTravel'; 7 | import {REDIRECT_URL} from '../src/configs'; 8 | import WebView from 'react-native-webview'; 9 | const link = 'http://example.com'; 10 | 11 | beforeEach(() => setupTimeTravel()); 12 | afterEach(() => jest.useRealTimers()); 13 | describe('', () => { 14 | it('renders with modal closed if visible prop is not true', () => { 15 | // create test renderer 16 | const TestRenderer = renderer.create( 17 | {}} /> 18 | ); 19 | // run assertions 20 | expect(TestRenderer.toJSON()).toMatchSnapshot(); 21 | }); 22 | 23 | it('renders with modal open if visible props is true', () => { 24 | // create test renderer 25 | const TestRenderer = renderer.create( 26 | {}} visible /> 27 | ); 28 | // simulate animation timeframes 29 | timeTravel(); 30 | // run assertions 31 | expect(TestRenderer.toJSON()).toMatchSnapshot(); 32 | }); 33 | 34 | it('fires onRedirect if redirect url is correct', (done) => { 35 | const onRedirect = jest.fn(); 36 | const url = REDIRECT_URL + '?foo=bar'; 37 | // create test renderer 38 | const TestRenderer = renderer.create( 39 | 40 | ); 41 | // fire on navigation state change 42 | TestRenderer.root.findByType(WebView).props.onNavigationStateChange({url}); 43 | // simulate animation timeframes 44 | timeTravel(); 45 | // revert to using real timers 46 | jest.useRealTimers() 47 | // wait for promise to resolve 48 | setTimeout(() => { 49 | // run assertions 50 | expect(onRedirect).toBeCalledTimes(1); 51 | expect(onRedirect).toBeCalledWith({foo: 'bar'}); 52 | done(); 53 | }, 10) 54 | }); 55 | 56 | it('does not fire onRedirect if redirect url is not correct', (done) => { 57 | const onRedirect = jest.fn(); 58 | const url = 'http://example/com?foo=bar'; 59 | // create test renderer 60 | const TestRenderer = renderer.create( 61 | 62 | ); 63 | // fire on navigation state change 64 | TestRenderer.root.findByType(WebView).props.onNavigationStateChange({url}); 65 | // simulate animation timeframes 66 | timeTravel(); // revert to using real timers 67 | jest.useRealTimers() 68 | // wait for promise to resolve 69 | setTimeout(() => { 70 | // run assertions 71 | expect(onRedirect).toBeCalledTimes(0); 72 | done(); 73 | }) 74 | }); 75 | 76 | it('asks user to confirm abort when use taps on the backdrop', () => { 77 | // create test renderer 78 | const TestRenderer = renderer.create( 79 | {}} visible link={link} /> 80 | ); 81 | // call backdrop onPress 82 | TestRenderer.root.findByProps({testID: 'flw-checkout-backdrop'}).props.onPress(); 83 | // run assertions 84 | expect(Alert.alert).toHaveBeenCalledTimes(1); 85 | expect(Alert.alert).toHaveBeenCalledWith( 86 | expect.any(String), 87 | expect.stringContaining('cancel this payment?'), 88 | expect.any(Array), 89 | ); 90 | }); 91 | 92 | it('calls onAbort if defined', (done) => { 93 | const onAbort = jest.fn(); 94 | // create test renderer 95 | const TestRenderer = renderer.create( 96 | {}} onAbort={onAbort} visible link={link} /> 97 | ); 98 | // call backdrop onPress 99 | TestRenderer.root.findByProps({testID: 'flw-checkout-backdrop'}).props.onPress(); 100 | // call the cancel alert button 101 | Alert.alert.mock.calls[0][2][1].onPress(); 102 | // simulate animation timeframes 103 | timeTravel(); 104 | // revert to using real timers 105 | jest.useRealTimers(); 106 | // wait for animateOut promise to resolve 107 | setTimeout(() => { 108 | // run assertions 109 | expect(Alert.alert).toHaveBeenCalledTimes(1); 110 | expect(onAbort).toHaveBeenCalledTimes(1); 111 | done(); 112 | }); 113 | }); 114 | 115 | it('renders error with hasLink prop as true if there is a link', () => { 116 | const onAbort = jest.fn(); 117 | // create test renderer 118 | const TestRenderer = renderer.create( 119 | {}} onAbort={onAbort} visible link={link} /> 120 | ); 121 | // create error test renderer 122 | const ErrorTestRenderer = renderer.create( 123 | TestRenderer.root.findByType(WebView).props.renderError() 124 | ); 125 | // run assertions 126 | expect(ErrorTestRenderer.root.props.hasLink).toEqual(true); 127 | }); 128 | 129 | it('renders error with hasLink prop as false if there is no link', () => { 130 | const onAbort = jest.fn(); 131 | // create test renderer 132 | const TestRenderer = renderer.create( 133 | {}} onAbort={onAbort} visible link={link} /> 134 | ); 135 | // create error test renderer 136 | const ErrorTestRenderer = renderer.create( 137 | TestRenderer.root.findByType(WebView).props.renderError() 138 | ); 139 | // run assertions 140 | expect(ErrorTestRenderer.root.props.hasLink).toEqual(true); 141 | }); 142 | 143 | // it('fires reload when called if webview reference is set', () => { 144 | // const onAbort = jest.fn(); 145 | // // create test renderer 146 | // const TestRenderer = renderer.create( 147 | // {}} 149 | // onAbort={onAbort} 150 | // visible 151 | // link={link} 152 | // /> 153 | // ); 154 | // // get WebView test renderer 155 | // const WebViewTestRenderer = TestRenderer.root.findByType(WebView); 156 | // // spy on reload method on webview 157 | // const reload = jest.spyOn(WebViewTestRenderer.instance, 'reload'); 158 | // // create error test renderer 159 | // const ErrorTestRenderer = renderer.create( 160 | // TestRenderer.root.findByType(WebView).props.renderError() 161 | // ); 162 | // // call try again function on webview error 163 | // ErrorTestRenderer.root.props.onTryAgain(); 164 | // // run assertions 165 | // expect(reload).toHaveBeenCalledTimes(1); 166 | // expect(1).toBeTruthy(); 167 | // }); 168 | 169 | it("returns query params if available in url passed to getRedirectParams", (done) => { 170 | const url = new String(REDIRECT_URL + '?foo=bar'); 171 | // spy on split method on String object 172 | const split = jest.spyOn(url, 'split'); 173 | // create test renderer 174 | const TestRenderer = renderer.create( 175 | {}} visible link={link} /> 176 | ); 177 | // fire on navigation state change 178 | TestRenderer.root.findByType(WebView).props.onNavigationStateChange({url}); 179 | // simulate animation timeframes 180 | timeTravel(); 181 | // revert to using real times 182 | jest.useRealTimers(); 183 | // wait for animateOut promise to resolve 184 | setTimeout(() => { 185 | // run assertions 186 | expect(split).toHaveBeenCalledTimes(2); 187 | done(); 188 | }); 189 | }); 190 | 191 | it("does not return query params if not available in url passed to getRedirectParams", (done) => { 192 | const url = new String(REDIRECT_URL); 193 | // spy on split method on String object 194 | const split = jest.spyOn(url, 'split'); 195 | // create test renderer 196 | const TestRenderer = renderer.create( 197 | {}} visible link={link} /> 198 | ); 199 | // fire on navigation state change 200 | TestRenderer.root.findByType(WebView).props.onNavigationStateChange({url}); 201 | // simulate animation timeframes 202 | timeTravel(); 203 | // revert to using real timers 204 | jest.useRealTimers(); 205 | // wait for animateOut promise to resolve 206 | setTimeout(() => { 207 | // run assertions 208 | expect(split).toHaveBeenCalledTimes(1); 209 | done(); 210 | }) 211 | }); 212 | }); 213 | 214 | describe('', () => { 215 | it('has a retry button if hasLink prop is true', () => { 216 | // create test renderer 217 | const TestRenderer = renderer.create( 218 | {}} /> 219 | ); 220 | // simulate animation timeframes 221 | timeTravel(); 222 | // font retry button 223 | const RetryButton = TestRenderer.root.findAllByType(TouchableOpacity) 224 | // run assertions 225 | expect(RetryButton).toHaveLength(1); 226 | }); 227 | 228 | it('does not have a retry button if hasLink prop is false', () => { 229 | // create test renderer 230 | const TestRenderer = renderer.create( 231 | {}} /> 232 | ); 233 | // simulate animation timeframes 234 | timeTravel(); 235 | // font retry button 236 | const RetryButton = TestRenderer.root.findAllByType(TouchableOpacity) 237 | // run assertions 238 | expect(RetryButton).toHaveLength(0); 239 | }); 240 | }); 241 | 242 | -------------------------------------------------------------------------------- /__tests__/FlutterwaveInit.spec.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInit, {FlutterwaveInitOptions} from '../src/FlutterwaveInit'; 2 | import {STANDARD_URL} from '../src/configs'; 3 | import FlutterwaveInitError from '../src/utils/FlutterwaveInitError'; 4 | 5 | const AUTHORIZATION = '[AUTHORIZATION]'; 6 | 7 | // fetch header 8 | const FETCH_HEADER = new Headers(); 9 | FETCH_HEADER.append('Content-Type', 'application/json'); 10 | FETCH_HEADER.append('Authorization', `Bearer ${AUTHORIZATION}`); 11 | 12 | // fetch body 13 | const FETCH_BODY: Omit = { 14 | redirect_url: 'http://flutterwave.com', 15 | amount: 50, 16 | currency: 'NGN', 17 | customer: { 18 | email: 'email@example.com', 19 | }, 20 | tx_ref: Date.now() + '-txref', 21 | payment_options: 'card', 22 | customizations: { 23 | title: 'Hello World', 24 | } 25 | } 26 | 27 | // payment options 28 | const INIT_OPTIONS: FlutterwaveInitOptions = { 29 | ...FETCH_BODY, 30 | authorization: AUTHORIZATION 31 | }; 32 | 33 | describe('', () => { 34 | it('runs a fetch request', async () => { 35 | // mock next fetch request 36 | fetchMock.mockOnce(JSON.stringify({ 37 | status: 'success', 38 | message: 'Payment link generated.', 39 | data: {link: 'http://example.com'}, 40 | })); 41 | try { 42 | // initialize payment 43 | await FlutterwaveInit(INIT_OPTIONS); 44 | // run assertions 45 | expect(global.fetch).toHaveBeenCalledTimes(1); 46 | expect(global.fetch).toHaveBeenCalledWith(STANDARD_URL, { 47 | body: JSON.stringify(FETCH_BODY), 48 | headers: FETCH_HEADER, 49 | method: 'POST', 50 | }); 51 | } catch (e) { 52 | // no error occurred 53 | } 54 | }); 55 | 56 | it('returns a payment link after initialization', async () => { 57 | const link = 'http://payment-link.com/checkout'; 58 | // mock next fetch request 59 | fetchMock.mockOnce(JSON.stringify({ 60 | status: 'success', 61 | message: 'Payment link generated.', 62 | data: {link}, 63 | })); 64 | try { 65 | // initialize payment 66 | const response = await FlutterwaveInit(INIT_OPTIONS) 67 | // run assertions 68 | expect(response).toEqual(link) 69 | } catch (e) { 70 | // no error occurred 71 | } 72 | }); 73 | 74 | it('includes error code and message of init error', async () => { 75 | const message = 'An error has occurred.'; 76 | // reject next fetch 77 | fetchMock.mockOnce(JSON.stringify({ 78 | status: 'error', 79 | message: message, 80 | })); 81 | try { 82 | // initialize payment 83 | await FlutterwaveInit(INIT_OPTIONS); 84 | } catch (error) { 85 | // run assertions 86 | expect(error.message).toEqual(message); 87 | expect(error.code).toEqual('STANDARD_INIT_ERROR'); 88 | } 89 | }); 90 | 91 | it('returns missing authorization request error code', async () => { 92 | const message = 'Authorization is required.'; 93 | // reject next fetch 94 | fetchMock.mockOnce(JSON.stringify({ 95 | status: 'error', 96 | message: message, 97 | })); 98 | try { 99 | // initialize payment 100 | await FlutterwaveInit(INIT_OPTIONS); 101 | } catch (error) { 102 | // run assertions 103 | expect(error.message).toEqual(message); 104 | expect(error.code).toEqual('AUTH_MISSING'); 105 | } 106 | }); 107 | 108 | it('returns invalid authorization request error code', async () => { 109 | const message = 'Authorization is invalid.'; 110 | // reject next fetch 111 | fetchMock.mockOnce(JSON.stringify({ 112 | status: 'error', 113 | message: message, 114 | })); 115 | try { 116 | // initialize payment 117 | await FlutterwaveInit(INIT_OPTIONS); 118 | } catch (error) { 119 | // run assertions 120 | expect(error.message).toEqual(message); 121 | expect(error.code).toEqual('AUTH_INVALID'); 122 | } 123 | }); 124 | 125 | it('returns field errors from request errors', async () => { 126 | const message = 'Missin fields.'; 127 | const errors = [{field: 'tx_ref', message: 'tx_ref is required'}]; 128 | // reject next fetch 129 | fetchMock.mockOnce(JSON.stringify({ 130 | status: 'error', 131 | message: message, 132 | errors: errors, 133 | })); 134 | try { 135 | // initialize payment 136 | await FlutterwaveInit(INIT_OPTIONS); 137 | } catch (error) { 138 | // run assertions 139 | expect(error.message).toEqual(message); 140 | expect(error.code).toEqual('INVALID_OPTIONS'); 141 | expect(error.errors).toBeDefined(); 142 | expect(error.errors[0]).toEqual(errors[0].message); 143 | } 144 | }); 145 | 146 | it('always has an error code property on error object', async () => { 147 | const message = 'An error has occurred.'; 148 | // reject next fetch 149 | fetchMock.mockRejectOnce(new Error(message)); 150 | try { 151 | // initialize payment 152 | await FlutterwaveInit(INIT_OPTIONS); 153 | } catch (error) { 154 | // run assertions 155 | expect(error.code).toBeDefined(); 156 | } 157 | }); 158 | 159 | it('catches missing response data error', async () => { 160 | const message = 'Hello, World!'; 161 | // mock next fetch 162 | fetchMock.mockOnce(JSON.stringify({status: 'success', message})); 163 | try { 164 | // initialize payment 165 | await FlutterwaveInit(INIT_OPTIONS); 166 | } catch (error) { 167 | // run assertions 168 | expect(error.code).toEqual('MALFORMED_RESPONSE'); 169 | } 170 | }); 171 | 172 | it('is abortable', async () => { 173 | // use fake jest timers 174 | jest.useFakeTimers(); 175 | // mock fetch response 176 | fetchMock.mockResponse(async () => { 177 | jest.advanceTimersByTime(60) 178 | return JSON.stringify({ 179 | status: 'error', 180 | message: 'Error!', 181 | }) 182 | }); 183 | // create abort controller 184 | const abortController = new AbortController; 185 | // abort next fetch 186 | setTimeout(() => abortController.abort(), 50); 187 | try { 188 | // initialize payment 189 | await FlutterwaveInit( 190 | INIT_OPTIONS, 191 | abortController 192 | ) 193 | } catch(error) { 194 | // run assertions 195 | expect(error).toBeInstanceOf(FlutterwaveInitError); 196 | expect(error.code).toEqual('ABORTERROR'); 197 | } 198 | }); 199 | }); 200 | -------------------------------------------------------------------------------- /__tests__/FlutterwaveInitError.spec.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInitError from '../src/utils/FlutterwaveInitError'; 2 | 3 | describe('', () => { 4 | it('initializes with the the message and code passed', () => { 5 | const message = 'Hello, World!'; 6 | const code = 'TEST'; 7 | const error = new FlutterwaveInitError({message, code}); 8 | expect(error.message).toEqual(message); 9 | expect(error.code).toEqual(code); 10 | }); 11 | 12 | it('has errors if specified', () => { 13 | const message = 'Hello, World!'; 14 | const code = 'TEST'; 15 | const errors = ['Error 1', 'Error 2']; 16 | const error = new FlutterwaveInitError({message, code, errors}); 17 | expect(Array.isArray(error.errors)).toBeTruthy(); 18 | }); 19 | 20 | it('has an error ID if specified', () => { 21 | const message = 'Hello, World!'; 22 | const code = 'TEST'; 23 | const errorId = 'N/F39040830498039434'; 24 | const error = new FlutterwaveInitError({message, code, errorId}); 25 | expect(typeof error.errorId === 'string').toBeTruthy(); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /__tests__/FlutterwaveInitV2.spec.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInitV2, {FlutterwaveInitV2Options} from '../src/FlutterwaveInitV2'; 2 | import {STANDARD_URL_V2} from '../src/configs'; 3 | import FlutterwaveInitError from '../src/utils/FlutterwaveInitError'; 4 | 5 | const AUTHORIZATION = '[PUB Key]'; 6 | 7 | // fetch header 8 | const FETCH_HEADER = new Headers(); 9 | FETCH_HEADER.append('Content-Type', 'application/json'); 10 | 11 | // fetch body 12 | const FETCH_BODY: FlutterwaveInitV2Options = { 13 | redirect_url: 'http://flutterwave.com', 14 | PBFPubKey: AUTHORIZATION, 15 | amount: 50, 16 | currency: 'NGN', 17 | customer_email: 'email@example.com', 18 | txref: Date.now() + '-txref', 19 | } 20 | 21 | // payment options 22 | const INIT_OPTIONS: FlutterwaveInitV2Options = { 23 | ...FETCH_BODY, 24 | }; 25 | 26 | const SUCCESS_RESPONSE = { 27 | status: 'success', 28 | message: 'Payment link generated.', 29 | data: { 30 | link: 'http://payment-link.com/checkout', 31 | }, 32 | }; 33 | 34 | describe('', () => { 35 | it('returns a payment link after initialization', async () => { 36 | // mock next fetch request 37 | fetchMock.mockOnce(JSON.stringify(SUCCESS_RESPONSE)); 38 | // flutterwave init test 39 | const link = await FlutterwaveInitV2(INIT_OPTIONS); 40 | // expect fetch to have been called once 41 | expect(global.fetch).toHaveBeenCalledTimes(1); 42 | // expect fetch to have been called to the standard init url 43 | expect(global.fetch).toHaveBeenCalledWith(STANDARD_URL_V2, { 44 | body: JSON.stringify(FETCH_BODY), 45 | headers: FETCH_HEADER, 46 | method: 'POST', 47 | }); 48 | expect(typeof link === 'string').toBeTruthy(); 49 | }); 50 | 51 | it('includes error code and message of init error', async () => { 52 | const message = 'An error has occurred.'; 53 | // mock next request 54 | fetchMock.mockOnce(JSON.stringify({ 55 | status: 'error', 56 | message: message, 57 | })); 58 | try { 59 | // initialize payment 60 | await FlutterwaveInitV2(INIT_OPTIONS); 61 | } catch (error) { 62 | // run assertions 63 | expect(error.message).toEqual(message); 64 | expect(error.code).toEqual('STANDARD_INIT_ERROR'); 65 | } 66 | }); 67 | 68 | it('sets error code to MALFORMED_RESPONSE if not defined in response', async () => { 69 | const message = 'An error has occurred.'; 70 | // reject next fetch 71 | fetchMock.mockOnce(JSON.stringify({ 72 | status: 'error', 73 | data: {}, 74 | })); 75 | try { 76 | // initialize payment 77 | await FlutterwaveInitV2(INIT_OPTIONS); 78 | } catch (error) { 79 | // run assertions 80 | expect(error.code).toEqual('MALFORMED_RESPONSE'); 81 | } 82 | }); 83 | 84 | it('sets error message to default message if not defined in response', async () => { 85 | const message = 'An error has occurred.'; 86 | // reject next fetch 87 | fetchMock.mockOnce(JSON.stringify({ 88 | status: 'error', 89 | data: {}, 90 | })); 91 | try { 92 | // initialize payment 93 | await FlutterwaveInitV2(INIT_OPTIONS); 94 | } catch (error) { 95 | // run assertions 96 | expect(error.message).toEqual('An unknown error occured!'); 97 | } 98 | }); 99 | 100 | it('handles missing data error', async () => { 101 | // mock next fetch 102 | fetchMock.mockOnce(JSON.stringify({status: 'error'})); 103 | try { 104 | // initialize payment 105 | const response = await FlutterwaveInitV2(INIT_OPTIONS); 106 | } catch (error) { 107 | // run assertions 108 | expect(error.code).toEqual('STANDARD_INIT_ERROR'); 109 | } 110 | }); 111 | 112 | it('rejects with an error if link is missing in data', async () => { 113 | const errorMessage = 'Missing link test.'; 114 | // mock next fetch 115 | fetchMock.mockOnce( 116 | JSON.stringify({ 117 | status: 'error', 118 | data: { 119 | message: errorMessage, 120 | code: 'MALFORMED_RESPONSE' 121 | } 122 | } 123 | ) 124 | ); 125 | try { 126 | // initialize payment 127 | const response = await FlutterwaveInitV2(INIT_OPTIONS); 128 | } catch (error) { 129 | // run assertions 130 | expect(error.code).toEqual('MALFORMED_RESPONSE'); 131 | } 132 | }); 133 | 134 | 135 | it('is abortable', async () => { 136 | // use fake jest timers 137 | jest.useFakeTimers(); 138 | // mock fetch response 139 | fetchMock.mockResponse(async () => { 140 | jest.advanceTimersByTime(60) 141 | return JSON.stringify({ 142 | status: 'error', 143 | message: 'Error!', 144 | }) 145 | }); 146 | // create abort controller 147 | const abortController = new AbortController; 148 | // abort next fetch 149 | setTimeout(() => abortController.abort(), 50); 150 | try { 151 | // initialize payment 152 | await FlutterwaveInitV2( 153 | INIT_OPTIONS, 154 | abortController 155 | ) 156 | } catch(error) { 157 | // run assertions 158 | expect(error).toBeInstanceOf(FlutterwaveInitError); 159 | expect(error.code).toEqual('ABORTERROR'); 160 | } 161 | }); 162 | }); 163 | -------------------------------------------------------------------------------- /__tests__/PayWithFlutterwave.spec.tsx: -------------------------------------------------------------------------------- 1 | import 'react-native'; 2 | import React from 'react'; 3 | import renderer from 'react-test-renderer'; 4 | import PayWithFlutterwave from '../src/PayWithFlutterwave'; 5 | import {FlutterwaveInitOptions} from '../src/FlutterwaveInit'; 6 | import {TouchableOpacity, Text} from 'react-native'; 7 | const CustomBtnTestID = 'flw-custom-button'; 8 | 9 | const CustomButton = ({onPress, disabled}) => ( 10 | 14 | {disabled ? 'Please wait...' : 'Pay'} 15 | 16 | ) 17 | 18 | const PAYMENT_INFO: Omit = { 19 | tx_ref: '34h093h09h034034', 20 | customer: { 21 | email: 'customer-email@example.com', 22 | }, 23 | authorization: '[Authorization]', 24 | amount: 50, 25 | currency: 'NGN', 26 | }; 27 | 28 | describe('PayWithFlutterwaveV3', () => { 29 | 30 | it('renders a default pay with flutterwave button', () => { 31 | // create component tree 32 | const Tree = renderer.create( 33 | {}} 35 | options={PAYMENT_INFO} 36 | /> 37 | ); 38 | // run assertions 39 | expect(Tree.toJSON()).toMatchSnapshot(); 40 | }); 41 | 42 | it('uses custom button in place of flw button if defined', () => { 43 | const Tree = renderer.create( 44 | {}} 46 | options={PAYMENT_INFO} 47 | customButton={CustomButton} 48 | /> 49 | ); 50 | // run assertions 51 | expect(Tree.toJSON()).toMatchSnapshot(); 52 | }) 53 | }); 54 | -------------------------------------------------------------------------------- /__tests__/PayWithFlutterwaveV2.spec.tsx: -------------------------------------------------------------------------------- 1 | import 'react-native'; 2 | import React from 'react'; 3 | import renderer from 'react-test-renderer'; 4 | import PayWithFlutterwaveV2 from '../src/PayWithFlutterwaveV2'; 5 | import {FlutterwaveInitV2Options} from '../src/FlutterwaveInitV2'; 6 | import {TouchableOpacity, Text} from 'react-native'; 7 | const CustomBtnTestID = 'flw-custom-button'; 8 | 9 | const CustomButton = ({onPress, disabled}) => ( 10 | 14 | {disabled ? 'Please wait...' : 'Pay'} 15 | 16 | ) 17 | 18 | const PAYMENT_INFO: Omit = { 19 | txref: '34h093h09h034034', 20 | customer_email: 'customer-email@example.com', 21 | PBFPubKey: '[Public Key]', 22 | amount: 50, 23 | currency: 'NGN', 24 | }; 25 | 26 | describe('PayWithFlutterwaveV3', () => { 27 | 28 | it('renders a default pay with flutterwave button', () => { 29 | // create component tree 30 | const Tree = renderer.create( 31 | {}} 33 | options={PAYMENT_INFO} 34 | /> 35 | ); 36 | // run assertions 37 | expect(Tree.toJSON()).toMatchSnapshot(); 38 | }); 39 | 40 | it('uses custom button in place of flw button if defined', () => { 41 | const Tree = renderer.create( 42 | {}} 44 | options={PAYMENT_INFO} 45 | customButton={CustomButton} 46 | /> 47 | ); 48 | // run assertions 49 | expect(Tree.toJSON()).toMatchSnapshot(); 50 | }) 51 | }); 52 | -------------------------------------------------------------------------------- /__tests__/ResponseParser.spec.ts: -------------------------------------------------------------------------------- 1 | import ResponseParser from '../src/utils/ResponseParser'; 2 | import FlutterwaveInitError from '../src/utils/FlutterwaveInitError'; 3 | 4 | describe('', () => { 5 | it('expect error to be instance of FlutterwaveInitError', async () => { 6 | try { 7 | // parse response 8 | await ResponseParser({ 9 | message: 'Error occurred!' 10 | }); 11 | } catch (error) { 12 | // run assertions 13 | expect(error).toBeInstanceOf(FlutterwaveInitError); 14 | } 15 | }); 16 | 17 | it('returns missing auth error', async () => { 18 | try { 19 | // parse response 20 | await ResponseParser({ 21 | message: 'Authorization is required' 22 | }); 23 | } catch (error) { 24 | // run assertions 25 | expect(error).toBeInstanceOf(FlutterwaveInitError); 26 | expect(error.code).toEqual('AUTH_MISSING'); 27 | } 28 | }); 29 | 30 | it('returns invalid auth error', async () => { 31 | try { 32 | // parse response 33 | await ResponseParser({ 34 | message: 'Authorization is invalid' 35 | }); 36 | } catch (error) { 37 | // run assertions 38 | expect(error).toBeInstanceOf(FlutterwaveInitError); 39 | expect(error.code).toEqual('AUTH_INVALID'); 40 | } 41 | }); 42 | 43 | it('return object with errors property', async () => { 44 | const errors = [{field: 'tx_ref', message: 'An error has occured'}]; 45 | try { 46 | // parse response 47 | await ResponseParser({ 48 | message: 'Missing fields error.', 49 | errors 50 | }); 51 | } catch (error) { 52 | // run assertions 53 | expect(error).toBeInstanceOf(FlutterwaveInitError); 54 | expect(error.code).toEqual('INVALID_OPTIONS'); 55 | expect(Array.isArray(error.errors)).toBeTruthy(); 56 | expect(error.errors[0]).toEqual(errors[0].message); 57 | } 58 | }); 59 | 60 | it('returns standard init error code as default code if none is specified', async () => { 61 | try { 62 | // parse response 63 | ResponseParser({ 64 | message: 'A server error occurred.' 65 | }); 66 | } catch (error) { 67 | // run assertions 68 | expect(error).toBeInstanceOf(FlutterwaveInitError); 69 | expect(error.code).toEqual('STANDARD_INIT_ERROR'); 70 | } 71 | }); 72 | 73 | it('returns malformed response if status is success and data or link is missing', async () => { 74 | try { 75 | // parse response 76 | await ResponseParser({ 77 | message: 'Great, it worked!!!', 78 | status: 'success' 79 | }); 80 | } catch (error) { 81 | // run assertions 82 | expect(error).toBeInstanceOf(FlutterwaveInitError); 83 | expect(error.code).toEqual('MALFORMED_RESPONSE'); 84 | } 85 | }); 86 | 87 | it('returns a payment link', async () => { 88 | try { 89 | const link = 'http://checkout.flutterwave.com/380340934u093u403' 90 | // parse response 91 | const data = await ResponseParser({ 92 | message: 'Hosted link.', 93 | status: 'success', 94 | data: {link} 95 | }); 96 | // run assertions 97 | expect(data).toEqual(link); 98 | } catch (err) { 99 | // no need to run this 100 | } 101 | }); 102 | }); 103 | -------------------------------------------------------------------------------- /__tests__/__snapshots__/FlutterwaveButton.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` applies left aligned style if alignLeft prop is present 1`] = ` 4 | 38 | 55 | 56 | `; 57 | 58 | exports[` renders pay with flutterwave by default 1`] = ` 59 | 91 | 108 | 109 | `; 110 | 111 | exports[` renders with overlay and inactive style of button is disabled 1`] = ` 112 | 146 | 163 | 175 | 176 | `; 177 | 178 | exports[` replaces pay with flutterwave image with children 1`] = ` 179 | 211 | 212 | Hello, World! 213 | 214 | 215 | `; 216 | -------------------------------------------------------------------------------- /__tests__/__snapshots__/FlutterwaveCheckout.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` renders with modal closed if visible prop is not true 1`] = ` 4 | 10 | 32 | 48 | 59 | 98 | 113 | 128 | 129 | 130 | 131 | 132 | `; 133 | 134 | exports[` renders with modal open if visible props is true 1`] = ` 135 | 141 | 163 | 179 | 190 | 229 | 244 | 259 | 260 | 261 | 262 | 263 | `; 264 | -------------------------------------------------------------------------------- /__tests__/__snapshots__/PayWithFlutterwave.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`PayWithFlutterwaveV3 renders a default pay with flutterwave button 1`] = ` 4 | Array [ 5 | 37 | 54 | , 55 | 61 | 83 | 99 | 110 | 149 | 164 | 179 | 180 | 181 | 182 | , 183 | ] 184 | `; 185 | 186 | exports[`PayWithFlutterwaveV3 uses custom button in place of flw button if defined 1`] = ` 187 | Array [ 188 | 205 | 206 | Pay 207 | 208 | , 209 | 215 | 237 | 253 | 264 | 303 | 318 | 333 | 334 | 335 | 336 | , 337 | ] 338 | `; 339 | -------------------------------------------------------------------------------- /__tests__/__snapshots__/PayWithFlutterwaveBase.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`PayWithFlutterwaveBase renders a default pay with flutterwave button 1`] = ` 4 | Array [ 5 | 37 | 54 | , 55 | 61 | 83 | 99 | 110 | 149 | 164 | 179 | 180 | 181 | 182 | , 183 | ] 184 | `; 185 | 186 | exports[`PayWithFlutterwaveBase uses custom button in place of flw button if defined 1`] = ` 187 | Array [ 188 | 205 | 206 | Pay 207 | 208 | , 209 | 215 | 237 | 253 | 264 | 303 | 318 | 333 | 334 | 335 | 336 | , 337 | ] 338 | `; 339 | -------------------------------------------------------------------------------- /__tests__/__snapshots__/PayWithFlutterwaveV2.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`PayWithFlutterwaveV3 renders a default pay with flutterwave button 1`] = ` 4 | Array [ 5 | 37 | 54 | , 55 | 61 | 83 | 99 | 110 | 149 | 164 | 179 | 180 | 181 | 182 | , 183 | ] 184 | `; 185 | 186 | exports[`PayWithFlutterwaveV3 uses custom button in place of flw button if defined 1`] = ` 187 | Array [ 188 | 205 | 206 | Pay 207 | 208 | , 209 | 215 | 237 | 253 | 264 | 303 | 318 | 333 | 334 | 335 | 336 | , 337 | ] 338 | `; 339 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = function (api) { 2 | api && api.cache(false); 3 | return { 4 | env: { 5 | test: { 6 | presets: ['module:metro-react-native-babel-preset'], 7 | }, 8 | }, 9 | presets: ['module:metro-react-native-babel-preset'], 10 | }; 11 | }; 12 | -------------------------------------------------------------------------------- /dist/FlutterwaveButton.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { StyleProp, ViewStyle } from 'react-native'; 3 | interface FlutterwaveButtonProps { 4 | style?: StyleProp; 5 | disabled?: boolean; 6 | alignLeft?: boolean; 7 | onPress?: () => void; 8 | } 9 | declare const FlutterwaveButton: React.FC; 10 | export default FlutterwaveButton; 11 | //# sourceMappingURL=FlutterwaveButton.d.ts.map -------------------------------------------------------------------------------- /dist/FlutterwaveButton.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"FlutterwaveButton.d.ts","sourceRoot":"","sources":["../src/FlutterwaveButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAGL,SAAS,EACT,SAAS,EAGV,MAAM,cAAc,CAAC;AAKtB,UAAU,sBAAsB;IAC9B,KAAK,CAAC,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB;AAED,QAAA,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAC/B,sBAAsB,CAsCvB,CAAA;AAuCD,eAAe,iBAAiB,CAAC"} -------------------------------------------------------------------------------- /dist/FlutterwaveButton.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { StyleSheet, Image, TouchableHighlight, View, } from 'react-native'; 3 | import { colors } from './configs'; 4 | var pryContent = require('./assets/pry-button-content.png'); 5 | var contentSizeDimension = 8.2962962963; 6 | var FlutterwaveButton = function FlutterwaveButton(_a) { 7 | var style = _a.style, alignLeft = _a.alignLeft, children = _a.children, disabled = _a.disabled, onPress = _a.onPress; 8 | // render primary button 9 | return ( 15 | <> 16 | {children ? children : ()} 17 | {disabled 18 | ? () 19 | : null} 20 | 21 | ); 22 | }; 23 | // component UI styles 24 | var styles = StyleSheet.create({ 25 | buttonBusyOvelay: { 26 | position: 'absolute', 27 | left: 0, 28 | top: 0, 29 | bottom: 0, 30 | right: 0, 31 | backgroundColor: 'rgba(255, 255, 255, 0.6)' 32 | }, 33 | buttonBusy: { 34 | borderColor: colors.primaryLight 35 | }, 36 | buttonAlignLeft: { 37 | justifyContent: 'flex-start' 38 | }, 39 | button: { 40 | paddingHorizontal: 16, 41 | minWidth: 100, 42 | height: 52, 43 | borderColor: colors.primary, 44 | borderWidth: 1, 45 | borderRadius: 6, 46 | backgroundColor: colors.primary, 47 | alignItems: 'center', 48 | justifyContent: 'center', 49 | flexDirection: 'row', 50 | overflow: 'hidden' 51 | }, 52 | buttonContent: { 53 | resizeMode: 'contain', 54 | width: 187.3, 55 | height: 187.3 / contentSizeDimension 56 | } 57 | }); 58 | // export component as default 59 | export default FlutterwaveButton; 60 | -------------------------------------------------------------------------------- /dist/FlutterwaveCheckout.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | export interface FlutterwaveCheckoutProps { 3 | onRedirect?: (data: any) => void; 4 | onAbort?: () => void; 5 | link?: string; 6 | visible?: boolean; 7 | } 8 | interface FlutterwaveCheckoutErrorProps { 9 | hasLink: boolean; 10 | onTryAgain: () => void; 11 | } 12 | declare const FlutterwaveCheckout: React.FC; 13 | export declare const FlutterwaveCheckoutError: React.FC; 14 | export default FlutterwaveCheckout; 15 | //# sourceMappingURL=FlutterwaveCheckout.d.ts.map -------------------------------------------------------------------------------- /dist/FlutterwaveCheckout.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"FlutterwaveCheckout.d.ts","sourceRoot":"","sources":["../src/FlutterwaveCheckout.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAsB1B,MAAM,WAAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAOD,UAAU,6BAA6B;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,MAAM,IAAI,CAAC;CACxB;AAoBD,QAAA,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,wBAAwB,CA0H3D,CAAA;AAoBD,eAAO,MAAM,wBAAwB,EAAE,KAAK,CAAC,EAAE,CAAC,6BAA6B,CAsB5E,CAAA;AA8ED,eAAe,mBAAmB,CAAC"} -------------------------------------------------------------------------------- /dist/FlutterwaveCheckout.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { StyleSheet, Modal, View, Animated, TouchableWithoutFeedback, Text, Alert, Image, Dimensions, Easing, TouchableOpacity, Platform, } from 'react-native'; 3 | import WebView from 'react-native-webview'; 4 | import { colors } from './configs'; 5 | var loader = require('./assets/loader.gif'); 6 | var borderRadiusDimension = 24 / 896; 7 | var windowHeight = Dimensions.get('window').height; 8 | var getRedirectParams = function (url) { 9 | // initialize result container 10 | var res = {}; 11 | // if url has params 12 | if (url.split('?').length > 1) { 13 | // get query params in an array 14 | var params = url.split('?')[1].split('&'); 15 | // add url params to result 16 | for (var i = 0; i < params.length; i++) { 17 | var param = params[i].split('='); 18 | var val = decodeURIComponent(param[1]).trim(); 19 | res[param[0]] = String(val); 20 | } 21 | } 22 | // return result 23 | return res; 24 | }; 25 | var FlutterwaveCheckout = function FlutterwaveCheckout(props) { 26 | var link = props.link, visible = props.visible, onRedirect = props.onRedirect, onAbort = props.onAbort; 27 | var _a = React.useState(false), show = _a[0], setShow = _a[1]; 28 | var webviewRef = React.useRef(null); 29 | var animation = React.useRef(new Animated.Value(0)); 30 | var animateIn = React.useCallback(function () { 31 | setShow(true); 32 | Animated.timing(animation.current, { 33 | toValue: 1, 34 | duration: 700, 35 | easing: Easing["in"](Easing.elastic(0.72)), 36 | useNativeDriver: false 37 | }).start(); 38 | }, []); 39 | var animateOut = React.useCallback(function () { 40 | return new Promise(function (resolve) { 41 | Animated.timing(animation.current, { 42 | toValue: 0, 43 | duration: 400, 44 | useNativeDriver: false 45 | }).start(function () { 46 | setShow(false); 47 | resolve(); 48 | }); 49 | }); 50 | }, []); 51 | var handleReload = React.useCallback(function () { 52 | if (webviewRef.current) { 53 | webviewRef.current.reload(); 54 | } 55 | }, []); 56 | var handleAbort = React.useCallback(function (confirmed) { 57 | if (confirmed === void 0) { confirmed = false; } 58 | if (!confirmed) { 59 | Alert.alert('', 'Are you sure you want to cancel this payment?', [ 60 | { text: 'No' }, 61 | { 62 | text: 'Yes, Cancel', 63 | style: 'destructive', 64 | onPress: function () { return handleAbort(true); } 65 | }, 66 | ]); 67 | return; 68 | } 69 | // remove tx_ref and dismiss 70 | animateOut().then(onAbort); 71 | }, [onAbort, animateOut]); 72 | var handleNavigationStateChange = React.useCallback(function (ev) { 73 | // cregex to check if redirect has occured on completion/cancel 74 | var rx = /\/flutterwave\.com\/rn-redirect/; 75 | // Don't end payment if not redirected back 76 | if (!rx.test(ev.url)) { 77 | return true; 78 | } 79 | // dismiss modal 80 | animateOut().then(function () { 81 | if (onRedirect) { 82 | onRedirect(getRedirectParams(ev.url)); 83 | } 84 | }); 85 | return false; 86 | }, [onRedirect]); 87 | var doAnimate = React.useCallback(function () { 88 | if (visible === show) { 89 | return; 90 | } 91 | if (visible) { 92 | return animateIn(); 93 | } 94 | animateOut().then(function () { }); 95 | }, [visible, show, animateOut, animateIn]); 96 | React.useEffect(function () { 97 | doAnimate(); 98 | return function () { }; 99 | }, [doAnimate]); 100 | var marginTop = animation.current.interpolate({ 101 | inputRange: [0, 1], 102 | outputRange: [windowHeight, 0] 103 | }); 104 | var opacity = animation.current.interpolate({ 105 | inputRange: [0, 0.3, 1], 106 | outputRange: [0, 1, 1] 107 | }); 108 | return ( 109 | 110 | 117 | ; }} renderLoading={function () { return ; }}/> 118 | 119 | ); 120 | }; 121 | var FlutterwaveCheckoutBackdrop = function FlutterwaveCheckoutBackdrop(_a) { 122 | var animation = _a.animation, onPress = _a.onPress; 123 | // Interpolation backdrop animation 124 | var backgroundColor = animation.interpolate({ 125 | inputRange: [0, 0.3, 1], 126 | outputRange: [colors.transparent, colors.transparent, 'rgba(0,0,0,0.5)'] 127 | }); 128 | return ( 129 | 130 | ); 131 | }; 132 | export var FlutterwaveCheckoutError = function (_a) { 133 | var hasLink = _a.hasLink, onTryAgain = _a.onTryAgain; 134 | return ( 135 | {hasLink ? (<> 136 | 137 | An error occurred, please tab below to try again. 138 | 139 | 140 | Try Again 141 | 142 | ) : ( 143 | An error occurred, please close the checkout dialog and try again. 144 | )} 145 | ); 146 | }; 147 | var FlutterwaveCheckoutLoader = function () { 148 | return ( 149 | 150 | ); 151 | }; 152 | var styles = StyleSheet.create({ 153 | errorActionButtonText: { 154 | textAlign: 'center', 155 | color: colors.primary, 156 | fontSize: 16 157 | }, 158 | errorActionButton: { 159 | paddingHorizontal: 16, 160 | paddingVertical: 16 161 | }, 162 | errorText: { 163 | color: colors.secondary, 164 | textAlign: 'center', 165 | marginBottom: 32, 166 | fontSize: 18 167 | }, 168 | error: { 169 | position: 'absolute', 170 | left: 0, 171 | right: 0, 172 | bottom: 0, 173 | top: 0, 174 | backgroundColor: '#ffffff', 175 | justifyContent: 'center', 176 | alignItems: 'center', 177 | paddingHorizontal: 56 178 | }, 179 | backdrop: { 180 | position: 'absolute', 181 | left: 0, 182 | right: 0, 183 | bottom: 0, 184 | top: 0 185 | }, 186 | loadingImage: { 187 | width: 64, 188 | height: 64, 189 | resizeMode: 'contain' 190 | }, 191 | loading: { 192 | position: 'absolute', 193 | top: 0, 194 | right: 0, 195 | bottom: 0, 196 | left: 0, 197 | backgroundColor: 'rgba(255, 255, 255, 0.3)', 198 | justifyContent: 'center', 199 | alignItems: 'center' 200 | }, 201 | webviewContainer: { 202 | top: Platform.select({ ios: 96, android: 64 }), 203 | flex: 1, 204 | backgroundColor: '#efefef', 205 | paddingBottom: Platform.select({ ios: 96, android: 64 }), 206 | overflow: 'hidden', 207 | borderTopLeftRadius: windowHeight * borderRadiusDimension, 208 | borderTopRightRadius: windowHeight * borderRadiusDimension 209 | }, 210 | webview: { 211 | flex: 1, 212 | backgroundColor: 'rgba(0,0,0,0)' 213 | } 214 | }); 215 | export default FlutterwaveCheckout; 216 | -------------------------------------------------------------------------------- /dist/FlutterwaveInit.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | export declare type Currency = 'AUD' | 'BIF' | 'CDF' | 'CAD' | 'CVE' | 'EUR' | 'GBP' | 'GHS' | 'GMD' | 'GNF' | 'KES' | 'LRD' | 'MWK' | 'MZN' | 'NGN' | 'RWF' | 'SLL' | 'STD' | 'TZS' | 'UGX' | 'USD' | 'XAF' | 'XOF' | 'ZAR' | 'ZMK' | 'ZMW' | 'ZWD'; 3 | export interface FlutterwaveInitSubAccount { 4 | id: string; 5 | transaction_split_ratio?: number; 6 | transaction_charge_type?: string; 7 | transaction_charge?: number; 8 | } 9 | export interface FlutterwaveInitOptionsBase { 10 | amount: number; 11 | currency?: Currency; 12 | integrity_hash?: string; 13 | payment_options?: string; 14 | payment_plan?: number; 15 | redirect_url: string; 16 | subaccounts?: Array; 17 | } 18 | interface FlutterwavePaymentMeta { 19 | [k: string]: any; 20 | } 21 | export interface FlutterwaveInitCustomer { 22 | email: string; 23 | phonenumber?: string; 24 | name?: string; 25 | } 26 | export interface FlutterwaveInitCustomizations { 27 | title?: string; 28 | logo?: string; 29 | description?: string; 30 | } 31 | export declare type FlutterwaveInitOptions = FlutterwaveInitOptionsBase & { 32 | authorization: string; 33 | tx_ref: string; 34 | customer: FlutterwaveInitCustomer; 35 | meta?: FlutterwavePaymentMeta | null; 36 | customizations?: FlutterwaveInitCustomizations; 37 | }; 38 | export interface FieldError { 39 | field: string; 40 | message: string; 41 | } 42 | export interface ResponseData { 43 | status?: 'success' | 'error'; 44 | message: string; 45 | error_id?: string; 46 | errors?: Array; 47 | code?: string; 48 | data?: { 49 | link: string; 50 | }; 51 | } 52 | /** 53 | * This function is responsible for making the request to 54 | * initialize a Flutterwave payment. 55 | * @param options FlutterwaveInitOptions 56 | * @param abortController AbortController 57 | * @return Promise 58 | */ 59 | export default function FlutterwaveInit(options: FlutterwaveInitOptions, abortController?: AbortController): Promise; 60 | export {}; 61 | //# sourceMappingURL=FlutterwaveInit.d.ts.map -------------------------------------------------------------------------------- /dist/FlutterwaveInit.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"FlutterwaveInit.d.ts","sourceRoot":"","sources":["../src/FlutterwaveInit.ts"],"names":[],"mappings":";AAIA,oBAAY,QAAQ,GAClB,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,CAAC;AAER,MAAM,WAAW,yBAAyB;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,KAAK,CAAC,yBAAyB,CAAC,CAAC;CAChD;AAED,UAAU,sBAAsB;IAC9B,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAClB;AAED,MAAM,WAAW,uBAAuB;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,6BAA6B;IAC5C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,oBAAY,sBAAsB,GAAG,0BAA0B,GAAG;IAChE,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,uBAAuB,CAAC;IAClC,IAAI,CAAC,EAAE,sBAAsB,GAAG,IAAI,CAAC;IACrC,cAAc,CAAC,EAAE,6BAA6B,CAAC;CAChD,CAAC;AAEF,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,SAAS,GAAG,OAAO,CAAC;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE;QACL,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;CACH;AASD;;;;;;GAMG;AACH,wBAA8B,eAAe,CAC3C,OAAO,EAAE,sBAAsB,EAC/B,eAAe,CAAC,EAAE,eAAe,GAChC,OAAO,CAAC,MAAM,CAAC,CAgCjB"} -------------------------------------------------------------------------------- /dist/FlutterwaveInit.js: -------------------------------------------------------------------------------- 1 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 2 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 3 | return new (P || (P = Promise))(function (resolve, reject) { 4 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 5 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 6 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 7 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 8 | }); 9 | }; 10 | var __generator = (this && this.__generator) || function (thisArg, body) { 11 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; 12 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; 13 | function verb(n) { return function (v) { return step([n, v]); }; } 14 | function step(op) { 15 | if (f) throw new TypeError("Generator is already executing."); 16 | while (_) try { 17 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; 18 | if (y = 0, t) op = [op[0] & 2, t.value]; 19 | switch (op[0]) { 20 | case 0: case 1: t = op; break; 21 | case 4: _.label++; return { value: op[1], done: false }; 22 | case 5: _.label++; y = op[1]; op = [0]; continue; 23 | case 7: op = _.ops.pop(); _.trys.pop(); continue; 24 | default: 25 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } 26 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } 27 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } 28 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } 29 | if (t[2]) _.ops.pop(); 30 | _.trys.pop(); continue; 31 | } 32 | op = body.call(thisArg, _); 33 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } 34 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; 35 | } 36 | }; 37 | var __rest = (this && this.__rest) || function (s, e) { 38 | var t = {}; 39 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) 40 | t[p] = s[p]; 41 | if (s != null && typeof Object.getOwnPropertySymbols === "function") 42 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { 43 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) 44 | t[p[i]] = s[p[i]]; 45 | } 46 | return t; 47 | }; 48 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 49 | import ResponseParser from './utils/ResponseParser'; 50 | import { STANDARD_URL } from './configs'; 51 | /** 52 | * This function is responsible for making the request to 53 | * initialize a Flutterwave payment. 54 | * @param options FlutterwaveInitOptions 55 | * @param abortController AbortController 56 | * @return Promise 57 | */ 58 | export default function FlutterwaveInit(options, abortController) { 59 | return __awaiter(this, void 0, void 0, function () { 60 | var authorization, body, headers, fetchOptions, response, responseData, _a, _b, e_1, error; 61 | return __generator(this, function (_c) { 62 | switch (_c.label) { 63 | case 0: 64 | _c.trys.push([0, 4, , 5]); 65 | authorization = options.authorization, body = __rest(options, ["authorization"]); 66 | headers = new Headers; 67 | headers.append('Content-Type', 'application/json'); 68 | headers.append('Authorization', "Bearer " + authorization); 69 | fetchOptions = { 70 | method: 'POST', 71 | body: JSON.stringify(body), 72 | headers: headers 73 | }; 74 | // add abortController if defined 75 | if (abortController) { 76 | fetchOptions.signal = abortController.signal; 77 | } 78 | ; 79 | return [4 /*yield*/, fetch(STANDARD_URL, fetchOptions)]; 80 | case 1: 81 | response = _c.sent(); 82 | return [4 /*yield*/, response.json()]; 83 | case 2: 84 | responseData = _c.sent(); 85 | _b = (_a = Promise).resolve; 86 | return [4 /*yield*/, ResponseParser(responseData)]; 87 | case 3: 88 | // resolve with the payment link 89 | return [2 /*return*/, _b.apply(_a, [_c.sent()])]; 90 | case 4: 91 | e_1 = _c.sent(); 92 | error = e_1 instanceof FlutterwaveInitError 93 | ? e_1 94 | : new FlutterwaveInitError({ message: e_1.message, code: e_1.name.toUpperCase() }); 95 | // resolve with error 96 | return [2 /*return*/, Promise.reject(error)]; 97 | case 5: return [2 /*return*/]; 98 | } 99 | }); 100 | }); 101 | } 102 | -------------------------------------------------------------------------------- /dist/FlutterwaveInitV2.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { Currency, FlutterwaveInitSubAccount } from './FlutterwaveInit'; 3 | export interface FlutterwaveInitOptionsBase { 4 | amount: number; 5 | currency?: Currency; 6 | integrity_hash?: string; 7 | payment_options?: string; 8 | payment_plan?: number; 9 | redirect_url: string; 10 | subaccounts?: Array; 11 | } 12 | export interface FieldError { 13 | field: string; 14 | message: string; 15 | } 16 | interface FlutterwavePaymentMetaV2 { 17 | metaname: string; 18 | metavalue: string; 19 | } 20 | export declare type FlutterwaveInitV2Options = FlutterwaveInitOptionsBase & { 21 | txref: string; 22 | PBFPubKey: string; 23 | customer_firstname?: string; 24 | customer_lastname?: string; 25 | customer_phone?: string; 26 | customer_email: string; 27 | country?: string; 28 | pay_button_text?: string; 29 | custom_title?: string; 30 | custom_description?: string; 31 | custom_logo?: string; 32 | meta?: Array; 33 | }; 34 | /** 35 | * This function is responsible for making the request to 36 | * initialize a Flutterwave payment. 37 | * @param options FlutterwaveInitOptions 38 | * @return Promise<{ 39 | * error: { 40 | * code: string; 41 | * message: string; 42 | * } | null; 43 | * link?: string | null; 44 | * }> 45 | */ 46 | export default function FlutterwaveInitV2(options: FlutterwaveInitV2Options, abortController?: AbortController): Promise; 47 | export {}; 48 | //# sourceMappingURL=FlutterwaveInitV2.d.ts.map -------------------------------------------------------------------------------- /dist/FlutterwaveInitV2.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"FlutterwaveInitV2.d.ts","sourceRoot":"","sources":["../src/FlutterwaveInitV2.ts"],"names":[],"mappings":";AAEA,OAAO,EAAC,QAAQ,EAAE,yBAAyB,EAAC,MAAM,mBAAmB,CAAC;AAEtE,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,KAAK,CAAC,yBAAyB,CAAC,CAAC;CAChD;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AASD,UAAU,wBAAwB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,oBAAY,wBAAwB,GAAG,0BAA0B,GAAG;IAClE,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,KAAK,CAAC,wBAAwB,CAAC,CAAC;CACxC,CAAA;AAYD;;;;;;;;;;;GAWG;AACH,wBAA8B,iBAAiB,CAC7C,OAAO,EAAE,wBAAwB,EACjC,eAAe,CAAC,EAAE,eAAe,GAChC,OAAO,CAAC,MAAM,CAAC,CA6CjB"} -------------------------------------------------------------------------------- /dist/FlutterwaveInitV2.js: -------------------------------------------------------------------------------- 1 | var __assign = (this && this.__assign) || function () { 2 | __assign = Object.assign || function(t) { 3 | for (var s, i = 1, n = arguments.length; i < n; i++) { 4 | s = arguments[i]; 5 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 6 | t[p] = s[p]; 7 | } 8 | return t; 9 | }; 10 | return __assign.apply(this, arguments); 11 | }; 12 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 13 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 14 | return new (P || (P = Promise))(function (resolve, reject) { 15 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 16 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 17 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 18 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 19 | }); 20 | }; 21 | var __generator = (this && this.__generator) || function (thisArg, body) { 22 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; 23 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; 24 | function verb(n) { return function (v) { return step([n, v]); }; } 25 | function step(op) { 26 | if (f) throw new TypeError("Generator is already executing."); 27 | while (_) try { 28 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; 29 | if (y = 0, t) op = [op[0] & 2, t.value]; 30 | switch (op[0]) { 31 | case 0: case 1: t = op; break; 32 | case 4: _.label++; return { value: op[1], done: false }; 33 | case 5: _.label++; y = op[1]; op = [0]; continue; 34 | case 7: op = _.ops.pop(); _.trys.pop(); continue; 35 | default: 36 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } 37 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } 38 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } 39 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } 40 | if (t[2]) _.ops.pop(); 41 | _.trys.pop(); continue; 42 | } 43 | op = body.call(thisArg, _); 44 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } 45 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; 46 | } 47 | }; 48 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 49 | import { STANDARD_URL_V2 } from './configs'; 50 | /** 51 | * This function is responsible for making the request to 52 | * initialize a Flutterwave payment. 53 | * @param options FlutterwaveInitOptions 54 | * @return Promise<{ 55 | * error: { 56 | * code: string; 57 | * message: string; 58 | * } | null; 59 | * link?: string | null; 60 | * }> 61 | */ 62 | export default function FlutterwaveInitV2(options, abortController) { 63 | return __awaiter(this, void 0, void 0, function () { 64 | var body, headers, fetchOptions, response, responseJSON, e_1, error; 65 | return __generator(this, function (_a) { 66 | switch (_a.label) { 67 | case 0: 68 | _a.trys.push([0, 3, , 4]); 69 | body = __assign({}, options); 70 | headers = new Headers; 71 | headers.append('Content-Type', 'application/json'); 72 | fetchOptions = { 73 | method: 'POST', 74 | body: JSON.stringify(body), 75 | headers: headers 76 | }; 77 | // add abort controller if defined 78 | if (abortController) { 79 | fetchOptions.signal = abortController.signal; 80 | } 81 | ; 82 | return [4 /*yield*/, fetch(STANDARD_URL_V2, fetchOptions)]; 83 | case 1: 84 | response = _a.sent(); 85 | return [4 /*yield*/, response.json()]; 86 | case 2: 87 | responseJSON = _a.sent(); 88 | // check if data is missing from response 89 | if (!responseJSON.data) { 90 | throw new FlutterwaveInitError({ 91 | code: 'STANDARD_INIT_ERROR', 92 | message: responseJSON.message || 'An unknown error occured!' 93 | }); 94 | } 95 | // check if the link is missing in data 96 | if (!responseJSON.data.link) { 97 | throw new FlutterwaveInitError({ 98 | code: responseJSON.data.code || 'MALFORMED_RESPONSE', 99 | message: responseJSON.data.message || 'An unknown error occured!' 100 | }); 101 | } 102 | // resolve with the payment link 103 | return [2 /*return*/, Promise.resolve(responseJSON.data.link)]; 104 | case 3: 105 | e_1 = _a.sent(); 106 | error = e_1 instanceof FlutterwaveInitError 107 | ? e_1 108 | : new FlutterwaveInitError({ message: e_1.message, code: e_1.name.toUpperCase() }); 109 | // resolve with error 110 | return [2 /*return*/, Promise.reject(error)]; 111 | case 4: return [2 /*return*/]; 112 | } 113 | }); 114 | }); 115 | } 116 | -------------------------------------------------------------------------------- /dist/PayWithFlutterwave.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { PayWithFlutterwavePropsBase } from './PaywithFlutterwaveBase'; 3 | import { FlutterwaveInitOptions } from './FlutterwaveInit'; 4 | export interface RedirectParams { 5 | status: 'successful' | 'cancelled'; 6 | transaction_id?: string; 7 | tx_ref: string; 8 | } 9 | export declare type PayWithFlutterwaveProps = PayWithFlutterwavePropsBase & { 10 | onRedirect: (data: RedirectParams) => void; 11 | options: Omit; 12 | }; 13 | declare const PayWithFlutterwave: React.FC; 14 | export default PayWithFlutterwave; 15 | //# sourceMappingURL=PayWithFlutterwave.d.ts.map -------------------------------------------------------------------------------- /dist/PayWithFlutterwave.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"PayWithFlutterwave.d.ts","sourceRoot":"","sources":["../src/PayWithFlutterwave.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EACL,2BAA2B,EAG5B,MAAM,0BAA0B,CAAC;AAClC,OAAwB,EAAC,sBAAsB,EAAC,MAAM,mBAAmB,CAAC;AAK1E,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,YAAY,GAAG,WAAW,CAAC;IACnC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AAGD,oBAAY,uBAAuB,GAAG,2BAA2B,GAAG;IAClE,UAAU,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IAC3C,OAAO,EAAE,IAAI,CAAC,sBAAsB,EAAE,cAAc,CAAC,CAAC;CACvD,CAAA;AAGD,QAAA,MAAM,kBAAkB,EAAC,KAAK,CAAC,EAAE,CAAC,uBAAuB,CASxD,CAAA;AAyBD,eAAe,kBAAkB,CAAC"} -------------------------------------------------------------------------------- /dist/PayWithFlutterwave.js: -------------------------------------------------------------------------------- 1 | var __assign = (this && this.__assign) || function () { 2 | __assign = Object.assign || function(t) { 3 | for (var s, i = 1, n = arguments.length; i < n; i++) { 4 | s = arguments[i]; 5 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 6 | t[p] = s[p]; 7 | } 8 | return t; 9 | }; 10 | return __assign.apply(this, arguments); 11 | }; 12 | var __rest = (this && this.__rest) || function (s, e) { 13 | var t = {}; 14 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) 15 | t[p] = s[p]; 16 | if (s != null && typeof Object.getOwnPropertySymbols === "function") 17 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { 18 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) 19 | t[p[i]] = s[p[i]]; 20 | } 21 | return t; 22 | }; 23 | import React from 'react'; 24 | import PropTypes from 'prop-types'; 25 | import { OptionsPropTypeBase, PayWithFlutterwavePropTypesBase } from './PaywithFlutterwaveBase'; 26 | import FlutterwaveInit from './FlutterwaveInit'; 27 | import { PAYMENT_OPTIONS } from './configs'; 28 | import { PaymentOptionsPropRule } from './utils/CustomPropTypesRules'; 29 | import PayWithFlutterwaveBase from './PaywithFlutterwaveBase'; 30 | // create V3 component 31 | var PayWithFlutterwave = function (_a) { 32 | var options = _a.options, props = __rest(_a, ["options"]); 33 | return (); 34 | }; 35 | // define component prop types 36 | PayWithFlutterwave.propTypes = __assign(__assign({}, PayWithFlutterwavePropTypesBase), { 37 | // @ts-ignore 38 | options: PropTypes.shape(__assign(__assign({}, OptionsPropTypeBase), { authorization: PropTypes.string.isRequired, tx_ref: PropTypes.string.isRequired, payment_options: PaymentOptionsPropRule(PAYMENT_OPTIONS), customer: PropTypes.shape({ 39 | name: PropTypes.string, 40 | phonenumber: PropTypes.string, 41 | email: PropTypes.string.isRequired 42 | }).isRequired, meta: PropTypes.object, customizations: PropTypes.shape({ 43 | title: PropTypes.string, 44 | logo: PropTypes.string, 45 | description: PropTypes.string 46 | }) })).isRequired }); 47 | // export component as default 48 | export default PayWithFlutterwave; 49 | -------------------------------------------------------------------------------- /dist/PayWithFlutterwaveV2.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { PayWithFlutterwavePropsBase } from './PaywithFlutterwaveBase'; 3 | import { FlutterwaveInitV2Options } from './FlutterwaveInitV2'; 4 | export interface RedirectParamsV2 { 5 | cancelled?: 'true' | 'false'; 6 | flwref?: string; 7 | txref: string; 8 | } 9 | export declare type PayWithFlutterwaveV2Props = PayWithFlutterwavePropsBase & { 10 | onRedirect: (data: RedirectParamsV2) => void; 11 | options: Omit; 12 | }; 13 | declare const PayWithFlutterwaveV2: React.FC; 14 | export default PayWithFlutterwaveV2; 15 | //# sourceMappingURL=PayWithFlutterwaveV2.d.ts.map -------------------------------------------------------------------------------- /dist/PayWithFlutterwaveV2.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"PayWithFlutterwaveV2.d.ts","sourceRoot":"","sources":["../src/PayWithFlutterwaveV2.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EACL,2BAA2B,EAG5B,MAAM,0BAA0B,CAAC;AAClC,OAA0B,EAAC,wBAAwB,EAAC,MAAM,qBAAqB,CAAC;AAKhF,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,oBAAY,yBAAyB,GAAG,2BAA2B,GAAG;IACpE,UAAU,EAAE,CAAC,IAAI,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC7C,OAAO,EAAE,IAAI,CAAC,wBAAwB,EAAE,cAAc,CAAC,CAAC;CACzD,CAAA;AAGD,QAAA,MAAM,oBAAoB,EAAC,KAAK,CAAC,EAAE,CAAC,yBAAyB,CAS5D,CAAA;AA2BD,eAAe,oBAAoB,CAAC"} -------------------------------------------------------------------------------- /dist/PayWithFlutterwaveV2.js: -------------------------------------------------------------------------------- 1 | var __assign = (this && this.__assign) || function () { 2 | __assign = Object.assign || function(t) { 3 | for (var s, i = 1, n = arguments.length; i < n; i++) { 4 | s = arguments[i]; 5 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 6 | t[p] = s[p]; 7 | } 8 | return t; 9 | }; 10 | return __assign.apply(this, arguments); 11 | }; 12 | var __rest = (this && this.__rest) || function (s, e) { 13 | var t = {}; 14 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) 15 | t[p] = s[p]; 16 | if (s != null && typeof Object.getOwnPropertySymbols === "function") 17 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { 18 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) 19 | t[p[i]] = s[p[i]]; 20 | } 21 | return t; 22 | }; 23 | import React from 'react'; 24 | import PropTypes from 'prop-types'; 25 | import { OptionsPropTypeBase, PayWithFlutterwavePropTypesBase } from './PaywithFlutterwaveBase'; 26 | import FlutterwaveInitV2 from './FlutterwaveInitV2'; 27 | import { PAYMENT_OPTIONS_V2 } from './configs'; 28 | import { PaymentOptionsPropRule } from './utils/CustomPropTypesRules'; 29 | import PayWithFlutterwaveBase from './PaywithFlutterwaveBase'; 30 | // create V2 component 31 | var PayWithFlutterwaveV2 = function (_a) { 32 | var options = _a.options, props = __rest(_a, ["options"]); 33 | return (); 34 | }; 35 | // define component prop types 36 | PayWithFlutterwaveV2.propTypes = __assign(__assign({}, PayWithFlutterwavePropTypesBase), { 37 | // @ts-ignore 38 | options: PropTypes.shape(__assign(__assign({}, OptionsPropTypeBase), { payment_options: PaymentOptionsPropRule(PAYMENT_OPTIONS_V2), txref: PropTypes.string.isRequired, PBFPubKey: PropTypes.string.isRequired, customer_firstname: PropTypes.string, customer_lastname: PropTypes.string, customer_email: PropTypes.string.isRequired, customer_phone: PropTypes.string, country: PropTypes.string, pay_button_text: PropTypes.string, custom_title: PropTypes.string, custom_description: PropTypes.string, custom_logo: PropTypes.string, meta: PropTypes.arrayOf(PropTypes.shape({ 39 | metaname: PropTypes.string, 40 | metavalue: PropTypes.string 41 | })) })).isRequired }); 42 | // export component as default 43 | export default PayWithFlutterwaveV2; 44 | -------------------------------------------------------------------------------- /dist/PaywithFlutterwaveBase.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 4 | import { StyleProp, ViewStyle } from 'react-native'; 5 | export interface CustomButtonProps { 6 | disabled: boolean; 7 | onPress: () => void; 8 | } 9 | export interface PayWithFlutterwavePropsBase { 10 | style?: StyleProp; 11 | onRedirect: (data: any) => void; 12 | onWillInitialize?: () => void; 13 | onDidInitialize?: () => void; 14 | onInitializeError?: (error: FlutterwaveInitError) => void; 15 | onAbort?: () => void; 16 | customButton?: (params: CustomButtonProps) => React.ReactNode; 17 | alignLeft?: 'alignLeft' | boolean; 18 | meta?: Array; 19 | currency?: string; 20 | } 21 | export declare const PayWithFlutterwavePropTypesBase: { 22 | alignLeft: PropTypes.Requireable; 23 | onAbort: PropTypes.Requireable<(...args: any[]) => any>; 24 | onRedirect: PropTypes.Validator<(...args: any[]) => any>; 25 | onWillInitialize: PropTypes.Requireable<(...args: any[]) => any>; 26 | onDidInitialize: PropTypes.Requireable<(...args: any[]) => any>; 27 | onInitializeError: PropTypes.Requireable<(...args: any[]) => any>; 28 | customButton: PropTypes.Requireable<(...args: any[]) => any>; 29 | }; 30 | export declare const OptionsPropTypeBase: { 31 | amount: PropTypes.Validator; 32 | currency: PropTypes.Requireable; 33 | payment_plan: PropTypes.Requireable; 34 | subaccounts: PropTypes.Requireable<(PropTypes.InferProps<{ 35 | id: PropTypes.Validator; 36 | transaction_split_ratio: PropTypes.Requireable; 37 | transaction_charge_type: PropTypes.Requireable; 38 | transaction_charge: PropTypes.Requireable; 39 | }> | null | undefined)[]>; 40 | integrity_hash: PropTypes.Requireable; 41 | }; 42 | interface PayWithFlutterwaveState { 43 | link: string | null; 44 | isPending: boolean; 45 | showDialog: boolean; 46 | reference: string | null; 47 | resetLink: boolean; 48 | } 49 | export declare type PayWithFlutterwaveBaseProps = PayWithFlutterwavePropsBase & { 50 | options: any; 51 | init: (options: any, abortController?: AbortController) => Promise; 52 | reference: string; 53 | }; 54 | declare class PayWithFlutterwaveBase

extends React.Component { 55 | state: PayWithFlutterwaveState; 56 | abortController?: AbortController; 57 | timeout: any; 58 | handleInitCall?: () => Promise; 59 | componentDidUpdate(prevProps: PayWithFlutterwaveBaseProps): void; 60 | componentWillUnmount(): void; 61 | reset: () => void; 62 | handleOptionsChanged: () => void; 63 | handleAbort: () => void; 64 | handleRedirect: (params: any) => void; 65 | handleInit: () => Promise; 66 | render(): JSX.Element; 67 | renderButton(): {} | null | undefined; 68 | } 69 | export default PayWithFlutterwaveBase; 70 | //# sourceMappingURL=PaywithFlutterwaveBase.d.ts.map -------------------------------------------------------------------------------- /dist/PaywithFlutterwaveBase.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"PaywithFlutterwaveBase.d.ts","sourceRoot":"","sources":["../src/PaywithFlutterwaveBase.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,oBAAoB,MAAM,8BAA8B,CAAC;AAIhE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEpD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,MAAM,WAAW,2BAA2B;IAC1C,KAAK,CAAC,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;IAC7B,UAAU,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,IAAI,CAAC;IAC7B,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC1D,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,KAAK,KAAK,CAAC,SAAS,CAAC;IAC9D,SAAS,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;IAClC,IAAI,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,eAAO,MAAM,+BAA+B;;;;;;;;CAQ3C,CAAC;AAEF,eAAO,MAAM,mBAAmB;;;;;;;;;;;CAuC/B,CAAC;AAEF,UAAU,uBAAuB;IAC/B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;IACpB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,oBAAY,2BAA2B,GAAG,2BAA2B,GAAG;IACtE,OAAO,EAAE,GAAG,CAAC;IACb,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,eAAe,CAAC,EAAE,eAAe,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3E,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,cAAM,sBAAsB,CAAC,CAAC,GAAG,EAAE,CAAE,SAAQ,KAAK,CAAC,SAAS,CAC1D,2BAA2B,GAAG,CAAC,EAC/B,uBAAuB,CACxB;IAEC,KAAK,EAAE,uBAAuB,CAM5B;IAEF,eAAe,CAAC,EAAE,eAAe,CAAC;IAElC,OAAO,EAAE,GAAG,CAAC;IAEb,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAEvC,kBAAkB,CAAC,SAAS,EAAE,2BAA2B;IAQzD,oBAAoB;IAMpB,KAAK,aAWH;IAEF,oBAAoB,aAYnB;IAED,WAAW,aAMV;IAED,cAAc,wBAcb;IAED,UAAU,sBA0ER;IAEF,MAAM;IAeN,YAAY;CAiBb;AAED,eAAe,sBAAsB,CAAC"} -------------------------------------------------------------------------------- /dist/PaywithFlutterwaveBase.js: -------------------------------------------------------------------------------- 1 | var __extends = (this && this.__extends) || (function () { 2 | var extendStatics = function (d, b) { 3 | extendStatics = Object.setPrototypeOf || 4 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 5 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 6 | return extendStatics(d, b); 7 | }; 8 | return function (d, b) { 9 | extendStatics(d, b); 10 | function __() { this.constructor = d; } 11 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 12 | }; 13 | })(); 14 | var __assign = (this && this.__assign) || function () { 15 | __assign = Object.assign || function(t) { 16 | for (var s, i = 1, n = arguments.length; i < n; i++) { 17 | s = arguments[i]; 18 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 19 | t[p] = s[p]; 20 | } 21 | return t; 22 | }; 23 | return __assign.apply(this, arguments); 24 | }; 25 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 26 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 27 | return new (P || (P = Promise))(function (resolve, reject) { 28 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 29 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 30 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 31 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 32 | }); 33 | }; 34 | var __generator = (this && this.__generator) || function (thisArg, body) { 35 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; 36 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; 37 | function verb(n) { return function (v) { return step([n, v]); }; } 38 | function step(op) { 39 | if (f) throw new TypeError("Generator is already executing."); 40 | while (_) try { 41 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; 42 | if (y = 0, t) op = [op[0] & 2, t.value]; 43 | switch (op[0]) { 44 | case 0: case 1: t = op; break; 45 | case 4: _.label++; return { value: op[1], done: false }; 46 | case 5: _.label++; y = op[1]; op = [0]; continue; 47 | case 7: op = _.ops.pop(); _.trys.pop(); continue; 48 | default: 49 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } 50 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } 51 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } 52 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } 53 | if (t[2]) _.ops.pop(); 54 | _.trys.pop(); continue; 55 | } 56 | op = body.call(thisArg, _); 57 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } 58 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; 59 | } 60 | }; 61 | import React from 'react'; 62 | import PropTypes from 'prop-types'; 63 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 64 | import FlutterwaveCheckout from './FlutterwaveCheckout'; 65 | import FlutterwaveButton from './FlutterwaveButton'; 66 | import { REDIRECT_URL } from './configs'; 67 | export var PayWithFlutterwavePropTypesBase = { 68 | alignLeft: PropTypes.bool, 69 | onAbort: PropTypes.func, 70 | onRedirect: PropTypes.func.isRequired, 71 | onWillInitialize: PropTypes.func, 72 | onDidInitialize: PropTypes.func, 73 | onInitializeError: PropTypes.func, 74 | customButton: PropTypes.func 75 | }; 76 | export var OptionsPropTypeBase = { 77 | amount: PropTypes.number.isRequired, 78 | currency: PropTypes.oneOf([ 79 | 'AUD', 80 | 'BIF', 81 | 'CDF', 82 | 'CAD', 83 | 'CVE', 84 | 'EUR', 85 | 'GBP', 86 | 'GHS', 87 | 'GMD', 88 | 'GNF', 89 | 'KES', 90 | 'LRD', 91 | 'MWK', 92 | 'MZN', 93 | 'NGN', 94 | 'RWF', 95 | 'SLL', 96 | 'STD', 97 | 'TZS', 98 | 'UGX', 99 | 'USD', 100 | 'XAF', 101 | 'XOF', 102 | 'ZAR', 103 | 'ZMK', 104 | 'ZMW', 105 | 'ZWD' 106 | ]), 107 | payment_plan: PropTypes.number, 108 | subaccounts: PropTypes.arrayOf(PropTypes.shape({ 109 | id: PropTypes.string.isRequired, 110 | transaction_split_ratio: PropTypes.number, 111 | transaction_charge_type: PropTypes.string, 112 | transaction_charge: PropTypes.number 113 | })), 114 | integrity_hash: PropTypes.string 115 | }; 116 | var PayWithFlutterwaveBase = /** @class */ (function (_super) { 117 | __extends(PayWithFlutterwaveBase, _super); 118 | function PayWithFlutterwaveBase() { 119 | var _this = _super !== null && _super.apply(this, arguments) || this; 120 | _this.state = { 121 | isPending: false, 122 | link: null, 123 | resetLink: false, 124 | showDialog: false, 125 | reference: null 126 | }; 127 | _this.reset = function () { 128 | if (_this.abortController) { 129 | _this.abortController.abort(); 130 | } 131 | // reset the necessaries 132 | _this.setState(function (_a) { 133 | var resetLink = _a.resetLink, link = _a.link; 134 | return ({ 135 | isPending: false, 136 | link: resetLink ? null : link, 137 | resetLink: false, 138 | showDialog: false 139 | }); 140 | }); 141 | }; 142 | _this.handleOptionsChanged = function () { 143 | var _a = _this.state, showDialog = _a.showDialog, link = _a.link; 144 | if (!link) { 145 | return; 146 | } 147 | if (!showDialog) { 148 | return _this.setState({ 149 | link: null, 150 | reference: null 151 | }); 152 | } 153 | _this.setState({ resetLink: true }); 154 | }; 155 | _this.handleAbort = function () { 156 | var onAbort = _this.props.onAbort; 157 | if (onAbort) { 158 | onAbort(); 159 | } 160 | _this.reset(); 161 | }; 162 | _this.handleRedirect = function (params) { 163 | var onRedirect = _this.props.onRedirect; 164 | // reset payment link 165 | _this.setState(function (_a) { 166 | var resetLink = _a.resetLink, reference = _a.reference; 167 | return ({ 168 | reference: params.flwref || params.status === 'successful' ? null : reference, 169 | resetLink: params.flwref || params.status === 'successful' ? true : resetLink, 170 | showDialog: false 171 | }); 172 | }, function () { 173 | onRedirect(params); 174 | _this.reset(); 175 | }); 176 | }; 177 | _this.handleInit = function () { return __awaiter(_this, void 0, void 0, function () { 178 | var _a, options, onWillInitialize, onInitializeError, onDidInitialize, init, _b, isPending, reference, link; 179 | var _this = this; 180 | return __generator(this, function (_c) { 181 | _a = this.props, options = _a.options, onWillInitialize = _a.onWillInitialize, onInitializeError = _a.onInitializeError, onDidInitialize = _a.onDidInitialize, init = _a.init; 182 | _b = this.state, isPending = _b.isPending, reference = _b.reference, link = _b.link; 183 | // just show the dialod if the link is already set 184 | if (link) { 185 | return [2 /*return*/, this.setState({ showDialog: true })]; 186 | } 187 | // throw error if transaction reference has not changed 188 | if (reference === this.props.reference) { 189 | // fire oninitialize error handler if available 190 | if (onInitializeError) { 191 | onInitializeError(new FlutterwaveInitError({ 192 | message: 'Please generate a new transaction reference.', 193 | code: 'SAME_TXREF' 194 | })); 195 | } 196 | return [2 /*return*/]; 197 | } 198 | // stop if currently in pending mode 199 | if (isPending) { 200 | return [2 /*return*/]; 201 | } 202 | // initialize abort controller if not set 203 | this.abortController = new AbortController; 204 | // fire will initialize handler if available 205 | if (onWillInitialize) { 206 | onWillInitialize(); 207 | } 208 | this.setState({ 209 | isPending: true, 210 | link: null, 211 | reference: this.props.reference, 212 | showDialog: false 213 | }, function () { return __awaiter(_this, void 0, void 0, function () { 214 | var paymentLink, error_1; 215 | return __generator(this, function (_a) { 216 | switch (_a.label) { 217 | case 0: 218 | _a.trys.push([0, 2, , 3]); 219 | return [4 /*yield*/, init(__assign(__assign({}, options), { redirect_url: REDIRECT_URL }), this.abortController)]; 220 | case 1: 221 | paymentLink = _a.sent(); 222 | // set payment link 223 | this.setState({ 224 | link: paymentLink, 225 | isPending: false, 226 | showDialog: true 227 | }, function () { 228 | // fire did initialize handler if available 229 | if (onDidInitialize) { 230 | onDidInitialize(); 231 | } 232 | }); 233 | return [3 /*break*/, 3]; 234 | case 2: 235 | error_1 = _a.sent(); 236 | // stop if request was canceled 237 | if (error_1 && /aborterror/i.test(error_1.code)) { 238 | return [2 /*return*/]; 239 | } 240 | // call onInitializeError handler if an error occured 241 | if (onInitializeError) { 242 | onInitializeError(error_1); 243 | } 244 | // set payment link to reset 245 | this.setState({ 246 | resetLink: true, 247 | reference: null 248 | }, this.reset); 249 | return [3 /*break*/, 3]; 250 | case 3: return [2 /*return*/]; 251 | } 252 | }); 253 | }); }); 254 | return [2 /*return*/]; 255 | }); 256 | }); }; 257 | return _this; 258 | } 259 | PayWithFlutterwaveBase.prototype.componentDidUpdate = function (prevProps) { 260 | var prevOptions = JSON.stringify(prevProps.options); 261 | var options = JSON.stringify(this.props.options); 262 | if (prevOptions !== options) { 263 | this.handleOptionsChanged(); 264 | } 265 | }; 266 | PayWithFlutterwaveBase.prototype.componentWillUnmount = function () { 267 | if (this.abortController) { 268 | this.abortController.abort(); 269 | } 270 | }; 271 | PayWithFlutterwaveBase.prototype.render = function () { 272 | var _a = this.state, link = _a.link, showDialog = _a.showDialog; 273 | return (<> 274 | {this.renderButton()} 275 | 276 | ); 277 | }; 278 | PayWithFlutterwaveBase.prototype.renderButton = function () { 279 | var _a = this.props, alignLeft = _a.alignLeft, customButton = _a.customButton, children = _a.children, style = _a.style; 280 | var isPending = this.state.isPending; 281 | if (customButton) { 282 | return customButton({ 283 | disabled: isPending, 284 | onPress: this.handleInit 285 | }); 286 | } 287 | return ; 288 | }; 289 | return PayWithFlutterwaveBase; 290 | }(React.Component)); 291 | export default PayWithFlutterwaveBase; 292 | -------------------------------------------------------------------------------- /dist/assets/loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/dist/assets/loader.gif -------------------------------------------------------------------------------- /dist/assets/pry-button-content.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/dist/assets/pry-button-content.png -------------------------------------------------------------------------------- /dist/configs.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * V# API Standard initialization endpoint 3 | */ 4 | export declare const STANDARD_URL = "https://api.flutterwave.com/v3/sdkcheckout/payments"; 5 | /** 6 | * Redirect URL used in V3 FlutterwaveButton 7 | */ 8 | export declare const REDIRECT_URL = "https://flutterwave.com/rn-redirect"; 9 | /** 10 | * Fluttereave volors 11 | */ 12 | export declare const colors: { 13 | primary: string; 14 | primaryLight: string; 15 | secondary: string; 16 | transparent: string; 17 | }; 18 | /** 19 | * Payment options available in V3 20 | */ 21 | export declare const PAYMENT_OPTIONS: string[]; 22 | /** 23 | * V2 API standard initialization endpoint 24 | */ 25 | export declare const STANDARD_URL_V2: string; 26 | /** 27 | * Payment options available in V2 API 28 | */ 29 | export declare const PAYMENT_OPTIONS_V2: string[]; 30 | //# sourceMappingURL=configs.d.ts.map -------------------------------------------------------------------------------- /dist/configs.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"configs.d.ts","sourceRoot":"","sources":["../src/configs.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,YAAY,wDAAwD,CAAC;AAElF;;GAEG;AACH,eAAO,MAAM,YAAY,wCAAwC,CAAC;AAElE;;GAEG;AACH,eAAO,MAAM,MAAM;;;;;CAKlB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,eAAe,UAkB3B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,MACiC,CAAC;AAEhE;;GAEG;AACH,eAAO,MAAM,kBAAkB,UAc9B,CAAC"} -------------------------------------------------------------------------------- /dist/configs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * V# API Standard initialization endpoint 3 | */ 4 | export var STANDARD_URL = 'https://api.flutterwave.com/v3/sdkcheckout/payments'; 5 | /** 6 | * Redirect URL used in V3 FlutterwaveButton 7 | */ 8 | export var REDIRECT_URL = 'https://flutterwave.com/rn-redirect'; 9 | /** 10 | * Fluttereave volors 11 | */ 12 | export var colors = { 13 | primary: '#f5a623', 14 | primaryLight: '#f9ce85', 15 | secondary: '#12122C', 16 | transparent: 'rgba(0,0,0,0)' 17 | }; 18 | /** 19 | * Payment options available in V3 20 | */ 21 | export var PAYMENT_OPTIONS = [ 22 | 'account', 23 | 'card', 24 | 'banktransfer', 25 | 'mpesa', 26 | 'mobilemoneyrwanda', 27 | 'mobilemoneyzambia', 28 | 'qr', 29 | 'mobilemoneyuganda', 30 | 'ussd', 31 | 'credit', 32 | 'barter', 33 | 'mobilemoneyghana', 34 | 'payattitude', 35 | 'mobilemoneyfranco', 36 | 'paga', 37 | '1voucher', 38 | 'mobilemoneytanzania', 39 | ]; 40 | /** 41 | * V2 API standard initialization endpoint 42 | */ 43 | export var STANDARD_URL_V2 = 'https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/hosted/pay'; 44 | /** 45 | * Payment options available in V2 API 46 | */ 47 | export var PAYMENT_OPTIONS_V2 = [ 48 | 'card', 49 | 'account', 50 | 'ussd', 51 | 'qr', 52 | 'mpesa', 53 | 'mobilemoneyghana', 54 | 'mobilemoneyuganda', 55 | 'mobilemoneyrwanda', 56 | 'mobilemoneyzambia', 57 | 'mobilemoneytanzania', 58 | 'barter', 59 | 'bank transfer', 60 | 'wechat', 61 | ]; 62 | -------------------------------------------------------------------------------- /dist/index.d.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInit from './FlutterwaveInit'; 2 | import FlutterwaveInitV2 from './FlutterwaveInitV2'; 3 | import PayWithFlutterwave from './PayWithFlutterwave'; 4 | import PayWithFlutterwaveV2 from './PayWithFlutterwaveV2'; 5 | import FlutterwaveButton from './FlutterwaveButton'; 6 | import FlutterwaveCheckout from './FlutterwaveCheckout'; 7 | export { FlutterwaveInit, PayWithFlutterwave, FlutterwaveInitV2, PayWithFlutterwaveV2, FlutterwaveButton, FlutterwaveCheckout, }; 8 | export default PayWithFlutterwave; 9 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /dist/index.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAChD,OAAO,iBAAiB,MAAM,qBAAqB,CAAC;AACpD,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AACtD,OAAO,oBAAoB,MAAM,wBAAwB,CAAC;AAC1D,OAAO,iBAAiB,MAAM,qBAAqB,CAAC;AACpD,OAAO,mBAAmB,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,GACpB,CAAC;AAGF,eAAe,kBAAkB,CAAC"} -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | import FlutterwaveInit from './FlutterwaveInit'; 2 | import FlutterwaveInitV2 from './FlutterwaveInitV2'; 3 | import PayWithFlutterwave from './PayWithFlutterwave'; 4 | import PayWithFlutterwaveV2 from './PayWithFlutterwaveV2'; 5 | import FlutterwaveButton from './FlutterwaveButton'; 6 | import FlutterwaveCheckout from './FlutterwaveCheckout'; 7 | // export modules 8 | export { FlutterwaveInit, PayWithFlutterwave, FlutterwaveInitV2, PayWithFlutterwaveV2, FlutterwaveButton, FlutterwaveCheckout, }; 9 | // export v3 PayWithFlutterwave as default 10 | export default PayWithFlutterwave; 11 | -------------------------------------------------------------------------------- /dist/utils/CustomPropTypesRules.d.ts: -------------------------------------------------------------------------------- 1 | export declare const PaymentOptionsPropRule: (options: string[]) => (props: { 2 | [k: string]: any; 3 | }, propName: string) => Error | null; 4 | //# sourceMappingURL=CustomPropTypesRules.d.ts.map -------------------------------------------------------------------------------- /dist/utils/CustomPropTypesRules.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"CustomPropTypesRules.d.ts","sourceRoot":"","sources":["../../src/utils/CustomPropTypesRules.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,sBAAsB;;oCA4BlC,CAAA"} -------------------------------------------------------------------------------- /dist/utils/CustomPropTypesRules.js: -------------------------------------------------------------------------------- 1 | export var PaymentOptionsPropRule = function (options) { return function (props, propName) { 2 | // skip check if payment options is not defined 3 | if (props[propName] === undefined) { 4 | return null; 5 | } 6 | // if not an array of payment options 7 | if (typeof props[propName] !== 'string') { 8 | return new Error('"payment_methods" should be a string.'); 9 | } 10 | var paymentOptionsList = props[propName].split(','); 11 | var _loop_1 = function (i) { 12 | if (options.findIndex(function (j) { return j.trim() === paymentOptionsList[i].trim(); }) === -1) { 13 | return { value: new Error("\"payment_options\"(" + props[propName] + ") must be any of the following values.\n" + options.map(function (i, n) { return n + 1 + ". " + i + "\n"; }).join('')) }; 14 | } 15 | }; 16 | for (var i = 0; i < paymentOptionsList.length; i++) { 17 | var state_1 = _loop_1(i); 18 | if (typeof state_1 === "object") 19 | return state_1.value; 20 | } 21 | return null; 22 | }; }; 23 | -------------------------------------------------------------------------------- /dist/utils/FlutterwaveInitError.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Flutterwave Init Error 3 | */ 4 | export default class FlutterwaveInitError extends Error { 5 | /** 6 | * Error code 7 | * @var string 8 | */ 9 | code: string; 10 | /** 11 | * Error code 12 | * @var string 13 | */ 14 | errorId?: string; 15 | /** 16 | * Error code 17 | * @var string 18 | */ 19 | errors?: Array; 20 | /** 21 | * Constructor Method 22 | * @param props {message?: string; code?: string} 23 | */ 24 | constructor(props: { 25 | message: string; 26 | code: string; 27 | errorId?: string; 28 | errors?: Array; 29 | }); 30 | } 31 | //# sourceMappingURL=FlutterwaveInitError.d.ts.map -------------------------------------------------------------------------------- /dist/utils/FlutterwaveInitError.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"FlutterwaveInitError.d.ts","sourceRoot":"","sources":["../../src/utils/FlutterwaveInitError.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,oBAAqB,SAAQ,KAAK;IACrD;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;MAGE;IACF,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;MAGE;IACF,MAAM,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAEvB;;;OAGG;gBACS,KAAK,EAAE;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;KAAC;CAM7F"} -------------------------------------------------------------------------------- /dist/utils/FlutterwaveInitError.js: -------------------------------------------------------------------------------- 1 | var __extends = (this && this.__extends) || (function () { 2 | var extendStatics = function (d, b) { 3 | extendStatics = Object.setPrototypeOf || 4 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 5 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 6 | return extendStatics(d, b); 7 | }; 8 | return function (d, b) { 9 | extendStatics(d, b); 10 | function __() { this.constructor = d; } 11 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 12 | }; 13 | })(); 14 | /** 15 | * Flutterwave Init Error 16 | */ 17 | var FlutterwaveInitError = /** @class */ (function (_super) { 18 | __extends(FlutterwaveInitError, _super); 19 | /** 20 | * Constructor Method 21 | * @param props {message?: string; code?: string} 22 | */ 23 | function FlutterwaveInitError(props) { 24 | var _this = _super.call(this, props.message) || this; 25 | _this.code = props.code; 26 | _this.errorId = props.errorId; 27 | _this.errors = props.errors; 28 | return _this; 29 | } 30 | return FlutterwaveInitError; 31 | }(Error)); 32 | export default FlutterwaveInitError; 33 | -------------------------------------------------------------------------------- /dist/utils/ResponseParser.d.ts: -------------------------------------------------------------------------------- 1 | import { ResponseData } from "../FlutterwaveInit"; 2 | /** 3 | * The purpose of this function is to parse the response message gotten from a 4 | * payment initialization error. 5 | * @param message string 6 | * @param code string (optional) 7 | * @returns {message: string; code: string} 8 | */ 9 | export default function ResponseParser({ status, errors, message, data, code, error_id, }: ResponseData): Promise; 10 | //# sourceMappingURL=ResponseParser.d.ts.map -------------------------------------------------------------------------------- /dist/utils/ResponseParser.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"ResponseParser.d.ts","sourceRoot":"","sources":["../../src/utils/ResponseParser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAGhD;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,EACE,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,QAAQ,GACT,EAAE,YAAY,GACd,OAAO,CAAC,MAAM,CAAC,CA6CjB"} -------------------------------------------------------------------------------- /dist/utils/ResponseParser.js: -------------------------------------------------------------------------------- 1 | import FlutterwaveInitError from "./FlutterwaveInitError"; 2 | /** 3 | * The purpose of this function is to parse the response message gotten from a 4 | * payment initialization error. 5 | * @param message string 6 | * @param code string (optional) 7 | * @returns {message: string; code: string} 8 | */ 9 | export default function ResponseParser(_a) { 10 | var status = _a.status, errors = _a.errors, message = _a.message, data = _a.data, code = _a.code, error_id = _a.error_id; 11 | return new Promise(function (resolve, reject) { 12 | // return success message 13 | if (status === 'success') { 14 | // check if data or data link is missing 15 | if (!data || !data.link) { 16 | return reject(new FlutterwaveInitError({ 17 | code: 'MALFORMED_RESPONSE', 18 | message: message 19 | })); 20 | } 21 | // return the payment link 22 | return resolve(data.link); 23 | } 24 | // missing authorization 25 | if (/authorization/i.test(message) && /required/i.test(message)) { 26 | reject(new FlutterwaveInitError({ 27 | code: 'AUTH_MISSING', 28 | message: message 29 | })); 30 | } 31 | // invalid authorization 32 | if (/authorization/i.test(message) && /invalid/i.test(message)) { 33 | reject(new FlutterwaveInitError({ 34 | code: 'AUTH_INVALID', 35 | message: message 36 | })); 37 | } 38 | // field errors 39 | if (errors) { 40 | reject(new FlutterwaveInitError({ 41 | code: 'INVALID_OPTIONS', 42 | message: message, 43 | errors: errors.map(function (i) { return i.message; }) 44 | })); 45 | } 46 | // defaults to the initially passed message 47 | reject(new FlutterwaveInitError({ 48 | code: String(code || 'STANDARD_INIT_ERROR').toUpperCase(), 49 | message: message, 50 | errorId: error_id 51 | })); 52 | }); 53 | } 54 | -------------------------------------------------------------------------------- /docs/AbortingPaymentInitialization.md: -------------------------------------------------------------------------------- 1 | # Aborting Payment Initialization 2 | :wave: 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, we use `fetch` underneath the hood to make the request to the standard payment endpoint and `fetch` allows you to pass an [abort controller](https://github.com/mo/abortcontroller-polyfill) which you can use to cancel ongoing requests, if your version of React Native does not have the abort functionality for fetch in the Javascript runtime, you will need to [install the polyfill](https://github.com/mo/abortcontroller-polyfill) before moving on. Below is a code snippet showcasing how you can go about cancelling an ongoing payment initialization. 3 | 4 | **:point_right:`If you have already installed the polyfill or have it already available in the Javascript runtime, this action happens automatically within FlutterwaveButton.`** 5 | 6 | ````jsx 7 | import React from 'react'; 8 | import {View, TouchableOpacity} from 'react-native'; 9 | import {FlutterwaveInit} from 'flutterwave-react-native'; 10 | 11 | class MyCart extends React.Component { 12 | abortController = null; 13 | 14 | componentWillUnmout() { 15 | if (this.abortController) { 16 | this.abortController.abort(); 17 | } 18 | } 19 | 20 | handlePaymentInitialization = () => { 21 | this.setState({ 22 | isPending: true, 23 | }, () => { 24 | // set abort controller 25 | this.abortController = new AbortController; 26 | try { 27 | // initialize payment 28 | const paymentLink = await FlutterwaveInit( 29 | { 30 | tx_ref: generateTransactionRef(), 31 | authorization: '[merchant public key]', 32 | amount: 100, 33 | currency: 'USD', 34 | customer: { 35 | email: 'customer-email@example.com', 36 | }, 37 | payment_options: 'card', 38 | }, 39 | this.abortController 40 | ); 41 | // use payment link 42 | return this.usePaymentLink(paymentLink); 43 | } catch (error) { 44 | // do nothing if our payment initialization was aborted 45 | if (error.code === 'ABORTERROR') { 46 | return; 47 | } 48 | // handle other errors 49 | this.displayErrorMessage(error.message); 50 | } 51 | }); 52 | } 53 | 54 | render() { 55 | const {isPending} = this.state; 56 | return ( 57 | 58 | ... 59 | 67 | Pay $100 68 | 69 | 70 | ) 71 | } 72 | } 73 | ```` 74 | In the above code we created a component called `MyCart` within that component we have an `abortController` property and in the same component we have two methods that interact with this property, the first is the `handlePaymentInitialization` method, this creates the abort controller before initializing the payment, the second method is `componentWillUnmount`, this is a react lifecycle hook method which is fired when the component is being unmounted, you are expected to unsubscribe from any event here before the component unmounts, so within this method we check to see if the abort controller has been defined and if it has, we call the abort method on the controller, this will abort the ongoing payment initialization and return an error with the error code `ABORTERROR`, if the we check the error code and it is `ABORTERROR` we can then stop the execution of `handlePaymentInitialization` so nothing else happens within our unmounted component. 75 | 76 | And that's all you need to abort an ongoing payment initialization. 77 | 78 | With love from Flutterwave. :yellow_heart: 79 | -------------------------------------------------------------------------------- /docs/v2/AbortingPaymentInitialization.md: -------------------------------------------------------------------------------- 1 | # Aborting Payment Initialization 2 | :wave: Hi, so there are cases where you have already initialized a payment with `FlutterwaveInitV2` 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, we use `fetch` underneath the hood to make the request to the standard payment endpoint and `fetch` allows you to pass an [abort controller](https://github.com/mo/abortcontroller-polyfill) which you can use to cancel ongoing requests, if your version of React Native does not have the abort functionality for fetch in the Javascript runtime, you will need to [install the polyfill](https://github.com/mo/abortcontroller-polyfill) before moving on. Below is a code snippet showcasing how you can go about cancelling an ongoing payment initialization. 3 | 4 | :point_right:**`If you have already installed the polyfill or have it already available in the Javascript runtime, this action happens automatically within FlutterwaveButton.`** 5 | 6 | ````jsx 7 | import React from 'react'; 8 | import {View, TouchableOpacity} from 'react-native'; 9 | import {FlutterwaveInitV2} from 'flutterwave-react-native'; 10 | 11 | class MyCart extends React.Component { 12 | abortController = null; 13 | 14 | componentWillUnmout() { 15 | if (this.abortController) { 16 | this.abortController.abort(); 17 | } 18 | } 19 | 20 | handlePaymentInitialization = () => { 21 | this.setState({ 22 | isPending: true, 23 | }, () => { 24 | // set abort controller 25 | this.abortController = new AbortController; 26 | try { 27 | // initialize a new payment 28 | const paymentLink = await FlutterwaveInitV2( 29 | { 30 | txref: generateTransactionRef(), 31 | PBFPubKey: '[Your Flutterwave Public Key]', 32 | amount: 100, 33 | currency: 'USD', 34 | }, 35 | this.abortController 36 | ); 37 | // use payment link 38 | return this.usePaymentLink(paymentLink); 39 | } catch (error) { 40 | // do nothing if our payment initialization was aborted 41 | if (error.code === 'ABORTERROR') { 42 | return; 43 | } 44 | // handle other errors 45 | this.displayErrorMessage(error.message); 46 | } 47 | }) 48 | } 49 | 50 | render() { 51 | const {isPending} = this.state; 52 | return ( 53 | 54 | ... 55 | 63 | Pay $100 64 | 65 | 66 | ) 67 | } 68 | } 69 | ```` 70 | In the above code we created a component called `MyCart` within that component we have an `abortController` property and in the same component we have two methods that interact with this property, the first is the `handlePaymentInitialization` method, this creates the abort controller before initializing the payment, the second method is `componentWillUnmount`, this is a react lifecycle hook method which is fired when the component is being unmounted, you are expected to unsubscribe from any event here before the component unmounts, so within this method we check to see if the abort controller has been defined and if it has, we call the abort method on the controller, this will abort the ongoing payment initialization and return an error with the error code `ABORTERROR`, if the we check the error code and it is `ABORTERROR` we can then stop the execution of `handlePaymentInitialization` so nothing else happens within our unmounted component. 71 | 72 | And that's all you need to abort an ongoing payment initialization. 73 | 74 | With love from Flutterwave. :yellow_heart: 75 | -------------------------------------------------------------------------------- /global.d.ts: -------------------------------------------------------------------------------- 1 | import 'jest-fetch-mock' 2 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // All imported modules in your tests should be mocked automatically 6 | automock: false, 7 | 8 | // Stop running tests after `n` failures 9 | // bail: 0, 10 | 11 | // Respect "browser" field in package.json when resolving modules 12 | // browser: false, 13 | 14 | // The directory where Jest should store its cached dependency information 15 | // cacheDirectory: "/private/var/folders/8f/kgcy219d1dvfvbcqky441_d00000gp/T/jest_dy", 16 | 17 | // Automatically clear mock calls and instances between every test 18 | clearMocks: true, 19 | 20 | // Indicates whether the coverage information should be collected while executing the test 21 | // collectCoverage: false, 22 | 23 | // An array of glob patterns indicating a set of files for which coverage information should be collected 24 | // collectCoverageFrom: null, 25 | 26 | // The directory where Jest should output its coverage files 27 | // coverageDirectory: "coverage", 28 | 29 | // An array of regexp pattern strings used to skip coverage collection 30 | // coveragePathIgnorePatterns: [ 31 | // "/node_modules/" 32 | // ], 33 | 34 | // A list of reporter names that Jest uses when writing coverage reports 35 | // coverageReporters: [ 36 | // "json", 37 | // "text", 38 | // "lcov", 39 | // "clover" 40 | // ], 41 | 42 | // An object that configures minimum threshold enforcement for coverage results 43 | // coverageThreshold: null, 44 | 45 | // A path to a custom dependency extractor 46 | // dependencyExtractor: null, 47 | 48 | // Make calling deprecated APIs throw helpful error messages 49 | // errorOnDeprecated: false, 50 | 51 | // Force coverage collection from ignored files usin a array of glob patterns 52 | // forceCoverageMatch: [], 53 | 54 | // A path to a module which exports an async function that is triggered once before all test suites 55 | // globalSetup: null, 56 | 57 | // A path to a module which exports an async function that is triggered once after all test suites 58 | // globalTeardown: null, 59 | 60 | // A set of global variables that need to be available in all test environments 61 | // globals: {}, 62 | 63 | // An array of directory names to be searched recursively up from the requiring module's location 64 | // moduleDirectories: [ 65 | // "node_modules" 66 | // ], 67 | 68 | // An array of file extensions your modules use 69 | // moduleFileExtensions: [ 70 | // "js", 71 | // "json", 72 | // "jsx", 73 | // "ts", 74 | // "tsx", 75 | // "node" 76 | // ], 77 | 78 | // A map from regular expressions to module names that allow to stub out resources with a single module 79 | // moduleNameMapper: {}, 80 | 81 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 82 | // modulePathIgnorePatterns: [], 83 | 84 | // Activates notifications for test results 85 | // notify: false, 86 | 87 | // An enum that specifies notification mode. Requires { notify: true } 88 | // notifyMode: "failure-change", 89 | 90 | // A preset that is used as a base for Jest's configuration 91 | preset: 'react-native', 92 | 93 | // Run tests from one or more projects 94 | // projects: null, 95 | 96 | // Use this configuration option to add custom reporters to Jest 97 | // reporters: undefined, 98 | 99 | // Automatically reset mock state between every test 100 | // resetMocks: false, 101 | 102 | // Reset the module registry before running each individual test 103 | // resetModules: false, 104 | 105 | // A path to a custom resolver 106 | // resolver: null, 107 | 108 | // Automatically restore mock state between every test 109 | // restoreMocks: false, 110 | 111 | // The root directory that Jest should scan for tests and modules within 112 | // rootDir: null, 113 | 114 | // A list of paths to directories that Jest should use to search for files in 115 | roots: [ 116 | "./__tests__" 117 | ], 118 | 119 | // Allows you to use a custom runner instead of Jest's default test runner 120 | // runner: "jest-runner", 121 | 122 | // The paths to modules that run some code to configure or set up the testing environment before each test 123 | setupFiles: [ 124 | "./setupJest.js" 125 | ], 126 | 127 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 128 | // setupFilesAfterEnv: [], 129 | 130 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 131 | // snapshotSerializers: [], 132 | 133 | // The test environment that will be used for testing 134 | testEnvironment: 'jsdom', 135 | 136 | // Options that will be passed to the testEnvironment 137 | // testEnvironmentOptions: {}, 138 | 139 | // Adds a location field to test results 140 | // testLocationInResults: false, 141 | 142 | // The glob patterns Jest uses to detect test files 143 | // testMatch: [ 144 | // "**/__tests__/**/*.[jt]s?(x)", 145 | // "**/?(*.)+(spec|test).[tj]s?(x)" 146 | // ], 147 | 148 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 149 | // testPathIgnorePatterns: [ 150 | // "/node_modules/" 151 | // ], 152 | 153 | // The regexp pattern or array of patterns that Jest uses to detect test files 154 | // testRegex: [], 155 | 156 | // This option allows the use of a custom results processor 157 | // testResultsProcessor: null, 158 | 159 | // This option allows use of a custom test runner 160 | // testRunner: "jasmine2", 161 | 162 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 163 | // testURL: "http://localhost", 164 | 165 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 166 | // timers: "real", 167 | 168 | // A map from regular expressions to paths to transformers 169 | 170 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 171 | // transformIgnorePatterns: [ 172 | // "/node_modules/" 173 | // ], 174 | 175 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 176 | // unmockedModulePathPatterns: undefined, 177 | 178 | // Indicates whether each individual test should be reported during the run 179 | // verbose: null, 180 | 181 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 182 | // watchPathIgnorePatterns: [], 183 | 184 | // Whether to use watchman for file crawling 185 | // watchman: true, 186 | }; 187 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flutterwave-react-native", 3 | "version": "1.0.6", 4 | "description": "The official React-Native library for Flutterwave for business v2 and v3 APIs.", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "build": "tsc", 8 | "postbuild": "npm run copy-files", 9 | "lint": "eslint \"src/**/*.{ts, tsx}\"", 10 | "format": "prettier-standard --format", 11 | "test": "jest --coverage", 12 | "copy-files": "copyfiles -u 1 src/assets/*.gif src/assets/*.png src/assets dist", 13 | "commit": "npx git-cz", 14 | "release": "semantic-release", 15 | "set-example": "npm run build && node setExample.js" 16 | }, 17 | "files": [ 18 | "dist" 19 | ], 20 | "keywords": [ 21 | "Flutterwave", 22 | "RavePay", 23 | "React-native-payment", 24 | "Payment", 25 | "Payments" 26 | ], 27 | "author": "Flutterwave Developers", 28 | "license": "MIT", 29 | "devDependencies": { 30 | "@babel/core": "^7.9.0", 31 | "@babel/runtime": "^7.6.3", 32 | "@react-native-community/eslint-config": "^1.0.0", 33 | "@semantic-release/git": "^9.0.0", 34 | "@types/jest": "^24.9.1", 35 | "@types/react": "^16.9.34", 36 | "@types/react-native": "^0.62.2", 37 | "@types/react-test-renderer": "^16.9.2", 38 | "@typescript-eslint/eslint-plugin": "^2.27.0", 39 | "@typescript-eslint/parser": "^2.27.0", 40 | "abortcontroller-polyfill": "^1.4.0", 41 | "babel-core": "^7.0.0-bridge.0", 42 | "babel-jest": "^24.9.0", 43 | "babel-plugin-module-resolver": "3.1.3", 44 | "babel-preset-react-native": "^4.0.1", 45 | "commitizen": "^4.0.4", 46 | "copyfiles": "^2.2.0", 47 | "cz-conventional-changelog": "^3.1.0", 48 | "dotenv": "^8.2.0", 49 | "eslint": "^6.8.0", 50 | "jest": "^24.9.0", 51 | "jest-fetch-mock": "^3.0.3", 52 | "log-symbols": "^4.0.0", 53 | "metro-react-native-babel-preset": "^0.56.0", 54 | "mockdate": "^3.0.2", 55 | "ncp": "^2.0.0", 56 | "prettier": "^2.0.4", 57 | "pretty-quick": "^2.0.1", 58 | "react": "^16.13.1", 59 | "react-native": "^0.62.2", 60 | "react-test-renderer": "16.8.6", 61 | "semantic-release": "^17.0.8", 62 | "ts-jest": "^24.2.0", 63 | "typescript": "^3.8.3" 64 | }, 65 | "peerDependencies": { 66 | "react": "*", 67 | "react-native": "*" 68 | }, 69 | "dependencies": { 70 | "prop-types": "^15.6.2", 71 | "react-native-webview": ">=6.0.2" 72 | }, 73 | "config": { 74 | "commitizen": { 75 | "path": "./node_modules/cz-conventional-changelog" 76 | } 77 | }, 78 | "directories": { 79 | "doc": "docs" 80 | }, 81 | "repository": { 82 | "type": "git", 83 | "url": "git+https://github.com/Flutterwave/flutterwave-react-native.git" 84 | }, 85 | "bugs": { 86 | "url": "https://github.com/Flutterwave/flutterwave-react-native/issues" 87 | }, 88 | "homepage": "https://github.com/Flutterwave/flutterwave-react-native#readme" 89 | } 90 | -------------------------------------------------------------------------------- /setExample.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | const packageInfo = require('./package-lock.json'); 3 | const logSymbols = require('log-symbols'); 4 | const {existsSync, mkdirSync} = require('fs'); 5 | const path = require('path'); 6 | const ncp = require('ncp'); 7 | const chalk = require('chalk'); 8 | const DIST_DIR = path.join(__dirname, './dist'); 9 | 10 | // logs error in particuler format to the terminal 11 | const logError = (title, message = undefined) => { 12 | console.log(' '); 13 | if (message) { 14 | console.log(chalk.red.bold(title)); 15 | console.log(logSymbols.error, chalk.red(message)); 16 | } else { 17 | console.log(logSymbols.error, chalk.red(title)); 18 | } 19 | console.log(' '); 20 | } 21 | 22 | // logs error in particuler format to the terminal 23 | const logSuccess = (message) => { 24 | console.log(logSymbols.success, message); 25 | } 26 | 27 | /** 28 | * This function is responsible for installing the built library in an example 29 | * project within the local environment this will always run so long as the 30 | * RN_FLW_EXAMPLE_PROJECT environment variable is set. 31 | */ 32 | (function setExample() { 33 | const {RN_FLW_EXAMPLE_PROJECT} = process.env; 34 | // stop if test project is not specified 35 | if (!RN_FLW_EXAMPLE_PROJECT) { 36 | return; 37 | } 38 | // create destination directory name 39 | const DESTINATION = path.join(RN_FLW_EXAMPLE_PROJECT, packageInfo.name); 40 | 41 | // stop if dist folder does not exist 42 | if (!existsSync(DIST_DIR)) { 43 | return logError( 44 | 'Build Not Found', 45 | 'Please execute \'npm run build\'.' 46 | ); 47 | } 48 | 49 | // stop if test folder does not exist 50 | if (!existsSync(RN_FLW_EXAMPLE_PROJECT)) { 51 | return logError( 52 | 'Example Project Not Found', 53 | 'Please add RN_FLW_EXAMPLE_PROJECT to your dot env file' 54 | ); 55 | } 56 | 57 | // log message stating the found test project 58 | console.log(' '); 59 | console.log(chalk.green.bold('Found Example Project')); 60 | logSuccess('Installing build...'); 61 | 62 | // create the library directory if it does not exist 63 | if (!existsSync(DESTINATION)) { 64 | logSuccess('Creating destination directory...'); 65 | mkdirSync(DESTINATION); 66 | logSuccess('Destination directory created successfully'); 67 | } 68 | 69 | // copy files 70 | ncp(DIST_DIR, DESTINATION, { 71 | stopOnErr: true, 72 | }, (err) => { 73 | // log error message 74 | if (err) { 75 | return logError('ERROR', err.message); 76 | } 77 | // log success message 78 | logSuccess('Library successfully installed at ' + DESTINATION + ''); 79 | console.log(' '); 80 | }); 81 | })(); 82 | 83 | -------------------------------------------------------------------------------- /setupJest.js: -------------------------------------------------------------------------------- 1 | import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'; 2 | require('jest-fetch-mock').enableMocks(); 3 | const frameTime = 1; 4 | 5 | jest.mock('react-native/Libraries/Alert/Alert', () => { 6 | return { 7 | alert: jest.fn() 8 | }; 9 | }); 10 | 11 | jest.mock('react-native/Libraries/Utilities/Dimensions', () => { 12 | return { 13 | get: () => ({ 14 | height: 1305, 15 | width: 300, 16 | }) 17 | }; 18 | }); 19 | 20 | global.requestAnimationFrame = cb => { 21 | setTimeout(cb, frameTime) 22 | } 23 | -------------------------------------------------------------------------------- /src/FlutterwaveButton.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | StyleSheet, 4 | Image, 5 | StyleProp, 6 | ViewStyle, 7 | TouchableHighlight, 8 | View, 9 | } from 'react-native'; 10 | import {colors} from './configs'; 11 | const pryContent = require('./assets/pry-button-content.png'); 12 | const contentSizeDimension = 8.2962962963; 13 | 14 | interface FlutterwaveButtonProps { 15 | style?: StyleProp; 16 | disabled?: boolean; 17 | alignLeft?: boolean; 18 | onPress?: () => void; 19 | } 20 | 21 | const FlutterwaveButton: React.FC< 22 | FlutterwaveButtonProps 23 | > = function FlutterwaveButton({ 24 | style, 25 | alignLeft, 26 | children, 27 | disabled, 28 | onPress 29 | }) { 30 | // render primary button 31 | return ( 32 | 44 | <> 45 | {children ? children : ( 46 | 53 | )} 54 | {disabled 55 | ? () 56 | : null} 57 | 58 | 59 | ); 60 | } 61 | 62 | // component UI styles 63 | const styles = StyleSheet.create({ 64 | buttonBusyOvelay: { 65 | position: 'absolute', 66 | left: 0, 67 | top: 0, 68 | bottom: 0, 69 | right: 0, 70 | backgroundColor: 'rgba(255, 255, 255, 0.6)', 71 | }, 72 | buttonBusy: { 73 | borderColor: colors.primaryLight, 74 | }, 75 | buttonAlignLeft: { 76 | justifyContent: 'flex-start', 77 | }, 78 | button: { 79 | paddingHorizontal: 16, 80 | minWidth: 100, 81 | height: 52, 82 | borderColor: colors.primary, 83 | borderWidth: 1, 84 | borderRadius: 6, 85 | backgroundColor: colors.primary, 86 | alignItems: 'center', 87 | justifyContent: 'center', 88 | flexDirection: 'row', 89 | overflow: 'hidden', 90 | }, 91 | buttonContent: { 92 | resizeMode: 'contain', 93 | width: 187.3, 94 | height: 187.3 / contentSizeDimension 95 | }, 96 | }); 97 | 98 | // export component as default 99 | export default FlutterwaveButton; 100 | -------------------------------------------------------------------------------- /src/FlutterwaveCheckout.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | StyleSheet, 4 | Modal, 5 | View, 6 | Animated, 7 | TouchableWithoutFeedback, 8 | Text, 9 | Alert, 10 | Image, 11 | Dimensions, 12 | Easing, 13 | TouchableOpacity, 14 | Platform, 15 | } from 'react-native'; 16 | import WebView from 'react-native-webview'; 17 | import {WebViewNavigation} from 'react-native-webview/lib/WebViewTypes'; 18 | import {colors} from './configs'; 19 | const loader = require('./assets/loader.gif'); 20 | const borderRadiusDimension = 24 / 896; 21 | const windowHeight = Dimensions.get('window').height; 22 | 23 | export interface FlutterwaveCheckoutProps { 24 | onRedirect?: (data: any) => void; 25 | onAbort?: () => void; 26 | link?: string; 27 | visible?: boolean; 28 | } 29 | 30 | interface FlutterwaveCheckoutBackdropProps { 31 | animation: Animated.Value, 32 | onPress?: () => void; 33 | } 34 | 35 | interface FlutterwaveCheckoutErrorProps { 36 | hasLink: boolean; 37 | onTryAgain: () => void; 38 | } 39 | 40 | const getRedirectParams = (url: string): {[k: string]: string} => { 41 | // initialize result container 42 | const res: any = {}; 43 | // if url has params 44 | if (url.split('?').length > 1) { 45 | // get query params in an array 46 | const params = url.split('?')[1].split('&'); 47 | // add url params to result 48 | for (let i = 0; i < params.length; i++) { 49 | const param: Array = params[i].split('='); 50 | const val = decodeURIComponent(param[1]).trim(); 51 | res[param[0]] = String(val); 52 | } 53 | } 54 | // return result 55 | return res; 56 | }; 57 | 58 | const FlutterwaveCheckout: React.FC = function FlutterwaveCheckout(props) { 59 | const {link, visible, onRedirect, onAbort} = props; 60 | const [show, setShow] = React.useState(false); 61 | const webviewRef = React.useRef(null); 62 | const animation = React.useRef(new Animated.Value(0)); 63 | 64 | const animateIn = React.useCallback(() => { 65 | setShow(true); 66 | Animated.timing(animation.current, { 67 | toValue: 1, 68 | duration: 700, 69 | easing: Easing.in(Easing.elastic(0.72)), 70 | useNativeDriver: false, 71 | }).start(); 72 | }, []); 73 | 74 | const animateOut = React.useCallback((): Promise => { 75 | return new Promise(resolve => { 76 | Animated.timing(animation.current, { 77 | toValue: 0, 78 | duration: 400, 79 | useNativeDriver: false, 80 | }).start(() => { 81 | setShow(false); 82 | resolve(); 83 | }); 84 | }) 85 | }, []); 86 | 87 | const handleReload = React.useCallback(() => { 88 | if (webviewRef.current) { 89 | webviewRef.current.reload(); 90 | } 91 | }, []); 92 | 93 | const handleAbort = React.useCallback((confirmed: boolean = false) => { 94 | if (!confirmed) { 95 | Alert.alert('', 'Are you sure you want to cancel this payment?', [ 96 | {text: 'No'}, 97 | { 98 | text: 'Yes, Cancel', 99 | style: 'destructive', 100 | onPress: () => handleAbort(true), 101 | }, 102 | ]); 103 | return; 104 | } 105 | // remove tx_ref and dismiss 106 | animateOut().then(onAbort); 107 | }, [onAbort, animateOut]); 108 | 109 | const handleNavigationStateChange = React.useCallback((ev: WebViewNavigation): boolean => { 110 | // cregex to check if redirect has occured on completion/cancel 111 | const rx = /\/flutterwave\.com\/rn-redirect/; 112 | // Don't end payment if not redirected back 113 | if (!rx.test(ev.url)) { 114 | return true; 115 | } 116 | // dismiss modal 117 | animateOut().then(() => { 118 | if (onRedirect) { 119 | onRedirect(getRedirectParams(ev.url)) 120 | } 121 | }); 122 | return false; 123 | }, [onRedirect]); 124 | 125 | const doAnimate = React.useCallback(() => { 126 | if (visible === show) { 127 | return; 128 | } 129 | if (visible) { 130 | return animateIn(); 131 | } 132 | animateOut().then(() => {}); 133 | }, [visible, show, animateOut, animateIn]); 134 | 135 | React.useEffect(() => { 136 | doAnimate(); 137 | return () => {}; 138 | }, [doAnimate]); 139 | 140 | const marginTop = animation.current.interpolate({ 141 | inputRange: [0, 1], 142 | outputRange: [windowHeight, 0], 143 | }); 144 | const opacity = animation.current.interpolate({ 145 | inputRange: [0, 0.3, 1], 146 | outputRange: [0, 1, 1], 147 | }); 148 | 149 | return ( 150 | 155 | handleAbort()} animation={animation.current} /> 156 | 166 | } 175 | renderLoading={() => } 176 | /> 177 | 178 | 179 | ) 180 | } 181 | 182 | const FlutterwaveCheckoutBackdrop: React.FC< 183 | FlutterwaveCheckoutBackdropProps 184 | > = function FlutterwaveCheckoutBackdrop({ 185 | animation, 186 | onPress 187 | }) { 188 | // Interpolation backdrop animation 189 | const backgroundColor = animation.interpolate({ 190 | inputRange: [0, 0.3, 1], 191 | outputRange: [colors.transparent, colors.transparent, 'rgba(0,0,0,0.5)'], 192 | }); 193 | return ( 194 | 195 | 196 | 197 | ); 198 | } 199 | 200 | export const FlutterwaveCheckoutError: React.FC = ({ 201 | hasLink, 202 | onTryAgain 203 | }): React.ReactElement => { 204 | return ( 205 | 206 | {hasLink ? ( 207 | <> 208 | 209 | An error occurred, please tab below to try again. 210 | 211 | 212 | Try Again 213 | 214 | 215 | ) : ( 216 | 217 | An error occurred, please close the checkout dialog and try again. 218 | 219 | )} 220 | 221 | ); 222 | } 223 | 224 | const FlutterwaveCheckoutLoader: React.FC<{}> = (): React.ReactElement => { 225 | return ( 226 | 227 | 232 | 233 | ); 234 | } 235 | 236 | const styles = StyleSheet.create({ 237 | errorActionButtonText: { 238 | textAlign: 'center', 239 | color: colors.primary, 240 | fontSize: 16, 241 | }, 242 | errorActionButton: { 243 | paddingHorizontal: 16, 244 | paddingVertical: 16, 245 | }, 246 | errorText: { 247 | color: colors.secondary, 248 | textAlign: 'center', 249 | marginBottom: 32, 250 | fontSize: 18, 251 | }, 252 | error: { 253 | position: 'absolute', 254 | left: 0, 255 | right: 0, 256 | bottom: 0, 257 | top: 0, 258 | backgroundColor: '#ffffff', 259 | justifyContent: 'center', 260 | alignItems: 'center', 261 | paddingHorizontal: 56, 262 | }, 263 | backdrop: { 264 | position: 'absolute', 265 | left: 0, 266 | right: 0, 267 | bottom: 0, 268 | top: 0, 269 | }, 270 | loadingImage: { 271 | width: 64, 272 | height: 64, 273 | resizeMode: 'contain', 274 | }, 275 | loading: { 276 | position: 'absolute', 277 | top: 0, 278 | right: 0, 279 | bottom: 0, 280 | left: 0, 281 | backgroundColor: 'rgba(255, 255, 255, 0.3)', 282 | justifyContent: 'center', 283 | alignItems: 'center', 284 | }, 285 | webviewContainer: { 286 | top: Platform.select({ios: 96, android: 64}), // status bar height aware for ios 287 | flex: 1, 288 | backgroundColor: '#efefef', 289 | paddingBottom: Platform.select({ios: 96, android: 64}), // status bar height aware for ios 290 | overflow: 'hidden', 291 | borderTopLeftRadius: windowHeight * borderRadiusDimension, 292 | borderTopRightRadius: windowHeight * borderRadiusDimension, 293 | }, 294 | webview: { 295 | flex: 1, 296 | backgroundColor: 'rgba(0,0,0,0)', 297 | }, 298 | }); 299 | 300 | export default FlutterwaveCheckout; 301 | -------------------------------------------------------------------------------- /src/FlutterwaveInit.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 2 | import ResponseParser from './utils/ResponseParser'; 3 | import {STANDARD_URL} from './configs'; 4 | 5 | export type Currency = 6 | 'AUD' | 7 | 'BIF' | 8 | 'CDF' | 9 | 'CAD' | 10 | 'CVE' | 11 | 'EUR' | 12 | 'GBP' | 13 | 'GHS' | 14 | 'GMD' | 15 | 'GNF' | 16 | 'KES' | 17 | 'LRD' | 18 | 'MWK' | 19 | 'MZN' | 20 | 'NGN' | 21 | 'RWF' | 22 | 'SLL' | 23 | 'STD' | 24 | 'TZS' | 25 | 'UGX' | 26 | 'USD' | 27 | 'XAF' | 28 | 'XOF' | 29 | 'ZAR' | 30 | 'ZMK' | 31 | 'ZMW' | 32 | 'ZWD'; 33 | 34 | export interface FlutterwaveInitSubAccount { 35 | id: string; 36 | transaction_split_ratio?: number; 37 | transaction_charge_type?: string; 38 | transaction_charge?: number; 39 | } 40 | 41 | export interface FlutterwaveInitOptionsBase { 42 | amount: number; 43 | currency?: Currency; 44 | integrity_hash?: string; 45 | payment_options?: string; 46 | payment_plan?: number; 47 | redirect_url: string; 48 | subaccounts?: Array; 49 | } 50 | 51 | interface FlutterwavePaymentMeta { 52 | [k: string]: any; 53 | } 54 | 55 | export interface FlutterwaveInitCustomer { 56 | email: string; 57 | phonenumber?: string; 58 | name?: string; 59 | } 60 | 61 | export interface FlutterwaveInitCustomizations { 62 | title?: string; 63 | logo?: string; 64 | description?: string; 65 | } 66 | 67 | export type FlutterwaveInitOptions = FlutterwaveInitOptionsBase & { 68 | authorization: string; 69 | tx_ref: string; 70 | customer: FlutterwaveInitCustomer; 71 | meta?: FlutterwavePaymentMeta | null; 72 | customizations?: FlutterwaveInitCustomizations; 73 | }; 74 | 75 | export interface FieldError { 76 | field: string; 77 | message: string; 78 | } 79 | 80 | export interface ResponseData { 81 | status?: 'success' | 'error'; 82 | message: string; 83 | error_id?: string; 84 | errors?: Array; 85 | code?: string; 86 | data?: { 87 | link: string; 88 | }; 89 | } 90 | 91 | interface FetchOptions { 92 | method: 'POST'; 93 | body: string; 94 | headers: Headers; 95 | signal?: AbortSignal; 96 | } 97 | 98 | /** 99 | * This function is responsible for making the request to 100 | * initialize a Flutterwave payment. 101 | * @param options FlutterwaveInitOptions 102 | * @param abortController AbortController 103 | * @return Promise 104 | */ 105 | export default async function FlutterwaveInit( 106 | options: FlutterwaveInitOptions, 107 | abortController?: AbortController, 108 | ): Promise { 109 | try { 110 | // get request body and authorization 111 | const {authorization, ...body} = options; 112 | // make request headers 113 | const headers = new Headers; 114 | headers.append('Content-Type', 'application/json'); 115 | headers.append('Authorization', `Bearer ${authorization}`); 116 | // make fetch options 117 | const fetchOptions: FetchOptions = { 118 | method: 'POST', 119 | body: JSON.stringify(body), 120 | headers: headers, 121 | } 122 | // add abortController if defined 123 | if (abortController) { 124 | fetchOptions.signal = abortController.signal 125 | }; 126 | // initialize payment 127 | const response = await fetch(STANDARD_URL, fetchOptions); 128 | // get response data 129 | const responseData: ResponseData = await response.json(); 130 | // resolve with the payment link 131 | return Promise.resolve(await ResponseParser(responseData)); 132 | } catch (e) { 133 | // always return a flutterwave init error 134 | const error = e instanceof FlutterwaveInitError 135 | ? e 136 | : new FlutterwaveInitError({message: e.message, code: e.name.toUpperCase()}) 137 | // resolve with error 138 | return Promise.reject(error); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/FlutterwaveInitV2.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 2 | import {STANDARD_URL_V2} from './configs'; 3 | import {Currency, FlutterwaveInitSubAccount} from './FlutterwaveInit'; 4 | 5 | export interface FlutterwaveInitOptionsBase { 6 | amount: number; 7 | currency?: Currency; 8 | integrity_hash?: string; 9 | payment_options?: string; 10 | payment_plan?: number; 11 | redirect_url: string; 12 | subaccounts?: Array; 13 | } 14 | 15 | export interface FieldError { 16 | field: string; 17 | message: string; 18 | } 19 | 20 | interface FetchOptions { 21 | method: 'POST'; 22 | body: string; 23 | headers: Headers; 24 | signal?: AbortSignal; 25 | } 26 | 27 | interface FlutterwavePaymentMetaV2 { 28 | metaname: string; 29 | metavalue: string; 30 | } 31 | 32 | export type FlutterwaveInitV2Options = FlutterwaveInitOptionsBase & { 33 | txref: string; 34 | PBFPubKey: string; 35 | customer_firstname?: string; 36 | customer_lastname?: string; 37 | customer_phone?: string; 38 | customer_email: string; 39 | country?: string; 40 | pay_button_text?: string; 41 | custom_title?: string; 42 | custom_description?: string; 43 | custom_logo?: string; 44 | meta?: Array; 45 | } 46 | 47 | interface ResponseJSON { 48 | status: 'success' | 'error'; 49 | message: string; 50 | data: { 51 | link?: string; 52 | code?: string; 53 | message?: string; 54 | }; 55 | } 56 | 57 | /** 58 | * This function is responsible for making the request to 59 | * initialize a Flutterwave payment. 60 | * @param options FlutterwaveInitOptions 61 | * @return Promise<{ 62 | * error: { 63 | * code: string; 64 | * message: string; 65 | * } | null; 66 | * link?: string | null; 67 | * }> 68 | */ 69 | export default async function FlutterwaveInitV2( 70 | options: FlutterwaveInitV2Options, 71 | abortController?: AbortController, 72 | ): Promise { 73 | try { 74 | // make request body 75 | const body = {...options}; 76 | // make request headers 77 | const headers = new Headers; 78 | headers.append('Content-Type', 'application/json'); 79 | // make fetch options 80 | const fetchOptions: FetchOptions = { 81 | method: 'POST', 82 | body: JSON.stringify(body), 83 | headers: headers, 84 | } 85 | // add abort controller if defined 86 | if (abortController) { 87 | fetchOptions.signal = abortController.signal 88 | }; 89 | // make http request 90 | const response = await fetch(STANDARD_URL_V2, fetchOptions); 91 | // get response json 92 | const responseJSON: ResponseJSON = await response.json(); 93 | // check if data is missing from response 94 | if (!responseJSON.data) { 95 | throw new FlutterwaveInitError({ 96 | code: 'STANDARD_INIT_ERROR', 97 | message: responseJSON.message || 'An unknown error occured!', 98 | }); 99 | } 100 | // check if the link is missing in data 101 | if (!responseJSON.data.link) { 102 | throw new FlutterwaveInitError({ 103 | code: responseJSON.data.code || 'MALFORMED_RESPONSE', 104 | message: responseJSON.data.message || 'An unknown error occured!', 105 | }); 106 | } 107 | // resolve with the payment link 108 | return Promise.resolve(responseJSON.data.link); 109 | } catch (e) { 110 | // always return a flutterwave init error 111 | const error = e instanceof FlutterwaveInitError 112 | ? e 113 | : new FlutterwaveInitError({message: e.message, code: e.name.toUpperCase()}) 114 | // resolve with error 115 | return Promise.reject(error); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/PayWithFlutterwave.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { 4 | PayWithFlutterwavePropsBase, 5 | OptionsPropTypeBase, 6 | PayWithFlutterwavePropTypesBase 7 | } from './PaywithFlutterwaveBase'; 8 | import FlutterwaveInit, {FlutterwaveInitOptions} from './FlutterwaveInit'; 9 | import {PAYMENT_OPTIONS} from './configs'; 10 | import {PaymentOptionsPropRule} from './utils/CustomPropTypesRules'; 11 | import PayWithFlutterwaveBase from './PaywithFlutterwaveBase'; 12 | 13 | export interface RedirectParams { 14 | status: 'successful' | 'cancelled', 15 | transaction_id?: string; 16 | tx_ref: string; 17 | } 18 | 19 | // create V3 component props 20 | export type PayWithFlutterwaveProps = PayWithFlutterwavePropsBase & { 21 | onRedirect: (data: RedirectParams) => void; 22 | options: Omit; 23 | } 24 | 25 | // create V3 component 26 | const PayWithFlutterwave:React.FC = ({options, ...props}) => { 27 | return ( 28 | 34 | ); 35 | } 36 | 37 | // define component prop types 38 | PayWithFlutterwave.propTypes = { 39 | ...PayWithFlutterwavePropTypesBase, 40 | // @ts-ignore 41 | options: PropTypes.shape({ 42 | ...OptionsPropTypeBase, 43 | authorization: PropTypes.string.isRequired, 44 | tx_ref: PropTypes.string.isRequired, 45 | payment_options: PaymentOptionsPropRule(PAYMENT_OPTIONS), 46 | customer: PropTypes.shape({ 47 | name: PropTypes.string, 48 | phonenumber: PropTypes.string, 49 | email: PropTypes.string.isRequired, 50 | }).isRequired, 51 | meta: PropTypes.object, 52 | customizations: PropTypes.shape({ 53 | title: PropTypes.string, 54 | logo: PropTypes.string, 55 | description: PropTypes.string, 56 | }), 57 | }).isRequired, 58 | }; 59 | // export component as default 60 | export default PayWithFlutterwave; 61 | -------------------------------------------------------------------------------- /src/PayWithFlutterwaveV2.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { 4 | PayWithFlutterwavePropsBase, 5 | OptionsPropTypeBase, 6 | PayWithFlutterwavePropTypesBase 7 | } from './PaywithFlutterwaveBase'; 8 | import FlutterwaveInitV2, {FlutterwaveInitV2Options} from './FlutterwaveInitV2'; 9 | import {PAYMENT_OPTIONS_V2} from './configs'; 10 | import {PaymentOptionsPropRule} from './utils/CustomPropTypesRules'; 11 | import PayWithFlutterwaveBase from './PaywithFlutterwaveBase'; 12 | 13 | export interface RedirectParamsV2 { 14 | cancelled?: 'true' | 'false'; 15 | flwref?: string; 16 | txref: string; 17 | } 18 | 19 | export type PayWithFlutterwaveV2Props = PayWithFlutterwavePropsBase & { 20 | onRedirect: (data: RedirectParamsV2) => void; 21 | options: Omit; 22 | } 23 | 24 | // create V2 component 25 | const PayWithFlutterwaveV2:React.FC = ({options, ...props}) => { 26 | return ( 27 | 33 | ); 34 | } 35 | 36 | // define component prop types 37 | PayWithFlutterwaveV2.propTypes = { 38 | ...PayWithFlutterwavePropTypesBase, 39 | // @ts-ignore 40 | options: PropTypes.shape({ 41 | ...OptionsPropTypeBase, 42 | payment_options: PaymentOptionsPropRule(PAYMENT_OPTIONS_V2), 43 | txref: PropTypes.string.isRequired, 44 | PBFPubKey: PropTypes.string.isRequired, 45 | customer_firstname: PropTypes.string, 46 | customer_lastname: PropTypes.string, 47 | customer_email: PropTypes.string.isRequired, 48 | customer_phone: PropTypes.string, 49 | country: PropTypes.string, 50 | pay_button_text: PropTypes.string, 51 | custom_title: PropTypes.string, 52 | custom_description: PropTypes.string, 53 | custom_logo: PropTypes.string, 54 | meta: PropTypes.arrayOf(PropTypes.shape({ 55 | metaname: PropTypes.string, 56 | metavalue: PropTypes.string, 57 | })), 58 | }).isRequired, 59 | }; 60 | // export component as default 61 | export default PayWithFlutterwaveV2; 62 | -------------------------------------------------------------------------------- /src/PaywithFlutterwaveBase.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import FlutterwaveInitError from './utils/FlutterwaveInitError'; 4 | import FlutterwaveCheckout from './FlutterwaveCheckout'; 5 | import FlutterwaveButton from './FlutterwaveButton'; 6 | import {REDIRECT_URL} from './configs'; 7 | import { StyleProp, ViewStyle } from 'react-native'; 8 | 9 | export interface CustomButtonProps { 10 | disabled: boolean; 11 | onPress: () => void; 12 | } 13 | 14 | export interface PayWithFlutterwavePropsBase { 15 | style?: StyleProp; 16 | onRedirect: (data: any) => void; 17 | onWillInitialize?: () => void; 18 | onDidInitialize?: () => void; 19 | onInitializeError?: (error: FlutterwaveInitError) => void; 20 | onAbort?: () => void; 21 | customButton?: (params: CustomButtonProps) => React.ReactNode; 22 | alignLeft?: 'alignLeft' | boolean; 23 | meta?: Array; 24 | currency?: string; 25 | } 26 | 27 | export const PayWithFlutterwavePropTypesBase = { 28 | alignLeft: PropTypes.bool, 29 | onAbort: PropTypes.func, 30 | onRedirect: PropTypes.func.isRequired, 31 | onWillInitialize: PropTypes.func, 32 | onDidInitialize: PropTypes.func, 33 | onInitializeError: PropTypes.func, 34 | customButton: PropTypes.func, 35 | }; 36 | 37 | export const OptionsPropTypeBase = { 38 | amount: PropTypes.number.isRequired, 39 | currency: PropTypes.oneOf([ 40 | 'AUD', 41 | 'BIF', 42 | 'CDF', 43 | 'CAD', 44 | 'CVE', 45 | 'EUR', 46 | 'GBP', 47 | 'GHS', 48 | 'GMD', 49 | 'GNF', 50 | 'KES', 51 | 'LRD', 52 | 'MWK', 53 | 'MZN', 54 | 'NGN', 55 | 'RWF', 56 | 'SLL', 57 | 'STD', 58 | 'TZS', 59 | 'UGX', 60 | 'USD', 61 | 'XAF', 62 | 'XOF', 63 | 'ZAR', 64 | 'ZMK', 65 | 'ZMW', 66 | 'ZWD' 67 | ]), 68 | payment_plan: PropTypes.number, 69 | subaccounts: PropTypes.arrayOf(PropTypes.shape({ 70 | id: PropTypes.string.isRequired, 71 | transaction_split_ratio: PropTypes.number, 72 | transaction_charge_type: PropTypes.string, 73 | transaction_charge: PropTypes.number, 74 | })), 75 | integrity_hash: PropTypes.string, 76 | }; 77 | 78 | interface PayWithFlutterwaveState { 79 | link: string | null; 80 | isPending: boolean; 81 | showDialog: boolean; 82 | reference: string | null; 83 | resetLink: boolean; 84 | } 85 | 86 | export type PayWithFlutterwaveBaseProps = PayWithFlutterwavePropsBase & { 87 | options: any; 88 | init: (options: any, abortController?: AbortController) => Promise; 89 | reference: string; 90 | }; 91 | 92 | class PayWithFlutterwaveBase

extends React.Component< 93 | PayWithFlutterwaveBaseProps & P, 94 | PayWithFlutterwaveState 95 | > { 96 | 97 | state: PayWithFlutterwaveState = { 98 | isPending: false, 99 | link: null, 100 | resetLink: false, 101 | showDialog: false, 102 | reference: null, 103 | }; 104 | 105 | abortController?: AbortController; 106 | 107 | timeout: any; 108 | 109 | handleInitCall?: () => Promise; 110 | 111 | componentDidUpdate(prevProps: PayWithFlutterwaveBaseProps) { 112 | const prevOptions = JSON.stringify(prevProps.options); 113 | const options = JSON.stringify(this.props.options); 114 | if (prevOptions !== options) { 115 | this.handleOptionsChanged() 116 | } 117 | } 118 | 119 | componentWillUnmount() { 120 | if (this.abortController) { 121 | this.abortController.abort(); 122 | } 123 | } 124 | 125 | reset = () => { 126 | if (this.abortController) { 127 | this.abortController.abort(); 128 | } 129 | // reset the necessaries 130 | this.setState(({resetLink, link}) => ({ 131 | isPending: false, 132 | link: resetLink ? null : link, 133 | resetLink: false, 134 | showDialog: false, 135 | })); 136 | }; 137 | 138 | handleOptionsChanged = () => { 139 | const {showDialog, link} = this.state; 140 | if (!link) { 141 | return; 142 | } 143 | if (!showDialog) { 144 | return this.setState({ 145 | link: null, 146 | reference: null, 147 | }) 148 | } 149 | this.setState({resetLink: true}) 150 | } 151 | 152 | handleAbort = () => { 153 | const {onAbort} = this.props; 154 | if (onAbort) { 155 | onAbort(); 156 | } 157 | this.reset(); 158 | } 159 | 160 | handleRedirect = (params: any) => { 161 | const {onRedirect} = this.props; 162 | // reset payment link 163 | this.setState( 164 | ({resetLink, reference}) => ({ 165 | reference: params.flwref || params.status === 'successful' ? null : reference, 166 | resetLink: params.flwref || params.status === 'successful' ? true : resetLink, 167 | showDialog: false, 168 | }), 169 | () => { 170 | onRedirect(params) 171 | this.reset(); 172 | } 173 | ); 174 | } 175 | 176 | handleInit = async () => { 177 | const { 178 | options, 179 | onWillInitialize, 180 | onInitializeError, 181 | onDidInitialize, 182 | init, 183 | } = this.props; 184 | const {isPending, reference, link} = this.state; 185 | // just show the dialod if the link is already set 186 | if (link) { 187 | return this.setState({showDialog: true}); 188 | } 189 | // throw error if transaction reference has not changed 190 | if (reference === this.props.reference) { 191 | // fire oninitialize error handler if available 192 | if (onInitializeError) { 193 | onInitializeError(new FlutterwaveInitError({ 194 | message: 'Please generate a new transaction reference.', 195 | code: 'SAME_TXREF', 196 | })) 197 | } 198 | return; 199 | } 200 | // stop if currently in pending mode 201 | if (isPending) { 202 | return; 203 | } 204 | // initialize abort controller if not set 205 | this.abortController = new AbortController; 206 | // fire will initialize handler if available 207 | if (onWillInitialize) { 208 | onWillInitialize(); 209 | } 210 | this.setState({ 211 | isPending: true, 212 | link: null, 213 | reference: this.props.reference, 214 | showDialog: false, 215 | }, async () => { 216 | // handle init 217 | try { 218 | // initialize payment 219 | const paymentLink = await init( 220 | {...options, redirect_url: REDIRECT_URL}, 221 | this.abortController 222 | ); 223 | // set payment link 224 | this.setState({ 225 | link: paymentLink, 226 | isPending: false, 227 | showDialog: true, 228 | }, () => { 229 | // fire did initialize handler if available 230 | if (onDidInitialize) { 231 | onDidInitialize(); 232 | } 233 | }); 234 | } catch (error) { 235 | // stop if request was canceled 236 | if (error && /aborterror/i.test(error.code)) { 237 | return; 238 | } 239 | // call onInitializeError handler if an error occured 240 | if (onInitializeError) { 241 | onInitializeError(error); 242 | } 243 | // set payment link to reset 244 | this.setState({ 245 | resetLink: true, 246 | reference: null, 247 | }, this.reset); 248 | } 249 | }) 250 | }; 251 | 252 | render() { 253 | const {link, showDialog} = this.state; 254 | return ( 255 | <> 256 | {this.renderButton()} 257 | 263 | 264 | ); 265 | } 266 | 267 | renderButton() { 268 | const {alignLeft, customButton, children, style} = this.props; 269 | const {isPending} = this.state; 270 | if (customButton) { 271 | return customButton({ 272 | disabled: isPending, 273 | onPress: this.handleInit 274 | }); 275 | } 276 | return ; 283 | } 284 | } 285 | 286 | export default PayWithFlutterwaveBase; 287 | -------------------------------------------------------------------------------- /src/assets/loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/src/assets/loader.gif -------------------------------------------------------------------------------- /src/assets/pry-button-content.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterwave/React-Native/27336a21c3db9c6ceea07410197cc40ea8682e62/src/assets/pry-button-content.png -------------------------------------------------------------------------------- /src/configs.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * V# API Standard initialization endpoint 3 | */ 4 | export const STANDARD_URL = 'https://api.flutterwave.com/v3/sdkcheckout/payments'; 5 | 6 | /** 7 | * Redirect URL used in V3 FlutterwaveButton 8 | */ 9 | export const REDIRECT_URL = 'https://flutterwave.com/rn-redirect'; 10 | 11 | /** 12 | * Fluttereave volors 13 | */ 14 | export const colors = { 15 | primary: '#f5a623', 16 | primaryLight: '#f9ce85', 17 | secondary: '#12122C', 18 | transparent: 'rgba(0,0,0,0)', 19 | }; 20 | 21 | /** 22 | * Payment options available in V3 23 | */ 24 | export const PAYMENT_OPTIONS = [ 25 | 'account', 26 | 'card', 27 | 'banktransfer', 28 | 'mpesa', 29 | 'mobilemoneyrwanda', 30 | 'mobilemoneyzambia', 31 | 'qr', 32 | 'mobilemoneyuganda', 33 | 'ussd', 34 | 'credit', 35 | 'barter', 36 | 'mobilemoneyghana', 37 | 'payattitude', 38 | 'mobilemoneyfranco', 39 | 'paga', 40 | '1voucher', 41 | 'mobilemoneytanzania', 42 | ]; 43 | 44 | /** 45 | * V2 API standard initialization endpoint 46 | */ 47 | export const STANDARD_URL_V2: string = 48 | 'https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/hosted/pay'; 49 | 50 | /** 51 | * Payment options available in V2 API 52 | */ 53 | export const PAYMENT_OPTIONS_V2 = [ 54 | 'card', 55 | 'account', 56 | 'ussd', 57 | 'qr', 58 | 'mpesa', 59 | 'mobilemoneyghana', 60 | 'mobilemoneyuganda', 61 | 'mobilemoneyrwanda', 62 | 'mobilemoneyzambia', 63 | 'mobilemoneytanzania', 64 | 'barter', 65 | 'bank transfer', 66 | 'wechat', 67 | ]; 68 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import FlutterwaveInit from './FlutterwaveInit'; 2 | import FlutterwaveInitV2 from './FlutterwaveInitV2'; 3 | import PayWithFlutterwave from './PayWithFlutterwave'; 4 | import PayWithFlutterwaveV2 from './PayWithFlutterwaveV2'; 5 | import FlutterwaveButton from './FlutterwaveButton'; 6 | import FlutterwaveCheckout from './FlutterwaveCheckout'; 7 | 8 | // export modules 9 | export { 10 | FlutterwaveInit, 11 | PayWithFlutterwave, 12 | FlutterwaveInitV2, 13 | PayWithFlutterwaveV2, 14 | FlutterwaveButton, 15 | FlutterwaveCheckout, 16 | }; 17 | 18 | // export v3 PayWithFlutterwave as default 19 | export default PayWithFlutterwave; 20 | -------------------------------------------------------------------------------- /src/utils/CustomPropTypesRules.ts: -------------------------------------------------------------------------------- 1 | export const PaymentOptionsPropRule = (options: Array) => (props:{[k: string]: any}, propName: string) => { 2 | // skip check if payment options is not defined 3 | if (props[propName] === undefined) { 4 | return null; 5 | } 6 | // if not an array of payment options 7 | if (typeof props[propName] !== 'string') { 8 | return new Error( 9 | '"payment_methods" should be a string.', 10 | ); 11 | } 12 | const paymentOptionsList = props[propName].split(','); 13 | for (let i = 0; i < paymentOptionsList.length; i++) { 14 | if ( 15 | options.findIndex( 16 | (j) => j.trim() === paymentOptionsList[i].trim(), 17 | ) === -1 18 | ) { 19 | return new Error( 20 | `"payment_options"(${ 21 | props[propName] 22 | }) must be any of the following values.\n${options.map( 23 | (i, n) => `${n + 1}. ${i}\n`, 24 | ).join('')}`, 25 | ); 26 | } 27 | } 28 | return null; 29 | } 30 | -------------------------------------------------------------------------------- /src/utils/FlutterwaveInitError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Flutterwave Init Error 3 | */ 4 | export default class FlutterwaveInitError extends Error { 5 | /** 6 | * Error code 7 | * @var string 8 | */ 9 | code: string; 10 | 11 | /** 12 | * Error code 13 | * @var string 14 | */ 15 | errorId?: string; 16 | 17 | /** 18 | * Error code 19 | * @var string 20 | */ 21 | errors?: Array; 22 | 23 | /** 24 | * Constructor Method 25 | * @param props {message?: string; code?: string} 26 | */ 27 | constructor(props: {message: string; code: string, errorId?: string, errors?: Array}) { 28 | super(props.message); 29 | this.code = props.code; 30 | this.errorId = props.errorId; 31 | this.errors = props.errors; 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/utils/ResponseParser.ts: -------------------------------------------------------------------------------- 1 | import {ResponseData} from "../FlutterwaveInit"; 2 | import FlutterwaveInitError from "./FlutterwaveInitError"; 3 | 4 | /** 5 | * The purpose of this function is to parse the response message gotten from a 6 | * payment initialization error. 7 | * @param message string 8 | * @param code string (optional) 9 | * @returns {message: string; code: string} 10 | */ 11 | export default function ResponseParser( 12 | { 13 | status, 14 | errors, 15 | message, 16 | data, 17 | code, 18 | error_id, 19 | }: ResponseData 20 | ): Promise { 21 | return new Promise((resolve, reject) => { 22 | // return success message 23 | if (status === 'success') { 24 | // check if data or data link is missing 25 | if (!data || !data.link) { 26 | return reject(new FlutterwaveInitError({ 27 | code: 'MALFORMED_RESPONSE', 28 | message, 29 | })) 30 | } 31 | // return the payment link 32 | return resolve(data.link); 33 | } 34 | // missing authorization 35 | if (/authorization/i.test(message) && /required/i.test(message)) { 36 | reject( 37 | new FlutterwaveInitError({ 38 | code: 'AUTH_MISSING', 39 | message, 40 | }) 41 | ); 42 | } 43 | // invalid authorization 44 | if (/authorization/i.test(message) && /invalid/i.test(message)) { 45 | reject(new FlutterwaveInitError({ 46 | code: 'AUTH_INVALID', 47 | message, 48 | })); 49 | } 50 | // field errors 51 | if (errors) { 52 | reject(new FlutterwaveInitError({ 53 | code: 'INVALID_OPTIONS', 54 | message: message, 55 | errors: errors.map(i => i.message), 56 | })); 57 | } 58 | // defaults to the initially passed message 59 | reject(new FlutterwaveInitError({ 60 | code: String(code || 'STANDARD_INIT_ERROR').toUpperCase(), 61 | message, 62 | errorId: error_id 63 | })); 64 | }) 65 | } 66 | -------------------------------------------------------------------------------- /timeTravel.js: -------------------------------------------------------------------------------- 1 | const MockDate = require('mockdate'); 2 | export const FRAME_TIME = 1; 3 | 4 | const advanceOneFrame = () => { 5 | MockDate.set(new Date(Date.now() + FRAME_TIME)) 6 | jest.advanceTimersByTime(FRAME_TIME) 7 | } 8 | 9 | // global time travel mock for mocking "RN Animated" fram steps; 10 | const timeTravel = (msToAdvance = FRAME_TIME) => { 11 | const numberOfFramesToRun = msToAdvance / FRAME_TIME 12 | let framesElapsed = 0 13 | 14 | // Step through each of the frames until we've ran them all 15 | while (framesElapsed < numberOfFramesToRun) { 16 | advanceOneFrame() 17 | framesElapsed++ 18 | } 19 | } 20 | 21 | export const setupTimeTravel = () => { 22 | MockDate.set(0) 23 | jest.useFakeTimers() 24 | } 25 | 26 | export default timeTravel 27 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src/*", "src/utils/CustomPropTypesRules.ts"], 3 | "exclude": [ 4 | "node_modules", 5 | "babel.config.js", 6 | "metro.config.js", 7 | "jest.config.js" 8 | ], 9 | "compilerOptions": { 10 | "baseUrl": "./src/", 11 | "jsx": "react-native", 12 | "module": "esnext", 13 | "moduleResolution": "node", 14 | "lib": ["es2017"], 15 | "declaration": true, 16 | "declarationMap": true, 17 | "outDir": "dist", 18 | "allowSyntheticDefaultImports": true, 19 | "esModuleInterop": true, 20 | "forceConsistentCasingInFileNames": true, 21 | "noFallthroughCasesInSwitch": true, 22 | "noImplicitReturns": true, 23 | "noUnusedLocals": true, 24 | "noUnusedParameters": true, 25 | "pretty": true, 26 | "resolveJsonModule": true, 27 | "skipLibCheck": true, 28 | "strict": true 29 | } 30 | } 31 | --------------------------------------------------------------------------------