微信支付(公众号支付)

以下流程是以rails项目为准

Gem源添加

gem 'wx_pay'
gem 'weixin_authorize'
gem agent_orange

配置文件初始化
wx_pay.rb

$client = WeixinAuthorize::Client.new(WxPay.appid, WxPay.appsecret)
# required
# dunkhome config data
WxPay.appid = '此处配置微信公众号ID'
WxPay.key = '此处配置微信支付商户API密钥' # 微信支付商户平台--> API安全--> API密钥
WxPay.mch_id = '微信支付商户号'
WxPay.debug_mode = true # default is true

# cert, see https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3
# using PCKS12
#WxPay.set_apiclient_by_pkcs12(File.read(pkcs12_filepath), pass)

# if you want to use "generate_authorize_req" and "authenticate"
WxPay.appsecret = '此处配置微信公众要密钥' # 目的:获取用户 授权信息

# optional - configurations for RestClient timeout, etc.
WxPay.extra_rest_client_options = {timeout: 2, open_timeout: 3}

Use
Helper Method
 def get_prepay_id(request_ip, open_id)
    wx_params = {  
    :out_trade_no => "test_no_01",
    :body => "test",
    :total_fee => 1, # 需要转换为分
    :spbill_create_ip => request_ip,
    :notify_url => "http://example.com/notify",
    :trade_type => "JSAPI",
    :nonce_str => "随机子串",
    :openid => open_id   # 用户公众号唯一id
    } 
    res = WxPay::Service.invoke_unifiedorder(wx_params)
    return res.success? ? res["prepay_id"] : nil 
end
Action
      #支付参数
      @wx_pay = {
      :appId => WxPay.appid,
      :timeStamp => Time.now.to_i.to_s,    
      :nonceStr => SecureRandom.hex,
      :package => "prepay_id=#{@order.get_prepay_id(request.ip, open_id)}",
      :signType => "MD5"
      }
      @pay_sign = WxPay::Sign.generate(@wx_pay)    # 签名生成
      @sign_package = Wechat.client.get_jssign_package(request.url)
View WeixinJS initialize
  wx.config({
  debug: false,
  appId: "<%= @sign_package['appId'] %>",
  timestamp: "<%= @sign_package['timestamp'] %>",
  nonceStr: "<%= @sign_package['nonceStr'] %>",
  signature: "<%= @sign_package['signature'] %>",
  jsApiList: ['chooseWXPay' ]
});
$pay.click(function(){
  wx.chooseWXPay({
    "timestamp": "<%= @wx_pay[:timeStamp] %>",
    "nonceStr": "<%= @wx_pay[:nonceStr] %>",
    "package": "<%= @wx_pay[:package] %>",
    "signType": "<%= @wx_pay[:signType] %>",
    "paySign": "<%= @pay_sign %>", // 支付签名
    success: function (res) {
      // 支付成功回调;
    }
  });
  return false;
});

流程到这里就ok了,按照开发者自己的设计,点击支付时,就能唤起微信的支付了。
PS:转载记得注明出处哦!

推荐阅读更多精彩内容