PHP

H5调起公众号JSAPI微信支付

一般在微信浏览器上的H5网页使用微信支付有两种方式

  • H5支付(跳转链接)
  • JSAPI(像小程序一样,不用跳转)

H5支付相对比较简单,一般都会喜欢使用这个跳链接的方式,但是H5支付在前期申请比较麻烦。不过其实JSAPI也很简单,也就5分钟的事情。不信看代码~

后端PHP:

//后端(使用插件yansongda)
//实例是简单的购买会员的业务
$combo_id = $this->request->param('combo_id');
$combo = ComboModel::where(['status'=>1,'id'=>$combo_id])->find();
if (empty($combo)) {
    $this->error('套餐不存在');
}
$order = [
    'order_sn' => cmf_get_order_sn(),
    'combo_id' => $combo['id'],
    'uid' => $this->user['id'] ?? 0,
    'price' => $combo['price'],
    'status' => 0,
    'create_time' => time()
];
OrderModel::create($order);
$wechat_config = Config::get('wechat_pay');
$config = [
    'app_id' => $wechat_config['app_id'],
    'mch_id' => $wechat_config['mch_id'],
    'key' => $wechat_config['key'],
    'notify_url' => 'https://'.$_SERVER['HTTP_HOST'].'/portal/Notice/wechat_notify',
    'http' => [
        'timeout' => 5.0,
        'connect_timeout' => 5.0,
    ],
];
$pay_order = [
    'out_trade_no' => $order['order_sn'],
    'total_fee' => $order['price']*100, //微信支付以分为单位
    'body' => $combo['name'],
    'openid' => $this->user['openid']
];
try {

    $pay = Pay::wechat($config);
    $pay_info = $pay->mp($pay_order);

    //返回的参数和小程序没啥两样
    $return = [
        'appId' => $pay_info->appId,
        'timeStamp' => $pay_info->timeStamp,
        'nonceStr' => $pay_info->nonceStr,
        'package' => $pay_info->package,
        'signType' => $pay_info->signType,
        'paySign' => $pay_info->paySign
    ];

    return api_json_return(0, 'success', $return);
} catch (Exception $e) {
    return api_json_return(500, $e->getMessage());
}

前端:

//点击购买
function tobuyvip()
{
    if (combo_id == '') {
        alert('请选择一个套餐');
    }

    $.post("{:url('portal/My/order')}", {combo_id:combo_id}, function(res) {
        if (res.code != 0) {
            alert(res.msg);
            window.location.reload();
        }
        var data = res.data;
        onBridgeReady(data.appId, data.timeStamp, data.nonceStr, data.package, data.signType, data.paySign);
    }, 'json');
}
//调起支付(只在微信浏览器有效,需要做更好的业务判断需要详细的阅读官方文档)
function onBridgeReady(appId, timeStamp, nonceStrm, package, signType, paySign){
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": appId,
            "timeStamp": timeStamp,
            "nonceStr": nonceStrm,
            "package": package,     
            "signType": signType,
            "paySign": paySign
        },
        function(res){
            //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
            console.log(res);
            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                window.location.href = "{:url('portal/My/index')}";
            }
        }
    ); 
}

后端记得处理支付回调

类似文章