Rails 微信小程序支付

July 08, 2017 · 3 mins read

Rails 微信小程序支付

Prepare

  1. 在公众平台注册一个小程序账号 点击入口 微信公众平台.png

  2. 申请微信支付 申请支付.jpg

  3. 配置商户信息 申请微信支付成功后,登陆商户平台(pay.weixin.qq.com)进入账户中心,设置微信商户的API Key与下载证书

  4. 配置Https服务器 可以参考:使用 Let’s Encrypt 加密(HTTPS)你的网站

Rails 服务端

Installation gem

Add this line to your Gemfile:

gem 'wx_pay'

And then execute:

bundle install

Config

Create config/initializers/wx_pay.rb and put following configurations into it.

# required
WxPay.appid = 'YOUR_APPID'
WxPay.key = 'YOUR_KEY'
WxPay.mch_id = 'YOUR_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 = 'YOUR_SECRET'

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

Request payment for miniapp

  # => {
  #    :appId=>"wx6743cf23566a7991",
  #    :package=>"prepay_id=wx20170703182440e40cd68a2e0757840067",
  #    :nonceStr=>"dpKt531nHFruKbfu",
  #    :timeStamp=>"1499077480",
  #    :signType=>"MD5",
  #    :paySign=>"183385DC3B435FF2164FB0C445DAACCD"
  #  }
  def request_payment
    unifiedorder = WxPay::Service.invoke_unifiedorder unifiedorder_params
    js_payment_params = {
      prepayid: unifiedorder[:raw]["xml"]["prepay_id"],
      noncestr: unifiedorder[:raw]["xml"]["nonce_str"]
    }
    result = WxPay::Service.generate_js_pay_req js_payment_params
    result
  end

  # official document for detailed request params and return fields
  # https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
  def unifiedorder_params
    {
      body: '商品订单支付',
      out_trade_no: 'test003',
      total_fee: 1,
      spbill_create_ip: '127.0.0.1',
      notify_url: 'https://youdomain/notify',
      trade_type: 'JSAPI',
      openid: 'OPENID'
    }
  end

Wechat nimiapp

调用服务端的接口获取到必要的参数

{
  :package=>"prepay_id=wx20170703182440e40cd68a2e0757840067",
  :nonceStr=>"dpKt531nHFruKbfu",
  :timeStamp=>"1499077480",
  :signType=>"MD5",
  :paySign=>"183385DC3B435FF2164FB0C445DAACCD"
}

将上述服务端返回对应到小程序的参数中去:

wx.requestPayment({
  'timeStamp': '1499077480',
  'nonceStr': 'dpKt531nHFruKbfu',
  'package': 'prepay_id=wx20170703182440e40cd68a2e0757840067',
  'signType': 'MD5',
  'paySign': '183385DC3B435FF2164FB0C445DAACCD',
  'success': function success(res) {
    wx.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 2000
    });
  },
  'fail': function fail(res) {
    console.log("支付失败");
  }
});