import React, { Fragment, useRef, useState } from 'react'; import { ActivityIndicator, Platform, StyleSheet, Text, View, } from 'react-native'; import { WebView, type WebViewMessageEvent } from 'react-native-webview'; import { serverSdkBaseUrl } from '../../lib/config'; type OmnipayProps = { color: string; env: 'dev' | 'prod'; publicKey: string; phoneNumber?: string; customerRef?: string; userRef?: string; amount: number; sessionId: string; orderId: string; onClose?: () => void; onPaymentLinkingSuccessful?: () => void; }; type Status = 'error' | 'loading' | 'success'; export const PaymentLinking = ({ color, env, publicKey, phoneNumber, customerRef, userRef, amount, sessionId, orderId, onClose, onPaymentLinkingSuccessful, }: OmnipayProps): JSX.Element => { const webviewRef = useRef(null); const [webviewStatus, setWebviewStatus] = useState('loading'); const webHost = getWebHost(); const webUrl = getWebUrl(); const onWebviewMount = ` window.nativeOs = ${Platform.OS}; true; `; function getWebHost() { return serverSdkBaseUrl[env]; } function getWebUrl() { const themeColor = color.includes('#') ? color.split('#')[1] : color; return `${webHost}order/create?theme=${themeColor}&publicKey=${publicKey}&phoneNumber=${ phoneNumber || '' }&customerRef=${customerRef || ''}&amountPending=${amount}&sessionId=${ sessionId || '' }&orderId=${orderId || ''}&userRef=${userRef || ''}`; } async function onWebviewMessage(e: WebViewMessageEvent) { try { if (e.nativeEvent && e.nativeEvent.data) { const eventData = JSON.parse(e.nativeEvent.data); const { dataKey } = eventData; if (dataKey === 'payment.linked') { if (onPaymentLinkingSuccessful) { onPaymentLinkingSuccessful(); } return; } if (dataKey === 'close.payment') { if (onClose) { onClose(); } return; } } } catch (error) {} } if (!publicKey.includes('OMNIPUBKEY_')) { return Invalid public key; } if (color.length < 3) { return Invalid color; } if (!['dev', 'prod'].includes(env)) { return Invalid environment; } if (!customerRef && !userRef) { if (!phoneNumber) { return Phone number is required; } if (phoneNumber?.length < 10) { return Invalid phone number; } } if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) { return Amount is required and should be greater than 0; } return ( setWebviewStatus('success')} /> {webviewStatus === 'loading' && ( )} ); }; const styles = StyleSheet.create({ hide: { display: 'none', }, full: { flex: 1, width: '100%', height: '100%', }, webview: { flex: 1, width: '100%', height: '100%', }, webviewLoader: { zIndex: 3, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center', flex: 1, width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, }, });