Vaibhav Herugu
Vaibhav Herugu

Reputation: 1102

Not connecting to Stripe API

I am coding a stripe React Native gateway and I was coding stripe connections to the API. I used the API in connecting to Stripe but it says that I am not connected to the API. This is mainly in two files: ShopScreen.js and index.js.

Here is ShopScreen.js:

import {PureComponent} from 'react';
import stripe from 'tipsi-stripe';
import Button from '../components/components/Button';
import {
  ActivityIndicator,
  TouchableOpacity,
  TextInput,
  Image,
  ImageBackground,
} from 'react-native';
import * as React from 'react';
import axios from 'axios';
import {WebView} from 'react-native-webview';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  FlatList,
} from 'react-native';
stripe.setOptions({
  publisherKey: 'pk_test_HWcOeGStIfoP98VZkHRIJUmO00E1eZyuQG',
});

class ShopScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      search: '',
      data: [],
    };
  }
  handleSearch = (text) => {
    this.setState({search: text});
  };

  componentDidMount() {
    axios
      .get('http://localhost:3000')
      .then((response) => {
        this.setState({
          data: response.data,
        });
      })
      .catch(function (err) {
        alert(err);
      });
  }

  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: 'Vaibhav Herugu',
            line1: '2 Darryl Drive',
            line2: '',
            city: 'Morganville',
            state: 'NJ',
            country: 'USA',
            postalCode: '07751',
            email: '[email protected]',
          },
        },
      });

      this.setState({loading: false, token: token});
    } catch (error) {
      this.setState({loading: false});
    }
  };

  makePayment = async () => {
    this.setState({loading: true});
    axios({
      method: 'POST',
      url:
        'https://us-central1-localmainstreet-b0144.cloudfunctions.net/completePaymentWithStripe',
      data: {
        amount: 0,
        currency: 'usd',
        token: this.state.token,
      },
    }).then((response) => {
      console.log(response);
      this.setState({loading: false});
    });
  };

  render() {
    const {loading, token} = this.state;
    console.log('##data', this.state.data);
    const Item = ({user}) => {
      console.log('##item', user);
      return (
        <View>
          <View style={styles.viewforFlatList}>
            <View style={styles.viewforButton}>
              <Text style={styles.businessNameStyle}>{user.item.bname}</Text>
              <View style={styles.container}>
                <Button
                  style={styles.buttons1}
                  text="Buy Now"
                  loading={loading}
                  onPress={this.handleCardPayPress}
                />
                <View style={styles.token}>
                  {token && (
                    <>
                      <Text style={styles.instruction}>
                        Token: {this.state.token}
                      </Text>
                      {this.makePayment}
                    </>
                  )}
                </View>
              </View>
            </View>
          </View>
          <Text style={styles.businessDescandEmailStyle}>
            {user.item.bdesc}
          </Text>
          <Text style={styles.businessDescandEmailStyle}>
            Email: {user.item.email}
          </Text>
          <Text style={styles.phoneNumberStyle}>
            Phone Number: {user.item.phonenum}
          </Text>
        </View>
      );
    };

    const {navigate} = this.props.navigation;
    return (
      <View style={styles.viewForSearch}>
        <StatusBar barStyle="dark-content" />
        <View style={styles.viewforButton}>
          <TextInput
            style={styles.input2}
            underlineColorAndroid="transparent"
            placeholder="Business Category/Name"
            placeholderTextColor="#000000"
            autoCapitalize="none"
            onChangeText={this.handleSearch}
          />
          <TouchableOpacity style={styles.buttons}>
            <Text style={styles.buttonText}>Search</Text>
          </TouchableOpacity>
        </View>
        <TouchableOpacity
          style={styles.buttonsUnderLogin}
          onPress={() => {
            navigate('Help');
          }}>
          <Text style={styles.buttonTextForSignUp}>Help</Text>
        </TouchableOpacity>
        {/* <WebView
        source={{ uri: 'https://reactnative.dev' }}
        style={{ marginTop: 20 }}
      />   */}
        <View style={styles.FlatList}>
          <FlatList
            data={this.state.data}
            renderItem={(user) => <Item user={user} />}
            keyExtractor={(user) => user.id}
          />
        </View>
      </View>
    );
  }
}

export default ShopScreen;

(styles not shown for ShopScreen.js)

and here is index.js:

const functions = require('firebase-functions');
const stripe = require('stripe')('SECRET-KEY');

exports.completePaymentWithStripe = functions.https.onRequest(
  (request, response) => {
    stripe.charges
      .create({
        amount: request.body.amount,
        currency: request.body.currency,
        source: 'tok_mastercard',
      })
      .then((charge) => {
        response.send(charge);
        return charge;
      })
      .catch((error) => {
        console.log(error);
      });
  },
);

(where it says SECRET-KEY I added my secret key)

This is supposed to connect to Stripe and process my payment. Instead, it shows,

I went to the docs and tried using what it said to use, but it didn't work, so I deleted it.

This is my problem. Thanks.

Upvotes: 2

Views: 456

Answers (1)

Bhuwan Chandra
Bhuwan Chandra

Reputation: 315

hey the issue is that you haven't added the token with your request

exports.completePaymentWithStripe = functions.https.onRequest(
      (request, response) => {
    stripe.customers.create(req.body.token).then(customer => {
        stripe.charges
          .create({
            amount: request.body.amount,
            currency: request.body.currency,
            source: 'tok_mastercard',
            customer: customer.id
          })
         })
          .then((charge) => {
            response.send(charge);
            return charge;
          })
          .catch((error) => {
            console.log(error);
          });
      },
    );

Upvotes: 1

Related Questions