微信支付–node
项目的结构是这样的
Django – 后端
Node – 中间层
Vue – 前端
一、h5支付
整个流程这样的:
前端vue
向后端django
请求一个订单号,再到node
层向微信发起统一订单和接受微信支付结果的异步通知,最后从将交易结果返回给django
层,将交易记录写入数据库。
- 准备阶段 按照文档的要求
申请入口:登录商户平台-->产品中心-->我的产品-->支付产品-->H5支付
取得APPID
,微信支付商户号
,API密钥
,Appsecret
四个字段。 - 引进node版的SDK
node-tenpay
,传送门 - 新建
wechat-pay.js
文件
注意:后台的路由是有带有
api
的
例如:www.domain.com/api/order
请求到后台的api
www.domain.com/unifiedOrder
请求到node
的app.js
文件
h5支付的流程:
- 向后台请求订单号
- 请求统一下单(在node层向微信发起请求)
- 微信返回同步结果(mweb_url)
- 跳转到微信app
- 用户输入密码支付
- 在node层接受微信返回的异步通知,并把结果发到后台计入数据库
- 回到vue向后台轮询支付结果,交易成功则弹出提示信息‘支付成功’
wechat-pay.js
const tenpay = require('tenpay')
const axios = require('axios')
const wechatConfig = {
appid: 'xxxx',
mchid: 'xxxx',
partnerKey: 'xxxx',
notify_url: `www.domain.com/notify`, //微信异步通知的地址
}
const wechatApi = new tenpay(wechatConfig)
async function unifiedOrder(ctx) {
//传过来的total_fee单位为:元,传给微信要转化为分
const {out_trade_no, total_fee} = ctx.request.body
let sceneInfoObj = {
h5_info: {
type:"Wap",
wap_url: 'xxxx',
wap_name: "赞赏"
}
}
function get_ip () { //获取用户的真实ip
let ip = ctx.request.get("X-Real-IP") || ctx.request.get("X-Forwarded-For") || ctx.request.ip
if (ip.split(',').length > 0) {
ip = ip.split(',')[0]
}
return ip
}
let fee = total_fee
let result = await wechatApi.unifiedOrder({
out_trade_no: out_trade_no, //商户内部订单号
body: 'xxxxxxxxxxxxxxxxxxxxx',
total_fee: fee*100, //订单金额(单位:分)
trade_type: 'MWEB',
spbill_create_ip: get_ip(), //ip地址
scene_info: JSON.stringify(sceneInfoObj) //场景信息
})
ctx.response.status = 302
ctx.response.type = 'json'
ctx.response.body = {next: result.mweb_url}
}
async function notifyVerify(ctx) {
let info = ctx.request.weixin //微信返回的信息
let total_fee, order_status
//根据订单号去后台取详细数据
await axios({
method:'get',
url: 'order/',
params: {
order_id: info.out_trade_no
}
}).then((res) => {
total_fee = res.data.fee //金额
order_status = res.data.order_status //交易完成状态,1表示已完成,0表示未完成
})
// 在`node-tenpay`源码中已校验签名,所以这里只需要校验金额
if (order_status !== 0){
ctx.reply('订单已支付')
}else if (info.total_fee === total_fee) {
//交易成功,记录入库
try{
await axios.post({
url: 'www.domain.com/api/order/finish/',
data: {
order_id: info.out_trade_no, //订单号
notify_trade_no: info.transaction_id, //微信交易流水号
order_status: 1, //交易状态
}
})
ctx.reply('') //回复微信商户接收通知成功并校验成功
}catch (e) {
ctx.reply(e)
throw new Error(e)
}
} else {
ctx.reply('金额不一致')
}
}
module.exports = {unifiedOrder, wechatApi, notifyVerify}
在node
的index.js
或app.js
中,主要代码:
//引进`wechat-pay.js`里定义的方法
var {unifiedOrder, wechatApi, notifyVerify} = require('./wechat-pay.js')
//微信支付
app.use(bodyParser({
enableTypes: ['json', 'form', 'text'],
extendTypes: {
text: ['text/xml', 'application/xml']
}
}))
//统一下单
router.post('/unifiedOrder', unifiedOrder)
//支付结果通知
router.post('/notify', wechatApi.middleware(), notifyVerify)
在vue
层的主要代码:
//pay.vue
<script>
import axios from 'axios'
export default {
methods: {
pay() {
return axios.get('www.domain.com/api/order').then(res => {
let postData = {
res.data.out_trade_no, //后台生成的订单号
res.data.total_fee, //交易金额
}
//请求到node层
return axios({
baseURL: 'www.domain.com',
method: 'post',
url: '/unifiedOrder/',
data: dataPost,
}).catch(err => {
if (err.response.status === 302) {
//返回的支付地址拼接上redirect_url,支付完返回到原来的页面时,如果有需要查询支付结果,可利用query的checkBill字段去发起查询
window.location.href=(err.response.data.next+'&redirect_url='+encodeURI(window.location.href+'?checkBill=true'))
} else {
alert('支付失败!')
}
})
})
}
}
}
}
</script>
二、pc扫码–模式二
pc扫码的统一下单和h5支付的区别在于pc扫码必须带有product_id
字段,还有就是统一下单的同步返回结果是二维码链接 code_url
, 而h5的同步返回的return_msg
是一个跳转到微信app的链接,异步通知的处理相同。
pc扫码的流程:
- 向后台请求订单号
- 请求统一下单(在node层向微信发起请求)
- 微信返回同步结果(code_url)
- 在vue层生成二维码
- 用户完成扫码支付
- 在node层接受微信返回的异步通知,并把结果发到后台计入数据库
- vue向后台轮询支付结果,交易成功则弹出提示信息‘支付成功’并刷新页面,回到发起支付的页面
修改wechat-pay.js
async function unifiedOrder(ctx) {
//传过来的total_fee单位为:元,传给微信要转化为分
const {out_trade_no, total_fee, product_id} = ctx.request.body
let sceneInfoObj = {
h5_info: {
type:"Wap",
wap_url: www.domain.com,
wap_name: "赞赏"
}
}
function get_ip () { //获取用户的真实ip
let ip = ctx.request.get("X-Real-IP") || ctx.request.get("X-Forwarded-For") || ctx.request.ip
if (ip.split(',').length > 0) {
ip = ip.split(',')[0]
}
return ip
}
let fee = total_fee || 5
if (product_id) { //pc端扫码---要求必须有produce_id字段
let result = await wechatApi.unifiedOrder({
out_trade_no: out_trade_no, //商户内部订单号
body: 'xxxxxxxxxxxxx',
total_fee: fee*100, //订单金额(单位:分)
trade_type: 'NATIVE', //pc扫码模式二
product_id: product_id,
spbill_create_ip: get_ip() //ip地址
})
ctx.response.status = 201
ctx.response.body = {next: result.code_url, order_id: result.out_trade_no}
} else { //手机h5支付
let result = await wechatApi.unifiedOrder({
out_trade_no: out_trade_no, //商户内部订单号
body: 'xxxxxxxxxxxx',
total_fee: fee*100, //订单金额(单位:分)
trade_type: 'MWEB',
spbill_create_ip: get_ip(), //ip地址
scene_info: JSON.stringify(sceneInfoObj) //场景信息
})
ctx.response.status = 302
ctx.response.type = 'json'
ctx.response.body = {next: result.mweb_url}
}
}
在vue
文件中:
<script>
import axios from 'axios'
export default {
methods: {
pay() {
return axios.get('www.domain.com/api/order').then(res => {
let postData = {
res.data.out_trade_no, //后台生成的订单号
res.data.total_fee, //交易金额
res.data.product_id //产品id--pc扫码必须字段
}
return axios({
baseURL: 'www.domain.com',
method: 'post',
url: '/unifiedOrder/',
data: dataPost,
}).then(res => {
//返回的二维码信息,需要自己转为二维码图片
this.qr_url = res.data.code_url
//根据订单号向后台循环查询交易是否成功
this.handleCheckBill(res.data.order_id)
})
})
}
},
handleCheckBill (order_id) {
//参考https://juejin.im/post/5afb873f51882542ac7d6998
//超过30s内循环
let payStatus=false,retryCount=0
for (;payStatus === false && retryCount < 30;retryCount++){
setTimeout(() => {
axios.get('www.domain.com/order/', {
// 向后端请求订单支付信息
order_id: order_id
})
.then(res => {
if (res.data.order_status) { //数据库里的交易状态码,1为成功,0为失败
payStatus = true //交易成功
this.$notify({
type: 'success',
title: '支付成功',
})
}
})
}, 1000*retryCount)
}
if(payStatus=false) this.$throwError('等待时间超过30s')
},
}
}
</script>