Sending the stripe token to rest API using fetch in react native

Introducation –

This post is a third part of integrating stripe payment gateway with react native, here i am going to in detail about “Sending the stripe token to rest API using fetch in react native“, if you didn’t create the stripe developer account and you don’t able to get the stripe token then please follow below blogs first.

Step 1 – creating stripe developer account.

Step 2 – getting stripe token.

Output Example –

Sending the stripe token to rest API using fetch in react native

Why we send stripe token to backend –

We need to send the stripe token to our web services(rest api’s), so our backend able to verify that token is valid or not and give the success or failure response.

In step 1 we get the stripe token, here when we click on make payment button then we call the rest API with token and amount.

Step 1 – Provide the definition of makePayment().

 makePayment = async () => {
  var apiUrl = 'https://api       
    c97a7.cloudfunctions.net/payWithStripe'
    this.setState({loading: true});
    fetch(apiUrl, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        amount: 100,
        currency: 'usd',
        token: this.state.token,
      }),
    })
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
        this.setState({loading: false});
      })
      .catch((error) => {
        console.error(error);
        this.setState({loading: false});
      });
  };

in makePayment() function, you need to set your url of API and work is done.

Step 2 – Complete App.js code

here you get the all code from step 1, step2 and step3 as well.

import React, {PureComponent} from 'react';
import {StyleSheet, View, Text} from 'react-native';
import Button from './components/Button';
import stripe from 'tipsi-stripe';

stripe.setOptions({
  publishableKey:
    'pk_test_51HSepBAAcuGAEoJYv2ddt-----------Cq0DWkkX5Qoavjnmn2eUQbufIwUKMNyYoVNidkt8bOJvaHc00ZFqRao4k',
});

export default class CardFormScreen extends PureComponent {
  static title = 'Card Form';
  state = {
    loading: false,
    token: null,
  };

  handleCardPayPress = async () => {
    try {
      this.setState({loading: true, token: null});
      const token = await stripe.paymentRequestWithCardForm({
        // Only iOS support this options
        smsAutofillDisabled: true,
        requiredBillingAddressFields: 'full',
        prefilledInformation: {
          billingAddress: {
            name: ' App',
            line1: 'Canary Place',
            line2: '3',
            city: 'Macon',
            state: 'Georgia',
            country: 'US',
            postalCode: '31217',
            email: 'app@mailnator.com',
          },
        },
      });
     this.setState({loading: false, token});
    } catch (error) {
      this.setState({loading: false});
    }
  };

 makePayment = async () => {
  var apiUrl = 'https://api       
    c97a7.cloudfunctions.net/payWithStripe'
    this.setState({loading: true});
    fetch(apiUrl, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        amount: 100,
        currency: 'usd',
        token: this.state.token,
      }),
    })
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
        this.setState({loading: false});
      })
      .catch((error) => {
        console.error(error);
        this.setState({loading: false});
      });
  };

  render() {
    const {loading, token} = this.state;

    return (
      <View style={styles.container}>
        <Text style={styles.header}>Card Form Example</Text>
        <Text style={styles.instruction}>
          Click button to show Card Form dialog.
        </Text>
        <Button
          text="Enter you card and pay"
          loading={loading}
          onPress={this.handleCardPayPress}
        />
        <View style={styles.token}>
          {token && (
            <View>
              <Text style={styles.instruction}>Token: {token.tokenId}. 
            </Text>
              <Button
                text="Make Payment"
                loading={loading}
                onPress={this.makePayment}></Button>
            </View>
          )}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  header: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instruction: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  token: {
    height: 20,
  },
});

So we completed the step 4(final step) which is “Sending the stripe token to rest API using fetch in react native” part of “How to integrate stripe payment gateway in react native“.

You can find my post on medium as well click here please follow me on medium as well.

You can find previous step of this post  here.

for more detail – https://tipsi.github.io/tipsi-stripe/docs/paymentrequestwithcardform.html

If have any query/issue, please feel free to ask.

Happy Coding Guys.


Related Post