在接入微信支付前,需要准备以下内容:
# Gemfile
gem 'wx_pay'
# config/initializers/wx_pay.rb
WxPay.appid = 'YOUR_APPID'
WxPay.key = 'YOUR_KEY'
WxPay.mch_id = 'YOUR_MCH_ID'
WxPay.apiclient_cert_path = 'path/to/apiclient_cert.p12'
WxPay.apiclient_cert_password = 'cert_password'
def create_payment
params = {
body: '商品描述',
out_trade_no: "order_#{Time.now.to_i}",
total_fee: (product.price * 100).to_i, # 金额以分为单位
spbill_create_ip: request.remote_ip,
notify_url: 'https://example.com/wx_notify',
trade_type: 'JSAPI',
openid: current_user.wx_openid
}
result = WxPay::Service.invoke_unifiedorder(params)
if result.success?
# 生成支付参数
payment_params = {
appId: WxPay.appid,
timeStamp: Time.now.to_i.to_s,
nonceStr: SecureRandom.hex(16),
package: "prepay_id=#{result['prepay_id']}",
signType: 'MD5'
}
payment_params[:paySign] = WxPay::Sign.generate(payment_params)
render json: { payment_params: payment_params }
else
render json: { error: result['return_msg'] }, status: :unprocessable_entity
end
end
def wx_notify
result = Hash.from_xml(request.body.read)['xml']
if WxPay::Sign.verify?(result)
# 处理支付成功逻辑
order = Order.find_by(out_trade_no: result['out_trade_no'])
order.update(status: 'paid') if order
render xml: { return_code: 'SUCCESS', return_msg: 'OK' }.to_xml(root: 'xml', dasherize: false)
else
render xml: { return_code: 'FAIL', return_msg: '签名失败' }.to_xml(root: 'xml', dasherize: false)
end
end
本文采用 署名-非商业性使用-相同方式共享 4.0 国际 许可协议,转载请注明出处。