标签:
官方文档链接:http://mp.weixin.qq.com/wiki/4/9ac2e7b1f1d22e9e57260f6553822520.html
/** * 获取code */ public function actionGetCode() { $response_type = ‘code‘; $scope = ‘snsapi_userinfo‘; $conf = yii::$app->params[‘oauth_conf‘][‘oauth_wx_in‘]; $url = ‘https://open.weixin.qq.com/connect/oauth2/authorize?‘; $url .= ‘appid=‘.$conf[‘app_id‘]; $url .= ‘&redirect_uri=‘ . urlencode($conf[‘redirect_uri‘]); $url .= ‘&response_type=code‘; //这是微信公众号内获取 $url .= ‘&scope=snsapi_userinfo‘; //这是微信开放平台获取 // $url .= ‘&scope=snsapi_login‘; $url .= ‘&#wechat_redirect‘; header(‘Location:‘.$url); } /** * 获取access_token */ public function actionGettoken() { $conf = yii::$app->params[‘oauth_conf‘][‘oauth_wx_in‘]; $code = $_GET[‘code‘]; $url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?‘; $url .= ‘appid=‘.$conf[‘app_id‘]; $url .= ‘&secret=‘.$conf[‘app_key‘]; $url .= ‘&code=‘.$code; $url .= ‘&grant_type=authorization_code‘; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $data = curl_exec($ch); $data = json_decode($data,true); curl_close($ch); $access_token = $data[‘access_token‘]; $openid = $data[‘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); $res = curl_exec($ch); curl_close($ch); //返回的是一个数组,里面存放用户的信息 $res = json_decode($res,true); }
标签:
原文地址:http://www.cnblogs.com/xj76149095/p/5814366.html