1. 程式人生 > >微信瀏覽器網頁授權獲取使用者openid 微信瀏覽器支付

微信瀏覽器網頁授權獲取使用者openid 微信瀏覽器支付

### 配置
1. appid
2. appsecret
3. merchid
4. apikey
5. 微信公眾號,介面許可權,網頁授權域名填寫

### 獲取code
```
function getWxCode($url){
    $appid = "";
    $appsecret = "";
    $domain = input('server.REQUEST_SCHEME'). '://' . input('server.SERVER_NAME');
    //url填寫可當前訪問url
    $redirect_url = $domain."/".$url;
    $redirect_url = urlencode($redirect_url);

    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//    dump($url);exit;
//    $result = curl_get($url);
//    return $result;
    return $url;
}
//引導使用者訪問此url

```
### 根據code獲取openid
```
$param =request()->param();
$code = $param['code'];
function returnAsskey($code)
{
    $appid = “”;
    $appsecret = "";
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';

    $ass_key = curl_get($url);
    return $ass_key;
}
//工具函式
function curl_get($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    return json_decode($data,1);//對資料進行json解碼
}
```
### 支付
```
//根據後臺統計下單後返回的資料喚起微信支付

data.timeStamp = String(data.timeStamp);
WeixinJSBridge.invoke('getBrandWCPayRequest', {
    'appId': data.appid ? data.appid : data.appId,
    'timeStamp': data.timeStamp,
    'nonceStr': data.nonceStr,
    'package': data.package,
    'signType': data.signType,
    'paySign': data.paySign,
}, function(res) {
    if(res.err_msg == 'get_brand_wcpay_request:ok') {
//                                    location.href = "{php echo app_url('pay/cash')}&orderno="+orderno+"&paytype="+paytype+"&done=1";
        alert("支付成功");
        location.reload();
    } else {
        /*$.post("{php echo app_url('pay/paytype')}",{orderno:orderno,remark:remark,othername:othername,op:"ajax",checkpay:"8"},function(m){
         $.toast("已取消支付");
         },"json");*/
        alert("已取消支付1");
    }
});

```