首页 > 解决方案 > React Native:获取 Stripe API

问题描述

我正在尝试使用fetch()Stripe 的 API 直接从前端使用 React Native 创建支付令牌。

我正在这样做:

  const genCard = {
    'card[number]': "4242424242424242",
    'card[exp_month]': "11",
    'card[exp_year]': "25,
    'card[cvc]': "111"
  }

  var formBody = []
  for (var property in genCard) {
    var encodedKey = encodeURIComponent(property)
    var encodedValue = encodeURIComponent(genCard[property])
    formBody.push(encodedKey + "=" + encodedValue)
  }
  formBody = formBody.join("&")

  const result = fetch("https://api.stripe.com/v1/tokens", {
    method: "post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Bearer " + "sk_test_4eC39HqLyjWDarjtT1zdp7dc",
    },
    body: formBody
  }).then(response => response.json())

  console.log('logging: \n', genCard, '\n', formBody, '\n', result)

日志记录输出为我提供以下信息:

logging: 
 {"card[cvc]": "111", "card[exp_month]": "11", "card[exp_year]": "25", "card[number]": "4242424242424242"} 
 card%5Bnumber%5D=4242424242424242&card%5Bexp_month%5D=11&card%5Bexp_year%5D=25&card%5Bcvc%5D=111 
 {"_40": 0, "_55": null, "_65": 0, "_72": null}

genCard包含 Stripe 所需的所有 CC 数据(number、exp_month、exp_year、cvc),并formBody根据我在网上找到的所有文档和指南格式化 CC 数据。但是,我收到的 API 响应不是预期的付款令牌,而是{"_40": 0, "_55": null, "_65": 0, "_72": null}.

我相信我已经遵循了 Stripe 的文档,但是标题数据不正确或正文数据格式错误。

有人熟悉这个过程吗?我错过了什么?

标签: react-nativefetchstripe-payments

解决方案


对于任何感兴趣的人,以下解决方案都有效:

async function testStripe() {
  const genCard = {
    'card[number]': "4242424242424242",
    'card[exp_month]': "11",
    'card[exp_year]': "25,
    'card[cvc]': "111"
  }

  const results = await fetch("https://api.stripe.com/v1/tokens", {
    method: "post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Bearer " + "sk_test_4eC39HqLyjWDarjtT1zdp7dc",
    },
    body: Object.keys(genCard)
      .map(key => key + '=' + genCard[key])
      .join('&'),
  }).then(response => response.json())

  console.log('\n\n\nlogging: \n', genCard, '\n', 'blank', '\n', results)

  return
}
  1. fetch将你的async函数和await结果包装起来
  2. fetch body必须是成对的key->value卡片数据
  3. 使用您Stripe Publishable Key的身份验证 api 请求

您的 api 响应应如下所示:

{"card": {"address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "brand": "Visa", "country": "US", "cvc_check": "unchecked", "dynamic_last4": null, "exp_month": 11, "exp_year": 2022, "fingerprint": "Xt5EWLLDS7FJjR1c", "funding": "credit", "id": "card_1INjaU2eZvKYlo2C5O5qqIFW", "last4": "4242", "metadata": {}, "name": null, "object": "card", "tokenization_method": null}, "client_ip": "66.42.75.92", "created": 1614020214, "id": "tok_1INjaU2eZvKYlo2CDjL8bde4", "livemode": false, "object": "token", "type": "card", "used": false}

推荐阅读