Не подключается к Stripe API - PullRequest
2 голосов
/ 04 мая 2020

Я кодирую полосовой шлюз React Native и кодирую полосовые подключения к API. Я использовал API для подключения к Stripe, но он говорит, что я не подключен к API. В основном это два файла: ShopScreen. js и index. js.

Вот 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: 'vherugu@gmail.com',
          },
        },
      });

      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;

(стили не показаны для ShopScreen. js)

и вот индекс. 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);
      });
  },
);

(где написано SECRET-KEY Я добавил свой секретный ключ)

Предполагается, что он подключается к Stripe и обрабатывает мой платеж. Вместо этого он показывает

Я зашел в документы и попытался использовать то, что он сказал, но это не сработало, поэтому я удалил это.

Это моя проблема. Спасибо.

1 Ответ

1 голос
/ 04 мая 2020

проблема в том, что вы не добавили токен в свой запрос

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);
          });
      },
    );
...