uniapp使用unipay云函数完成微信支付

2021/4/7 10:42:37 | 阅6222 来源:好空间网络 [打印] [关闭]
 

1.     在项目上点击右键,创建unicloud环境,会自动出现cloudfunctions,database2个目录,

在cloudfunctions文件夹下建立common文件夹


2导入公共模块uniid,成功后会自动在common文件夹下找到uni-id文件夹

    2.1 https://ext.dcloud.net.cn/plugin?id=2116 导入地址

    2.2:在uniid下建立config.json,内容如下:

{
	"passwordSecret": "passwordSecret-demo",
	"tokenSecret": "tokenSecret-demo",
	"tokenExpiresIn": 7200,
	"tokenExpiresThreshold": 600,
	"passwordErrorLimit": 6,
	"bindTokenToDevice": true,
	"passwordErrorRetryTime": 3600,
	"autoSetInviteCode": false,
	"forceInviteCode": false,
	"app-plus": {
		"tokenExpiresIn": 2592000,
		"oauth" : {
			"weixin" : {
				"appid" : "weixin appid",
				"appsecret" : "weixin appsecret"
			}
		}
	},
	"mp-weixin": {
		"oauth" : {
			"weixin" : {
				"appid" : "wx770e0da6e86af1a6",
				"appsecret" : "a179be149d285f5b09dfb318fa6dc503"
			}
		}
	},
	"mp-alipay": {
		"oauth" : {
			"alipay" : {
				"appid" : "alipay appid",
				"privateKey" : "alipay privateKey"
			}
		}
	},
	"service": {
		"sms": {
			"name": "DCloud",
			"codeExpiresIn": 300,
			"smsKey": "your sms key",
			"smsSecret": "your sms secret"
		}
	}
}

具体参数说明请见:

https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=%e5%bf%ab%e9%80%9f%e4%b8%8a%e6%89%8b


3.在cloudfunctions文件夹下建立getOpenid云函数

const uniID = require('uni-id')
exports.main = async function(event,context) {
    const res = await uniID.code2SessionWeixin({
    code: event.code
  })
    return res
}

在刚刚建立的getOpenid云函数上点击右键,管理公共模块依赖,选择刚刚的uniid,这样以后如果需要修改微信的appid等可以直接修改uni-id函数,修改后右键有个更新所有依赖次函数的模块,就会自动更新


111.png


4.

安装unipay,安装好上传即可无需其他操作

https://ext.dcloud.net.cn/plugin?id=1835



5.新建getOrderInfo云函数

'use strict';
 
const unipay = require('unipay')
const unipayIns = unipay.initWeixin({
   appId: '', //小程序appid
   mchId: '', //微信商户号
   key: '', //商户号的API密钥
   //pfx: fs.readFileSync('/path/to/your/pfxfile'), // p12文件路径,使用微信退款时需要,需要注意的是阿里云目前不支持以相对路径读取文件,请使用绝对路径的形式
})
exports.main = async (event, context) => {
   //event为客户端上传的参数
   let orderInfo = await unipayIns.getOrderInfo({
      openid: event.openid, //这个是客户端上传的用户的openid
      subject: event.name, // 订单名称微信支付时不可填写此项
      body: '养老服务费',
      outTradeNo: event.suiji, //给他个随机号让他可以第二次发起支付
      totalFee: event.pric, // 金额,单位元,在上传过来的时候就已经*100了
      notifyUrl: 'https://xxxx.net/PayResult', // 支付结果通知地址
      attach: event.out_trade, //备注,订单号或 长者id 在下一步通知中判断长度来确定
   })
   return { orderInfo }
 
};

在刚刚新建的getOrderInfo云函数上点击右键,选择管理公共模块依赖,选择刚刚的unipay,让他们关联起来


6. 编写小程序端文件

// 1.传递weixin 获取微信的code
uni.login({
               provider: 'weixin',
               success(code) {
                  console.log('code:', code.code)
                  //2:获得微信openid
                  uniCloud.callFunction({
                     name: 'getOpenid',
                     data: {
                        code: code.code
                     }
                  }).then(openid => {
                     console.log('openid:', openid)
                     //3:統一下單
                     uniCloud.callFunction({
                        name: 'getOrderInfo',
                        data: {
                           openid: openid.result.openid,
                           name: that.order.name,
                           out_trade: that.order.out_trade, // 订单号
                           suiji: Math.floor(Math.random() * 100000000),
                           pric: Number(that.order.AgencyPric) * 100
                        }
                     }).then(odr => {
                        console.log('OrderInfo:', odr)
                        uni.hideLoading(); //隐藏loding...
                        uni.requestPayment({
                           // #ifdef MP-WEIXIN
                           ...odr.result.orderInfo,
                           // #endif                                   
                           success() {
                              uni.showModal({
                                 title: '支付成功',
                                 content: '请和顾问联系执行订单即可!'
                              })
                           },
                           fail() {},
                           complete() {
                              // 支付完成后重新加载该页面
                              that.getData()
                           }
                        })
                     })
 
                  })
               },
               fail(err) {
                  reject(new Error('微信登录失败'))
               }
            })
            // 支付结束


经营许可证ICP:皖B2-20100052 公司邮箱:zcdnsz@jspkongjian.net
Copyright © 2004-2015, 安徽好空间网络科技有限公司 版权所有 , 本站素材部分来源于网络,如有侵权请告知删除。