1、安装
gem 'wx_pay', :git => 'git://github.com/jasl/wx_pay'
2、后台api
params = {
body: "在#{@order.shop.name}消费了#{@order.total_fee}元", # 订单显示的文字
out_trade_no: @order.sn, # 订单唯一码,后台生成
total_fee: (@order.total_fee * 100).to_i, # 订单总价,必须为整型
spbill_create_ip: '120.55.164.64', # 订单ip,服务器ip
notify_url: 'http://www.jiancan.me/pay_notify', # 支付回调函数
trade_type: 'JSAPI', # could be "JSAPI", "NATIVE" or "APP", # H5端用JSAPI
openid: "#{current_user.weixin_open_id}" # 支付类型为JSAPI时候要提供,这个是用户
# 授权后返回的。
}
r = WxPay::Service.invoke_unifiedorder params
# 申请支付返回的json数据
# => {
# "return_code"=>"SUCCESS",
# "return_msg"=>"OK",
# "appid"=>"YOUR APPID",
# "mch_id"=>"YOUR MCH_ID",
# "nonce_str"=>"8RN7YfTZ3OUgWX5e",
# "sign"=>"623AE90C9679729DDD7407DC7A1151B2",
# "result_code"=>"SUCCESS",
# "prepay_id"=>"wx2014111104255143b7605afb0314593866",
# "trade_type"=>"JSAPI"
# }
#如果成功就执行
if r.success? # => true
timeStamp = Time.now.to_i.to_s # 时间戳
nonceStr = SecureRandom.uuid.tr('-', '') # 随机字符串
# 要以下的数据生成支付签名
params = {
appId: r['appid'],
timeStamp: timeStamp,
nonceStr: nonceStr,
package: "prepay_id=#{r['prepay_id']}",
signType: 'MD5'
}
paySign = WxPay::Sign.generate(params) # 生成支付签名
# 返回支付数据给前端
{ "prepay_id" => r["prepay_id"], "timeStamp" => timeStamp, "nonceStr" =>
nonceStr, "paySign" => paySign, "return_code" => r["return_code"], "return_msg"
=> r["return_msg"] }
else # 错误就返回错误信息
{ "return_code" => r["return_code"], "return_msg" => r["return_msg"],
"result_code" => r["result_code"], "err_code" => r["err_code"], "err_code_des" =>
r["err_code_des"] }
end
3、前端支付函数
weiXinPay () {
let access_token = localStorage.getItem('jc_user_access_token')
let self = this
if (access_token !== null) {
this.$http.get('http://jiancan.me/api/u1/pay.json', { order_id: this.$route.params.order_id, access_token: access_token }).then(function (response) {
if (response.data.result_code !== undefined && response.data.result_code === 'FAIL') {
window.alert(response.data.err_code_des)
} else {
window.wx.chooseWXPay({
timestamp: response.data.timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: response.data.nonceStr, // 支付签名随机串,不长于 32 位
package: 'prepay_id=' + response.data.prepay_id, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)
signType: 'MD5', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: response.data.paySign, // 支付签名
success: function (res) {
// 支付成功后的回调函数
self.order.status_text = '已支付'
},
fail: function (res) {
console.log(res)
},
cancel: function (res) {
// 支付取消
}
})
}
}, function (response) {
this.showAlert(response.data.title, response.data.error, response.status)
})
}
}