PHP静默方式获取微信用户openid,单文件完成微信支付
2019-10-23 admin php 1676
通过跳转获取用户的openid,跳转流程如下:
1. 设置自己需要调回的url及其其他参数,跳转到微信服务器
https://open.weixin.qq.com/connect/oauth2/authorize
拼接成这样能获得code:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
2. 微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
3. 通过code调用微信链接获取access_token,再从工作平台获取openid;
静默方式获取时,需要把微信参数中scope的值变成snsapi_base !但是应用授权作用域,snsapi_base (只能获取用户openid)!
代码如下:
//获取用户微信openid public function GetOpenid(){ $appid = env('WEIXIN_KEY'); $appKey = env('WEIXIN_SECRET'); //通过code获得openid if (!isset($_GET['code'])){ //触发微信返回code码 $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://'; $uri = $_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']; if($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI']; $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$uri); $urlObj["appid"] = $appid; $urlObj["redirect_uri"] = "$baseUrl"; $urlObj["response_type"] = "code"; $urlObj["scope"] = "snsapi_base"; $urlObj["state"] = "STATE"."#wechat_redirect"; $buff = ""; foreach ($urlObj as $k => $v){ if($k != "sign") $buff .= $k . "=" . $v . "&"; } $bizString = trim($buff, "&"); $url = "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString; Header("Location: $url"); exit(); } else { //获取code码,以获取openid $code = $_GET['code']; $urlObj["appid"] = $appid; $urlObj["secret"] = $appKey; $urlObj["code"] = $code; $urlObj["grant_type"] = "authorization_code"; $buff = ""; foreach ($urlObj as $k => $v){ if($k != "sign") $buff .= $k . "=" . $v . "&"; } $bizString = trim($buff, "&"); $url = "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString; $options = array(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); if (!empty($options)) { curl_setopt_array($ch, $options); } //https请求 不验证证书和host curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $res = curl_exec($ch); curl_close($ch); //取出openid $data = json_decode($res,true); $openid = $data['openid']; //dd($openid); return $openid; } }
其中,appid和appKey需要填写,在公众号后台获取。
单元文件完成微信支付: