This article mainly shares with you how to obtain openid on WeChat. First of all, it must be clear that if you want user authorization, you need to guide the user to your authorization page.
1. You must have a link
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
Instructions:
APPID is your WeChat official account ID, starting with wx
URI is your authorization entrance, usually under the main domain name pointed to by the WeChat official account. I put it here: http://www.xxoo.com/home/index/test
Pay attention to escaping, so URI=http%3A%2F%2Fwww.xxoo.com%2Fhome%2Findex% 2Ftest
2. This link can generate a QR code for others to scan. For example, go to this website: https://cli.im/
and fill in the link replaced above, and the generated code will be generated. Can.
3. Get the openid code
function test(){ $code=$_GET['code']; //echo htmlspecialchars($code);exit; $appid='wx**********'; //APPID $appsecret='**************'; //APP密钥 $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code'; $header [] = "content-type: application/json; charset=UTF-8"; $ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, $url ); //请求的方式是post curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "GET" ); // 禁用后cURL将终止从服务端进行验证 curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE ); //不检查证书 curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE ); //发送头部字段 curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header ); //告诉对方 自己的浏览器型号 curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' ); //即表示自动进行跳转抓取(如果URL发生了302重定向)继续抓取 curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 ); //自动重定向开启 curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 ); //发送的post参数 //curl_setopt ( $ch, CURLOPT_POSTFIELDS, $param ); //得到的结果不显示在屏幕上,作为变量结果储存 curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); $res = curl_exec ( $ch ); //如果运行错误,返回一个错误号 $flat = curl_errno ( $ch ); if ($flat) { $data = curl_error ( $ch ); } curl_close ( $ch ); //拿到了返回结果后json格式转化为可以使用的数组格式 $res = json_decode ( $res, true ); //$access_token=$res['access_token']; $openid=$res['openid']; //跳转到抽奖页面 header('Location: http://wx.xxoo.com/test/index/index/openid/'.$openid); }
This way you can identify each WeChat user by getting the openid.
Related recommendations:
How to obtain openid and user information in WeChat mini program
A case of obtaining session_key and openid in WeChat mini program (Picture)
The above is the detailed content of How to get openid on WeChat. For more information, please follow other related articles on the PHP Chinese website!