ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Sunday, December 11, 2022

[FIXED] How do you implement payments in React Native 0.70?

 December 11, 2022     payment, react-native, reactjs, stripe-payments, typescript   

Issue

How do you implement payments in React Native 0.70. I worked with earlier React Native versions using react-native-credit-card-input and react-native-credit-card-input-plus that are now breaking.


Solution

Now it very easy to implement the payment methods in react-native because stripe provide official doc.

They provide a built-in UI for checkout and Card Tokenisation, Here you can Follow Official Doc

1) Setup

install stripe official react-native sdk

yarn add @stripe/stripe-react-native

To initialise Stripe in your React Native app, either wrap your payment screen with the StripeProvider component, or use the initStripe initialisation method.

<StripeProvider publishableKey={PUBLISHABLE_KEY}>
    <Navigation />
 </StripeProvider>

How to get PUBLISHABLE_KEY

Now in your component

Either use the Stripe UI or create your own custom UI for getting card details. In this answer, I'm using rn-credit-card for getting a card, which gives me customization options 🙂.

2) Get Card details, create Card Token and save for future use

import CreditCardForm, { FormModel } from "rn-credit-card";

const handleConfirm = (model: FormModel) => {
   axios
  .post(
    "https://api.stripe.com/v1/tokens",
    {
      "card[name]": model.holderName,
      "card[number]": model.cardNumber,
      "card[exp_month]": model.expiration.split("/")[0],
      "card[exp_year]": model.expiration.split("/")[1],
      "card[cvc]": model.cvv,
    },
    {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: `Bearer ${STRIPE_KEY}`,
      },
    }
  )
  .then((res) => {
    if (res?.data?.id) {
        //res?.data?.id It will return the payment method ID sent to your backend
        // You can also save it for future use by saving it in the database.
      console.log(res?.data?.id)
    }
  })
  .catch((err) => {
    Alert.alert("Stripe Error", err.message);
  });

};

For setting defaultValues

const formMethods = useForm<FormModel>({
mode: "onBlur",
defaultValues: {
  holderName: "",
  cardNumber: "",
  expiration: "",
  cvv: "",
},
 });
const { handleSubmit, formState } = formMethods;

Form to get card details

<CreditCardForm
        LottieView={LottieView}
        horizontalStart={false}
        overrides={{
          labelText: {
            marginTop: 16,
          },
        }}
      />
    {formState.isValid && (
      <Button
        style={styles.button}
        title={'CONFIRM PAYMENT'}
        onPress={handleSubmit(handleConfirm)}
      />
    )}

Now When you pay or checkout simple do the following step

3) Checkout or Payment Time

  1. Create a PaymentIntent by passing the paymentMethods Id with other params like reservationId etc
  2. The backend will return you clientSecret and also the calculated bill
  3. Send the clientSecret to stripe
import { useStripe } from "@stripe/stripe-react-native";

  const { confirmPayment } = useStripe();
const handlePay = async () => {
setStripeLoading(true);
try {
//Step 1
  const response = await createPaymentIntent({
    variables: {
      paymentMethodId: paymentMethodId, // That you stored on the backend
      reserveId: id, // In our case reserveId is required 
      amountToDeduct: 23,
    },
  });
  if (response) {
      //Step 2 by getting clientSecret
    const { clientSecret } = response?.createPaymentIntent;
//sending clientSecret to deduct amount
    const { error, paymentIntent } = await confirmPayment(clientSecret);
    if (error) {
      setStripeLoading(false);
      Alert.alert(`Error code: ${error.code}`, error.message);
    }
    if (paymentIntent) {
      setStripeLoading(false);
      // Show Success Alert
    }
  }
} catch (error) {
  setStripeLoading(false);
} finally {
  setStripeLoading(false);
}
};

Tada you done 🥰



Answered By - Naveed Khan
Answer Checked By - - Pedro (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix