uniapp Stripe 支付

发布于:2025-02-11 ⋅ 阅读:(74) ⋅ 点赞:(0)

引入 Stripe  

npm install @stripe/stripe-js

import { loadStripe } from '@stripe/stripe-js';

Stripe 提供两种不同类型组件

Payment Element 和  Card Element:如果你使用的是 Payment Element,它是一个更高级别的组件,能够自动处理多种支付方式(如信用卡、Apple Pay 等),并且不需要你手动指定 payment_method 对象。而 Card Element 则是专门用于收集信用卡信息的低级别组件

 这里用的是 Payment Element Stripe 自动处理支付方式的选择,并且不要手动构造 payment_method 对象

import { loadStripe } from '@stripe/stripe-js';

export default {
  data() {
    return {
      stripe: null,
      elements: null,
      paymentElement: null,
      clientSecret: ''  // 调用后端创建订单接口返回的参数
    };
  },
  async mounted() {
    uni.showLoading({
		title: 'loading...'
    });
    this.stripe = await loadStripe(''); // 替换为你的 Publishable Key
	this.setupElements()
  },
  methods: {
    setupElements(){
        if (!this.stripe || !this.clientSecret) return;
		this.elements = this.stripe.elements({
			 clientSecret: this.clientSecret,
		})
		this.paymentElement= this.elements.create('payment');
		this.paymentElement.mount('#payment-element');
		uni.hideLoading()
    },
	async handleSubmit() {
				if (!this.stripe || !this.paymentElement || !this.clientSecret) {
                    //  自己封装的提示方法
					this.$Common.showToast('Payment setup is incomplete');
					return;
				}
				uni.showLoading({
					title: 'loading...'
				});
				const {
					error,
					paymentIntent
				} = await this.stripe.confirmPayment({
					elements: this.elements,
					confirmParams: {
						// 用户完成支付后的重定向 URL
						return_url: 'http://123:8080/#/pages/pay/orderComplete',
					},
				});
				if (error) {
					console.error('Error:', error.message);
					this.$Common.showToast(error.message);
					uni.hideLoading()
					
				} else {
					if (paymentIntent.status === 'succeeded') {
						uni.hideLoading()
						this.$Common.showToast('Payment succeeded!');
						
						// 这里可以根据业务逻辑跳转到成功页面或执行其他操作
					}
				}
			},
  }
};


网站公告

今日签到

点亮在社区的每一天
去签到