PHP代码 如何网页获取用户的openid
public function getOpenid($appid, $appsecret) { $SERVER_NAME = $_SERVER['SERVER_NAME']; $REQUEST_URI = $_SERVER['REQUEST_URI']; $redirect_uri = urlencode('http://' . $SERVER_NAME . $REQUEST_URI); $code = $_GET['code']; if (! $code) { // 网页授权当scope=snsapi_userinfo时才会提示是否授权应用 $autourl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect"; header("location:$autourl"); } else { // 获取openid $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code"; $row = $this->posturl($url); return ($row['openid']); } } public function posturl($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $jsoninfo = json_decode($output, true); return $jsoninfo; }
//使用方法: $appid = "wx18a554232c71513b"; $secret = "662xxxxxxf9xxxxxxb6xxxxxx44xxxxx"; $openid= $this->getOpenid($appid, $secret);
当网页授权的scope=snsapi_userinfo时才会出现下面的界面:
非常感谢大神的指点,让我走了很少的弯路,我也想让看到的朋友少走弯路哈。
(本人微信号:Liberty-bcy)如果,你正在埋怨命运不眷顾,那请记住:命,是失败者的借口;运,是成功者的谦词。