uniapp+nodejs实现小程序支付

1.准备商户号、企业级小程序(或者个体工商户级别的)

2.在小程序端调用uni.login获取code,传递给后端

复制代码
uni.login({
			success: loginRes => {
				uni.request({
					url: "http://127.0.0.1:3003/wxpay/pay",
					data: {
						code: loginRes.code
					},
					method: "get",
					success: res => {
						
					},
					fail: err => {
						
					}
				})
			}
		})

3.在nodejs端,

复制代码
let express = require("express");
let router = express.Router();
const WxPay = require('wechatpay-node-v3');
const fs = require('fs');
let api = require("../api/index");
var path = require('path');
let weixinData = require('../utils/weixinData');
const qs = require('querystring')

//根据code查找openid
function getOpenid(code){
    return new Promise((resolve, reject) => {
        let appid = weixinData.Appid
        let secret = weixinData.AppSecret
        let params = {
            appid,
            secret,
            js_code:code
        }
        let formData = qs.stringify(params)
        let openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?" + formData + "&grant_type=authorization_code"
        api.get(openIdUrl).then( res => {
            resolve(res.data.openid)
        })
    })
}

// 创建支付实例
const pay = new WxPay({
    appid: 'wx9fc72986dc9287b6',
    mchid: '1674432158',
    publicKey: fs.readFileSync(path.resolve(__dirname, 'apiclient_cert.pem')), // 公钥
    privateKey: fs.readFileSync(path.resolve(__dirname, 'apiclient_key.pem')), // 秘钥
    key: 'zlc010903zlc010903zlc010903wcpwc'
});

// 订单号生成函数
function randomNumber() {
    const now = new Date()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let hour = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds()
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    hour = hour < 10 ? "0" + hour : hour;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    return orderCode;
}

let notify = async (req, res) => {
    // 申请的APIv3
    let key = 'zlc010903zlc010903zlc010903wcpwc';
    let { ciphertext, associated_data, nonce } = req.body.resource;
    // 解密回调信息
    const result = pay.decipher_gcm(ciphertext, associated_data, nonce, key);
    // 拿到订单号
    let { out_trade_no } = result;
    if (result.trade_state == 'SUCCESS') {
        // 支付成功之后需要进行的业务逻辑
		console.log('支付成功')



    }
}

// 拿到支付所需参数
let payInfo = (req, res) => {
    let { code } = req.query
    //获取openid
    getOpenid(code).then(async resolve => {
        const params = {
            mchid: '1674432158',
            description: '支付测试', // 订单描述
            out_trade_no: randomNumber(), // 订单号,一般每次发起支付都要不一样,可使用随机数生成
            notify_url: 'http://127.0.0.1:3003/wxpay/notify_url',
            amount: {
                total: 1, // 支付金额,单位为分
                currency: 'CNY'
            },
            payer: {
                openid: resolve, // 微信小程序用户的openid,一般需要前端发送过来
            },
            scene_info: {
                payer_client_ip: 'ip', // 支付者ip,这个不用理会也没有问题
            },
        };
        const result = await pay.transactions_jsapi(params);
        // 将结果响应给微信小程序前端
        res.send(result);
    })
    
}

// 回调路由
router.post('/notify_url', notify)
router.get('/pay', payInfo);
module.exports = router
相关推荐
小光学长1 分钟前
基于微信小程序的评奖评优系统51r12nd0(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·微信小程序·小程序
Jenna的海糖5 分钟前
检查微信小程序版本更新,手动更新
微信小程序·小程序
2501_916007471 小时前
iOS 自动化上架的工具组合,在多平台环境中实现稳定发布
android·运维·ios·小程序·uni-app·自动化·iphone
1024小神1 小时前
uniapp项目中使用vue3和小程序组件父子通信
前端·小程序·uni-app
爱敲代码的婷婷婷.2 小时前
微信小程序配置h5域名 / 普通二维码规则
微信小程序·小程序
fruge3 小时前
华玥组件库 · 为 uni-app 打造的新一代高效组件解决方案
uni-app
遗憾随她而去.17 小时前
uniapp 折叠动画 <transition> 踩坑记录
css·uni-app
说私域18 小时前
基于开源AI大模型的AI智能名片在S2B2C商城小程序维度表重复数据整理中的应用及效果研究
人工智能·小程序
云起SAAS21 小时前
图文小程序内无实质业务服务功能体验不完整解决小程序开源
小程序
毕设源码-朱学姐1 天前
【开题答辩全过程】以 干洗店预约服务小程序为例,包含答辩的问题和答案
小程序