一:微信授权
//用户授权
public function is_weixin(){ $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxxxxxxxxxxx&redirect_uri=http://xxx.xxxxx.com/index.php/privilege/getWeixinUser&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; redirect($url); }
上面的$url 中有5个get参数,前面2个get参数的值由我们指定,即appid 和 redirect_uri
appid="微信APP_ID"
redirect_uri="回调地址"
以上例子中 is_weixin 方法执行后浏览器会访问 redirect_uri所填写的地址,也就是会执行privilege中的getWeixinUser方法
public function getWeixinUser(){ $appid = "xxxxxxxxxxxxxxxxxxxxxxx"; $secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; $code = $_GET["code"]; $get_token_url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=‘.$appid.‘&secret=‘.$secret.‘&code=‘.$code.‘&grant_type=authorization_code‘; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$get_token_url); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); $res = curl_exec($ch); curl_close($ch); $json_obj = json_decode($res,true); //根据openid和access_token查询用户信息 $access_token = $json_obj[‘access_token‘]; $openid = $json_obj[‘openid‘]; $get_user_info_url = ‘https://api.weixin.qq.com/sns/userinfo?access_token=‘.$access_token.‘&openid=‘.$openid.‘&lang=zh_CN‘; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$get_user_info_url); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); $res = curl_exec($ch); curl_close($ch); //解析json $user_obj = json_decode($res,true); // array( // [openid] => o3ushwi5OiaBfCNA2F187BKPdnfU // [nickname] => xxx // [sex] => 1 // [language] => zh_CN // [city] => 深圳 // [province] => 广东 // [country] => 中国 // [headimgurl] => http://wx.qlogo.cn/mmopen/qibdIUkiaxRnic3D9icdBOonZxI3HibH1sP1xKchqhlDOnQibVuxhfNxHVvRJCrfz9jOkR5uZxsWiaToMIQQ0spkRNfG325j8NaGO67/0 // ); }
getWeixinUser方法中最终得到的$user_obj就是一个包含了用户微信基本信息的数组。
二:QQ授权
时间: 2024-10-18 02:54:00