【记录】 uni-app app端 实现支付宝和微信支付

7,067 阅读1分钟

需求

最近项目使用uni-app实现支付宝和微信支付,把过程简单记录下。

uniapp 官方支付文档

uniapp.dcloud.io/api/plugins…

需要的资料

  1. 申请了商户号,拿到了API秘钥。这个需要微信开发平台上申请。

  2. 后面代码里用到的appid和秘钥之类需要实现申请号。

  3. 在uni-app manifest.json 配置sdk支付权限

实现的思路:

重点:打包的时候包名需要和微信开放平台提供的包名一致并且打自定义包!!!

我的需求是在app内通过微信或支付宝购买会员,我调后端的接口传个id和价格,后端去调用微信或支付宝的下单接口,然后返回给我uni.requestPayment 需要的参数。

前端案例:

微信支付

// 微信支付
this.$Request
	.post({
		url: '/wx/APPPay',
		data: {
			openmemberid: this.cardId,
			total_fee: this.money
		}
	})
	.then(res => {
		console.log(res);
		let obj = {
			appid: res.appId,
			noncestr: res.nonceStr,
			package: 'Sign=WXPay', // 固定值,以微信支付文档为主
			partnerid: res.partnerid,
			prepayid: res.prepayid,
			timestamp: res.timestamp,
			sign: res.sign // 根据签名算法生成签名
		};

		let orderInfo = JSON.stringify(obj);

		console.log(orderInfo);
		uni.requestPayment({
			provider: 'wxpay',
			orderInfo: orderInfo, //微信、支付宝订单数据
			success: res => {
				Show.show('您已开通会员');
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			fail: function(err) {
				console.log('fail:' + JSON.stringify(err));
			}
		});
	});

支付宝支付:其实代码基本上差不多

this.$Request
	.post({
		url: '/jiekou/AliPay',
		data: {
			openmemberid: this.cardId,
			total_amount: this.money
		}
	})
	.then(res => {
		let orderInfo = res.res;

		uni.requestPayment({
			provider: 'alipay',
			orderInfo: orderInfo,
			success: res => {
				Show.show('您已开通会员');
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			fail: function(err) {
				Show.show('支付失败: ' + err);
				console.log('fail:' + JSON.stringify(err));
			}
		});
	})
	.catch(err => {
		console.log(err);
	});

参数都是后端返回的orderinfo,其实这个orderinfo也是微信或者支付宝给后端,后端再返回给前端

以上就是全部的代码 用于记录!!