Home > Mobile >  React native firebase handling payment flow
React native firebase handling payment flow

Time:07-02

I am integrating payment api, I'm using firebase cloud functions as my backend and react-native in frontend, so right now i have the following code:

In react-native side:

const PaymentScreen = () => {
  setLoading(true);
  const onPay = () => {
    const onPaymentCall = firebase.functions().httpsCallable('onPayment');
    onPaymentCall(productsData)
    .then(res => {
      setLoading(false);
      if (res?.data?.statusCode === 200) {
        const paymentReceivedData = {
          transactionId: res?.data?.transactionId,
          paymentDate: new Date().now(),
          totalPrice: res?.data?.totalPrice
        }
        navigator.navigate('ReceiptScreen', { paymentReceivedData });
      }
    })
  }
  return (
    <TouchableOpacity onPress={onPay}>PAY</TouchableOpacity>
  )
}

firebase function to handle payment:

export const onPayment = functions
    .runWith({ timeoutSeconds: 300 })
    .https.onCall(async (data: any, context: any) => {
      if (!context.auth) {
            throw new functions.https.HttpsError(
                'failed-precondition',
                'The function must be called while authenticated.'
            );
        }
      try {
        const paymentResult = await paymentThroughApi(data);
        await admin.firestore().collection('wallet').add({...paymentResult});
        const response = {
          statusCode: 200,
          totalPrice: paymentResult.totalPrice,
          transactionId: paymentResult.transactionId,
        }
        return response;
      } catch (error) {
        const response = {
          statusCode: 400,
          message: 'Payment unsuccessful',
          transactionId: null,
        }
        return response;
      }

So the question is, how can I handle long-time response/timeout error/network-loss etc in react-native side, like how should I make it more robust? especially handling long-time responses, timeout errors, payment failures etc? Which packages should I use? like NetInfo to check internet connectivity but what is the best way to make payment flow robust?

So can anyone guide me or suggest any code snippets to add on to my current code?

Thank you!

CodePudding user response:

I don't think there is one definite answer to your question, But here is what I think:

For managing network connection status in React Native you can use NetInfo for information about network connection and Axios to make network requests to a public API as per documentation and for more information check with this Stackoverflow Link.

For timeout errors you can check the Article from Dan Abromov, which states Making setInterval Declarative with React Hooks and with this link

There are different answers for long-time responses in react-native.

  • Related