云开发支付
发布于 4 年前 作者 jun77 2048 次浏览 来自 分享

代码前提:只需要替换两个与自己相关的参数key和mch_id

1、小程序开通微信支付成功,去公众平台(https://mp.weixin.qq.com/);

成功后可以知道自己的mch_id,即商户号。

2、去这里:商户平台(https://pay.weixin.qq.com/),获取key = API密钥

小程序端:

wx.cloud.callFunction({
  name: 'wepay',
  success: res => {
    console.log(res.result)
    if (!res.result.appId) return
    wx.requestPayment({
      ...res.result,
      success: res => {
        console.log(res)
      }
    })
  }
})

云函数wepay:

const key = "ABC...XYZ"//换成你的商户key,32位
const mch_id = "1413092000"//换成你的商户号
//以下全部照抄即可
const cloud = require('wx-server-sdk')
const rp = require('request-promise')
const crypto = require('crypto')
cloud.init()
function getSign(args) {
  let sa = []
  for (let k in args) sa.push(k + '=' + args[k])
  sa.push('key=' + key)
  return crypto.createHash('md5').update(sa.join('&'), 'utf8').digest('hex').toUpperCase()
}
function getXml(args) {
  let sa = []
  for (let k in args) sa.push('<' + k + '>' + args[k] + '</' + k + '>')
  sa.push('<sign>' + getSign(args) + '</sign>')
  return '<xml>' + sa.join('') + '</xml>'
}
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let appId = appid = wxContext.APPID
  let openid = wxContext.OPENID
  let attach = 'attach'
  let body = 'body'
  let total_fee = 1
  let notify_url = "https://mysite.com/notify"
  let spbill_create_ip = "118.89.40.200"
  let nonceStr = nonce_str = Math.random().toString(36).substr(2, 15)
  let timeStamp = parseInt(Date.now() / 1000) + ''
  let out_trade_no = "otn" + nonce_str + timeStamp
  let trade_type = "JSAPI"
  let xmlArgs = { appid, attach, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type }
  let xml = (await rp({ url: "https://api.mch.weixin.qq.com/pay/unifiedorder", method: 'POST', body: getXml(xmlArgs) })).toString("utf-8")
  if (xml.indexOf('prepay_id') < 0) return xml
  let prepay_id = xml.split("<prepay_id><![CDATA[")[1].split("]]></prepay_id>")[0]
  let payArgs = { appId, nonceStr, package: ('prepay_id=' + prepay_id), signType: 'MD5', timeStamp }
  return { ...payArgs, paySign: getSign(payArgs) }
}

packge.json:

{
  "name": "wepay",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "wx-server-sdk": "latest",
    "crypto": "^1.0.1",
    "request-promise": "^4.2.2"
  }
}
7 回复

有没有轮询查微信支付结果的案例云函数的。。

放弃了.哈哈

👍 👍 👍

云开发怎么做退款呀

厉害,就是 notify_url 需要自己服务器没啥解决方法。

Setting data field “brArr” to undefined is invalid 小程序感觉所有传值都没有成功,之前本地测试都正常的,API上公网就报这个错,postman单独测试又是正常的

特约商户的吗?

回到顶部