【问题标题】:How to do payment with stripe in react native?如何在原生反应中使用条纹付款?
【发布时间】:2021-07-14 13:42:48
【问题描述】:

我正在创建一个 React Native 应用程序,我需要使用 Stripe 进行支付。有没有办法使用或不使用任何第三方库? 我可以通过使用以下代码 sn-p 访问条带 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 库来获取信用卡详细信息。我是反应原生的新手。而且我不知道在此之后如何实现代码。我可以通过使用上面的代码 sn-p 访问“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[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 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', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Bearer '+ STRIPE_PUBLISHABLE_KEY
                 },
                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',
                            'Content-Type': 'application/x-www-form-urlencoded',
                            '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,
    paddingHorizontal: 20,
    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,
    fontWeight: 'bold',
    color: 'white',
  },
});

我收到以下错误。

【问题讨论】:

  • 这个问题有什么解决办法吗?如何使用fetch方法调用stripe API?

标签: react-native stripe-payments react-native-android react-native-stripe-api


【解决方案1】:

所有条带支付都可以通过 api 使用 fetch 处理,因此不需要使用 3rd 方库。

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

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

【讨论】:

  • 非常感谢。你有任何与我的问题相关的代码吗?
  • 很遗憾,由于 shltty postman update 6.xx -> 7.xx,我失去了所有的工作,包括这些请求,但很可能按照这个顺序,stripe.com/docs/api 应该让你继续前进跨度>
  • 好的,非常感谢。我会检查这个文档。
猜你喜欢
  • 2017-05-20
  • 2019-02-25
  • 1970-01-01
  • 2014-10-31
  • 2021-02-23
  • 2015-08-30
  • 2021-10-12
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多