;
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 |
--------------------------------------------------------------------------------