企业版
首先需要在微信商户里面设置好 v3密钥,弄好证书,网上有很多这边不做详细讲解了,可以自行查询。
v3签名
直接贴出我的全部代码
unicloud
money 的index.js
cert是在money下面的文件夹
'use strict';
const db = uniCloud.database()
// 云函数入口文件
// 读取证书
const appid = "xxxxxx"//你的appid
let mchid = 'xxxxxx' //你的微信商户号
// 支付密钥
// 证书序列号
let num = 'xxxxxxxxxxxxxxxx'
const fs = require('fs') // 文件读取模块
const path = require('path'); // 引入内置的path模块
const crypto = require('crypto');
exports.main = async (event, context) => {
event.out_batch_no = `plfk${Math.floor(Date.now() / 1000)}`
event.total_amount = parseFloat(event.total_amount)
event.transfer_detail_list[0].transfer_amount = event.total_amount
// 读取证书
const cert = fs.readFileSync(path.resolve(__dirname, 'cert/apiclient_cert.pem'))
const prikey = fs.readFileSync(path.resolve(__dirname, 'cert/apiclient_key.pem'))
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
let maxPos = chars.length;
let character = '';
for (let i = 0; i < 32; i++) {
character += chars.charAt(Math.floor(Math.random() * maxPos))
}
// 获取签名
const timestamp = Math.floor(Date.now() / 1000);
const nonceStr = character; // 替换成随机字符串
const method = 'POST'; // 请求方法
const path2 = '/v3/transfer/batches'; // 请求路径
const body = JSON.stringify(event); // 请求体数据,如果有的话
const serialNo = num; // 商户证书序列号
// 构建待签名字符串
const message = `${method}\n${path2}\n${timestamp}\n${nonceStr}\n${body}\n`;
// 使用商户私钥进行签名
const sign = crypto
.createSign('sha256')
.update(message)
.sign(prikey, 'base64');
// 创建 Authorization 头部
const authorization =
`WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",serial_no="${serialNo}",nonce_str="${nonceStr}",timestamp="${timestamp}",signature="${sign}"`;
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'user-agent': encodeURIComponent('私厨到家啦/1.0.0'),
'Wechatpay-Serial': num,
"Authorization": authorization
};
let data = {
cert_sn: cert,
mch_id: mchid,
api_key: 'xxxxxxxxxxxxx'// v3密钥
};
const res = await uniCloud.httpclient.request('https://api.mch.weixin.qq.com/v3/transfer/batches', {
method: 'POST',
data: JSON.stringify(event),
rejectUnauthorized: false,
body: JSON.stringify(event),
headers: headers,
contentType: 'json', // 指定以 application/json 发送 data 内的数据
dataType: 'json', // 指定返回值为 json 格式,自动进行 parse
timeout: 30 * 1000
})
return res
};
前端代码
let param = {
appid: appid,
out_batch_no: partner_trade_no, //商家批次单号
batch_name: time + "厨师提现",
batch_remark: time + "厨师提现",
total_amount: Number(this.moneyVal) * 100, // 转账金额
total_num: 1,
transfer_scene_id: "1001",
transfer_detail_list: [
{
out_detail_no: nonce_str,
transfer_amount: Number(this.moneyVal) * 100, // 转账金额
transfer_remark: time + "厨师提现",
openid: "o8Pt3649dwh9r9U3eOrjcjPCIYtQ",
},
],
};
// 接口我自己做了封装
let RES = await this.$common.GetUniCloud("money", param);
console.log(RES, "json======");
到这边的话,提现功能就成功了!!