React-Native,Stripe 卡元素不显示实时 API 密钥

nit*_*ian 3 html javascript stripe-payments react-native react-native-webview

在我的 react-native 项目中,我使用了 react-native-webview 和 stripe js ( https://js.stripe.com/v3 )

使用条纹 js 我正在创建卡片元素来收集卡片详细信息

var elements = stripe.elements()
var card = elements.create('card');
card.mount('#card-element');
Run Code Online (Sandbox Code Playgroud)

当用户按下提交按钮时,我正在调用 stripe.confirmPaymentIntent() 函数来完成付款。

但是当我使用 PRODUCTION PUBLIC_KEY 卡元素未显示时,我遇到了问题,用于测试 PUBLIC_KEY 卡元素是否正确显示。

任何解决方案?

我的项目详情是

  • “反应”:“16.9.0”
  • “反应原生”:“0.61.5”
  • “react-native-webview”:“10.3.2”

xcode 版本 - 12.1 IOS 版本 - 14.1

function stripeCheckoutRedirectHTML(PUBLIC_KEY) {
  return `<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<html>
<body>
  <!-- Load Stripe.js on your website. -->
  <script src="https://js.stripe.com/v3"></script>
  <h1 id="error-message"></h1>
  <form method="post" id="payment-form">
    <div class="form-row">
      <label for="card-element">
        Credit or debit card
      </label>
      <div id="card-element">
        <!-- A Stripe Element will be inserted here. -->
      </div>
    </div>
    <button>Submit Payment</button>
  </form>
  <script>
    var stripe = Stripe(${PUBLIC_KEY});
    var elements = stripe.elements();
    var card = elements.create('card');
    card.mount('#card-element');
  </script>
</body>

</html>`;
}
Run Code Online (Sandbox Code Playgroud)
export default function Payment({route, navigation}) {
  return (
    <View style={styles.container}>
      <View style={styles.body} showsVerticalScrollIndicator={false}>
        <WebView
          originWhitelist={['*']}
          source={{
            html: stripeCheckoutRedirectHTML(Config.PUBLIC_KEY),
          }}
        />
      </View>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

小智 6

Stripe.js 要求您在生产环境中通过 HTTPS 运行您的站点。为了使测试更容易,当您使用测试 API 密钥时会取消此限制,这就是它以前对您有用的原因。默认情况下,React Native 将通过about:blank. 因此,当您从测试切换到实时可发布密钥时,Stripe 会抛出一个错误,指出实时 Stripe.js 集成必须使用 HTTPS。有两个选项可以解决这个问题:

  • 您可以通过 HTTPS 托管您的站点,并在实例化组件时将其作为源 URI 传递,而不是向 WebView 组件提供原始 HTML。
  • 您可以提供指向通过 https 提供服务的站点的 baseURL 选项。React Native 将替换about:blank为该 URL,原始 HTML 中的任何非绝对链接都将与该 URL 相关。例如:
export default function Payment({route, navigation}) {
  return (
    <View style={styles.container}>
      <View style={styles.body} showsVerticalScrollIndicator={false}>
        <WebView
          originWhitelist={['*']}
          source={{
            html: stripeCheckoutRedirectHTML(Config.PUBLIC_KEY),
            baseUrl: 'https://example.com',
          }}
        />
      </View>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)