React 快速入门
使用 CapacitorStripeProvider 来封装该应用的功能。该提供程序会调用 Stripe.initialize 方法,检查 Apple Pay 和 Google Pay 的可用性,并在网页上注册 stripe-pwa-elements 相关元素。
App.tsx
import { IonApp } from '@ionic/react';
import { CapacitorStripeProvider } from '@capacitor-community/stripe/react';
const App: React.FC = () => (
<CapacitorStripeProvider
publishableKey="Your Publishable Key"
fallback={<p>Loading...</p>}
>
<IonApp>{/* ... */}</IonApp>
</CapacitorStripeProvider>
);
export default App;
CapacitorStripeProvider 也接受 Stripe Connect 的可选参数 stripeAccount。
此提供程序只初始化 Payment。如果应用还使用 Identity、Terminal 或 Billing,需分别初始化。构建 Web 版本时,请安装兼容的对等依赖:
npm install stripe-pwa-elements@^5.3.0
使用 Stripe 客户端
使用 useCapacitorStripe 函数来初始化客户端对象。返回的 stripe 对象其实就是与 @capacitor-community/stripe 中的 Stripe 模块相同的插件实例。
import { useCapacitorStripe } from '@capacitor-community/stripe/react';
export const PaymentSheet: React.FC = () => {
const { stripe } = useCapacitorStripe();
return (
<button
onClick={async () => {
await stripe.createPaymentSheet({
paymentIntentClientSecret,
merchantDisplayName: 'App Name',
});
await stripe.presentPaymentSheet();
}}
>
Pay
</button>
);
};
从要求身份验证的后端获取 paymentIntentClientSecret,参见服务器集成。在界面中处理取消和失败,并以服务端验证过的 webhook 作为履约依据。
在应用启动过程中,会一次性注册所有监听器的回调函数,而不是在支付按钮的 handlers 中分别进行注册。详情请参阅事件监听器。
官方的 React 演示代码可以在capacitor-community/stripe/demo/react中找到。