微信支付--node作为中间层

微信支付–node

项目的结构是这样的

Django – 后端
Node – 中间层
Vue – 前端

一、h5支付

整个流程这样的:
  前端vue向后端django请求一个订单号,再到node层向微信发起统一订单和接受微信支付结果的异步通知,最后从将交易结果返回给django层,将交易记录写入数据库。


  1. 准备阶段 按照文档的要求申请入口:登录商户平台-->产品中心-->我的产品-->支付产品-->H5支付取得APPID,微信支付商户号,API密钥,Appsecret四个字段。这里写图片描述
  2. 引进node版的SDKnode-tenpay,传送门
  3. 新建wechat-pay.js文件

注意:后台的路由是有带有api
例如:www.domain.com/api/order 请求到后台的api
www.domain.com/unifiedOrder请求到nodeapp.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}

nodeindex.jsapp.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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
老规矩,先看本节效果图我们实现这个支付功能完全是借助小程序云开发实现的,不用搭建自己的服务器,不用买域名,不用备案域名,不用支持https。只需要一个简单的云函数,就可以轻松的实现微信小程序支付功能。核心代码就下面这些一,创建一个云开发小程序关于如何创建云开发小程序,这里我就不再做具体讲解。不知道怎么创建云开发小程序的同学,可以去翻看我之前的文章,或者看下我录制的视频:https://edu.csdn.net/course/play/9604/204528创建云开发小程序有几点注意的1,一定不要忘记在app.js里初始化云开发环境。2,创建完云函数后,一定要记得上传二, 创建支付的云函数1,创建云函数pay三,引入三方依赖tenpay我们这里引入三方依赖的目的,是创建我们支付时需要的一些参数。我们安装依赖是使用里npm 而npm必须安装node,关于如何安装node,我这里不做讲解,百度一下,网上一大堆。1,首先右键pay,然后选择在终端中打开2,我们使用npm来安装这个依赖。在命令行里执行 npm i tenpay安装完成后,我们的pay云函数会多出一个package.json 文件到这里我们的tenpay依赖就安装好了。四,编写云函数pay完整代码如下//云开发实现支付 const cloud = require('wx-server-sdk')cloud.init() //1,引入支付的三方依赖 const tenpay = require('tenpay'); //2,配置支付信息 const config = ;exports.main = async(event, context) => 一定要注意把appid,mchid,partnerKey换成你自己的。到这里我们获取小程序支付所需参数的云函数代码就编写完成了。不要忘记上传这个云函数。出现下图就代表上传成功五,写一个简单的页面,用来提交订单,调用pay云函数。这个页面很简单,1,自己随便编写一个订单号(这个订单号要大于6位)2,自己随便填写一个订单价(单位是分)3,点击按钮,调用pay云函数。获取支付所需参数。下图是官方支付api所需要的一些必须参数。下图是我们调用pay云函数获取的参数,和上图所需要的是不是一样。六,调用wx.requestPayment实现支付下图是官方的示例代码这里不在做具体讲解了,完整的可以看视频。实现效果1,调起支付键盘2,支付完成3,log日志,可以看出不同支付状态的回调上图是支付成功的回调,我们可以在支付成功回调时,改变订单支付状态。下图是支付失败的回调,下图是支付完成的状态。到这里我们就轻松的实现了微信小程序的支付功能了。是不是很简单啊,完整的讲解可以看视频。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值