如何在 React Native 中使用 Stripe 进行支付?

问题描述

我正在创建一个 React Native 应用程序,我需要使用 Stripe 进行付款。有没有办法在使用或不使用任何第三方库的情况下做到这一点? 我可以通过使用以下代码片段访问条带 API 来创建具有 fetch 方法的令牌。

代码片段

    var cardDetails = {
              'card[number]': this.state.cardData.values.number.replace(/ /g,''),'card[exp_month]': this.state.cardData.values.expiry.split('/')[0],'card[exp_year]': this.state.cardData.values.expiry.split('/')[1],'card[cvc]': this.state.cardData.values.cvc
            };
         
            var formBody = [];
            for(var property in cardDetails){
                var encodedKey = encodeURIComponent(property);
                var encodedValue = encodeURIComponent(cardDetails[property]);
                formBody.push(encodedKey + "=" + encodedValue);
            }
            formBody = formBody.join("&");

            fetch('https://api.stripe.com/v1/tokens',{
                method: 'POST',headers: {
                    'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded','Authorization': 'Bearer '+ STRIPE_PUBLISHABLE_KEY
                 },body: formBody
            })
            .then(responseJson => {
                responseJson.json().then(solved=>{
                    cardToken =solved.id;
})

这是我试过的。

这里我使用 react-native-credit-card-input 库来获取信用卡详细信息。我是本机反应的新手。我不知道在这之后如何实现代码。我可以通过使用上面的代码片段访问“https://api.stripe.com/v1/tokens”这个 URL 来从条带中获取令牌。但是当我要使用该令牌创建费用时,它会给我一个错误(“https://api.stripe.com/v1/charges”)。使用 react-native 创建条带支付的正确流程是什么?

import React,{Component} from 'react';
import {
  View,Text,TouchableOpacity,TextInput,Platform,StyleSheet,StatusBar,Alert,Image,ScrollView,Animated,Dimensions,Modal,} from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Feather from 'react-native-vector-icons/Feather';

import {
    CreditCardInput,LiteCreditCardInput,} from 'react-native-credit-card-input';

class stripePay extends Component {

    constructor(props) {
        super(props);
        this.state = { cardData: { valid: false },tokenCRD:'' };
      }
  
  ContFunction = () => {
    this.getCreditCardToken();
  };

    getCreditCardToken = () => {

        var cardToken;
        var STRIPE_PUBLISHABLE_KEY = 'pk_test_*****************';
        var STRIPE_SECRET_KEY ='sk_test_*************************';

         var cardDetails = {
              'card[number]': this.state.cardData.values.number.replace(/ /g,'card[cvc]': this.state.cardData.values.cvc
            };
          var amount= 1*100;
              
            var formBody = [];
            for(var property in cardDetails){
                var encodedKey = encodeURIComponent(property);
                var encodedValue = encodeURIComponent(cardDetails[property]);
                formBody.push(encodedKey + "=" + encodedValue);
            }
            formBody = formBody.join("&");

            fetch('https://api.stripe.com/v1/tokens',body: formBody
            })
            .then(responseJson => {
                // console.log(responseJson);
                responseJson.json().then(solved=>{
                    cardToken =solved.id;
                    // console.log(cardToken);
                    
                    var paymentbody = {
                      amount: amount,currency: 'usd',description: 'Example charge',source: cardToken,//source: "tok_visa",}

                    if(cardToken!=""){
                      //console.log(cardToken);

                      fetch('https://api.stripe.com/v1/charges',{
                          method: 'POST',headers: {
                            'Accept': 'application/json','Authorization': 'Bearer '+ STRIPE_SECRET_KEY
                          },body:paymentbody
                        })
                          .then(response => response.json())
                          .then(responseJson => {
                            console.log(responseJson);
                          })
                          .catch(error => {
                            console.error(error);
                          });

                    }else{
                      console.log("Error")
                    }
                    
                });
            })
            .catch(error => {
                console.error(error);
            });      
    }

  render() {
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="#009387" barStyle="light-content" />
        <View style={styles.header}>
          <Text style={styles.text_header}>Testing Stripe Payment!</Text>
        </View>
        <View style={[styles.footer]}>

        <View style={styles.cardContainer}>
              <CreditCardInput
                autoFocus
                requiresName
                requiresCVC
                requiresPostalCode

                labelStyle={styles.label}
                inputStyle={styles.input}
                validColor={'black'}
                invalidColor={'red'}
                placeholderColor={'darkgray'}
                onFocus={this._onFocus}
                // onChange={this._onChange}
                onChange={(cardData) => this.setState({ cardData })}
              />
            </View>

            <View style={styles.button1}>
              <TouchableOpacity
                style={styles.btnCon}
                onPress={() => this.ContFunction()}>
                <View
                  style={styles.btnCon}>
                  <Text style={[styles.textCon]}>Pay Now</Text>
                </View>
              </TouchableOpacity>
            </View>
          
        </View>
      </View>
    );
  }
}

export default stripePay;

const styles = StyleSheet.create({
  container: {
    flex: 1,backgroundColor: '#009387',},header: {
    flex: 1,justifyContent: 'flex-end',paddingHorizontal: 20,paddingBottom: 30,text_header: {
    color: '#fff',fontWeight: 'bold',fontSize: 30,footer: {
    flex: 3,backgroundColor: '#fff',borderTopLefTradius: 30,borderTopRighTradius: 30,paddingVertical: 30,cardContainer: {
    backgroundColor: '#fff',marginTop: 60,label: {
    color: 'black',fontSize: 12,input: {
    fontSize: 16,color: 'black',button1: {
    alignItems: 'center',marginTop: 40,// width:'80%',btnCon: {
    width: '80%',height: 50,justifyContent: 'center',alignItems: 'center',borderRadius: 10,backgroundColor: '#00b530',textCon: {
    fontSize: 18,color: 'white',});

我收到以下错误

Error

解决方法

所有条带支付都可以使用 fetch 通过 api 处理,因此无需使用第三方库。

您需要创建一个客户,将卡添加到客户,然后创建付款,创建一次性使用的卡令牌并使用卡令牌确认付款。

付款验证通过响应链接处理,该链接应该在浏览器中打开,用户可以在其中手动确认付款。在这种情况下,请使用 PaymentIntents api。