开源宝典:React Native下的支付新纪元 —— Square的In-App Payments插件
import React from 'react';
import { View, Text } from 'react-native';
import { useInAppPayments } from 'react-native-square-in-app-payments';
const PaymentScreen = () => {
const { loading, error, createPaymentRequest, onPaymentResult } = useInAppPayments();
if (loading) {
return <Text>正在加载...</Text>;
}
if (error) {
return <Text>错误: {error.message}</Text>;
}
// 创建付款请求
const paymentRequest = createPaymentRequest({
currencyCode: 'USD',
countryCode: 'US',
total: {
label: '总金额',
amount: '100', // 以分为单位
pending: false
}
});
// 处理付款结果
const handlePaymentResult = (result) => {
if (result.userCancelled) {
console.log('用户取消了支付');
} else {
console.log('支付成功', result.payment);
}
};
// 触发支付
const requestPayment = () => {
onPaymentResult(paymentRequest, handlePaymentResult);
};
return (
<View>
<Text onPress={requestPayment}>触发支付</Text>
</View>
);
};
export default PaymentScreen;
这个代码示例展示了如何在React Native应用中使用Square的In-App Payments插件来请求用户的支付。它首先检查加载状态和错误,然后创建一个付款请求,并处理用户的支付结果。最后,它提供了一个可供用户触发支付流程的按钮。
评论已关闭