<input type="hidden" id="order_app_id" value="<%= @order_params[‘appId’] %>"/>
<input type="hidden" id="order_time_stamp" value="<%= @order_params[‘timeStamp’] %>"/>
<%= javascript_tag do %>
var orderParams = {
appId: "<%= @order_params[:appId] %>",
timeStamp: "<%= @order_params[:timeStamp] %>",
nonceStr: "<%= @order_params[:nonceStr] %>",
package: "<%= @order_params[:package] %>",
signType: "<%= @order_params[:signType] %>"
paySign: "<%= @order_params[:paySign] %>"
};
<% end %>
def wechat_pay_js_params
@params = {
appid: 'wx7d32820a35d2458c',
prepay_id: 'wx201506150843452f821f7b070705485969'
}
_prepay_id = @params[:prepay_id]
@params = {
appId: 'WxPay.appid',
timeStamp: Time.now.to_i.to_s,
nonceStr: SecureRandom.uuid.tr('-', ''),
package: "prepay_id=#{_prepay_id}",
signType: "MD5"
}
render json: @params
end
$.ajax({
url: '/users/wechat_pay_js_params',
dataType: 'JSON',
type: 'GET',
success: function(response){
alert(response.appId);
if(response && response.appId){
WeixinJSBridge.invoke('getBrandWCPayRequest', response, function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ) {
window.location.href = '/orders/'+ response.orderNumber;
}
//使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
//因此微信团队建议,当收到ok返回时,向商户后台询问是否收到交易成功的通知,若收到通知,前端展示交易成功的界面;若此时未收到通知,商户后台主动调用查询订单$
});
}
},
error: function(err){
alert('ajax: error')
alert(err);
console.log(err);
}
});
别忘记设置路由
Rails.application.routes.draw do
get '/users/wechat_pay_js_params', :to => "users#wechat_pay_js_params"
resources :users
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
<%= raw @params %>,
function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
window.location.href = '<%= wxpay_callback_order_path(@order) %>';
} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
window.location.href = '<%= order_path(@order) %>';
} else if (res.err_msg == "get_brand_wcpay_request:fail") {
alert('系统错误');
} else {
alert('未知错误');
}
}
);
你觉得哪种最优雅? 还有其他方法吗?