简体   繁体   English

Stripe 支付集成 React Native。 调用 presentPaymentSheet 函数导致应用崩溃

[英]Stripe payment integration React Native. calling presentPaymentSheet function leads to app crash

I am building an e-commerce app using React Native and Django as backend.我正在使用 React Native 和 Django 作为后端构建一个电子商务应用程序。 The payment integration is built with Stripe.支付集成是使用 Stripe 构建的。 The following lines of code are from Django views, whose aim is to create a customer, ephemeral key, and payment intent and return their specific values which will be needed to complete the transactions...以下代码行来自 Django 视图,其目的是创建客户、临时密钥和支付意图,并返回完成交易所需的特定值...

@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def payment_sheet(request, *args, **kwargs):

    data = request.data
    subtotal = data['subtotal']
    customer = stripe.Customer.create()
    ephemeralKey = stripe.EphemeralKey.create(
    customer=customer['id'],
    stripe_version='2020-08-27'
    )
    paymentIntent = stripe.PaymentIntent.create(
        amount=int(subtotal),
        currency='eur',
        customer=customer['id'],
    )
    return JsonResponse({
        'paymentIntent': paymentIntent.client_secret,
        'ephemeralKey': ephemeralKey.secret,
        'customer': customer.id
    })

My screen is within the StripeProvider as Docs guides.我的屏幕在 StripeProvider 作为 Docs 指南。

const MainFlow = ({ }) => {

return (
    <ShoppingProvider>
        <StripeProvider
            publishableKey="pk_test_Dt4ZBItXSZT1EzmOd8yCxonL"
        >
            <OrderItemProvider>
                <MainFlowStack.Navigator>
                    <MainFlowStack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} />
                    <MainFlowStack.Screen name="Cart" component={CartScreen} options={{ headerShown: false }} />
                    <MainFlowStack.Screen name="Favourite" component={FavouriteScreen} options={{ headerShown: false }} />
                    <MainFlowStack.Screen name="Search" component={SearchScreen} options={{ headerShown: false }} />
                    <MainFlowStack.Screen name="Detail" component={DetailScreen} options={{ headerShown: false }} />
                    <MainFlowStack.Screen name="Checkout" component={CheckoutScreen} options={{ headerShown: false }} />
                </MainFlowStack.Navigator>
            </OrderItemProvider>
        </StripeProvider>
    </ShoppingProvider>
)

On the other hand, here is the code from my Checkout Screen from my React Native project.另一方面,这里是来自我的 React Native 项目的 Checkout Screen 的代码。

const CheckoutScreen = ({ route }) => {

const { token } = useUserInfo()
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const [clientSecret, setClientSecret] = useState('')
const [loading, setLoading] = useState(false);
const subtotal = route.params.subtotal

const fetchPaymentSheetData = (token, subtotal) => {

    const total = (subtotal * 100).toString()
    const data = { "subtotal": total }

    return fetch(`${API}/api/payment/payment-sheet/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Token ${token}`
        },
        body: JSON.stringify(data)
    })
        .then((res) => {
            return res.json()
        })
        .catch((err) => console.log(err))
}

const initializePaymentSheet = (token, subtotal) => {

    fetchPaymentSheetData(token, subtotal)
        .then((res) => {
            setClientSecret(res.paymentIntent)
            initPaymentSheet({
                customerId: res.customer,
                customerEphemeralKeySecret: res.ephemeralKey,
                paymentIntentClientSecret: res.paymentIntent,
            })
                .then((res) => {
                    console.log(res)
                    setLoading(true)
                })
                .catch((err) => console.log(err))
        })
        .catch((err) => console.log(err))

    // const { error } = await initPaymentSheet({
    //     customerId: paymentInfo.customer,
    //     customerEphemeralKeySecret: paymentInfo.ephemeralKey,
    //     paymentIntentClientSecret: paymentInfo.paymentIntent,
    // })
    // if (!error) {
    //     setLoading(true)
    // }
}

const openPaymentSheet = async () => {
    const { error } = await presentPaymentSheet({ clientSecret });

    if (error) {
        Alert.alert(`Error code: ${error.code}`, error.message);
    } else {
        Alert.alert('Success', 'Your order is confirmed!');
    }
};

useEffect(() => {
    initializePaymentSheet(token, subtotal)
}, [])

return (
    <View style={style.root}>
        <Navbar />
        <Text>{subtotal}</Text>
        <Button
            variant="primary"
            disabled={!loading}
            title="Checkout"
            onPress={openPaymentSheet}
        />
    </View>
);

} }

The initPaymentSheet promise is not rejected and the 'Checkout' Button is now available. initPaymentSheet 承诺不会被拒绝,并且“结帐”按钮现在可用。 The problem comes when the button is pressed and hence within the 'openPaymentSheet' function, presentPaymentSheet is called... this leads to a crashing in the app.当按下按钮时出现问题,因此在“openPaymentSheet”函数中,presentPaymentSheet 被调用......这会导致应用程序崩溃。 Can anyone point out a bug or tell why this error is happening?谁能指出一个错误或告诉为什么会发生这个错误?

Thanks in advance提前致谢

I fell into the same problem, and for me the problem was solved by providing some additional information while initPaymentSheet.我遇到了同样的问题,对我来说,通过在 initPaymentSheet 时提供一些额外的信息解决了这个问题。

   const {error} = await initPaymentSheet({
      customerEphemeralKeySecret: ephemeralKey,
      setupIntentClientSecret: setupIntent,
      customerId: customer,
      customFlow: false,
      merchantDisplayName: 'Test Inc.',
      style: 'alwaysDark',
    });

packages versions are:软件包版本是:

"@stripe/stripe-react-native": "^0.13.1",
"react-native": "^0.68.2",

I was following the bellow document to implement the stripe我正在按照下面的文档来实现条纹

https://stripe.com/docs/payments/save-and-reuse https://stripe.com/docs/payments/save-and-reuse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM