已经写过,这次用到了就有写了遍。。
//获取openid
public function wxlogin(){
$appid= Env::get('wx_chat.wx_appid_fwh');
$appsecret= Env::get('wx_chat.wx_secret_fwh');
$Token=Env::get('wx_chat.wx_token_fwh');
// $Crypt = $wechat['EncodingAESKey'];
$redirect_url= 'http://'.$_SERVER['HTTP_HOST'].'/index/wxlogin/wxlogin';
$baseurl = urlencode($redirect_url);
$snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YOUBUS#wechat_redirect';
//2.静默授权,获取code
$code=$_GET['code'];
if( !isset($code) ){
header('Location:'.$snsapi_base_url);
}
//3.通过code换取网页授权access_token和openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
$oauth2 = $this->http_curl($oauth2Url);
//accestoken
$access_token = $oauth2["access_token"];
//openid
$openid = $oauth2['openid'];
session('access_token', $access_token);
session('openid', $openid);
$this->get_userinfo($access_token,$openid);
return $openid;
}
public function get_userinfo($access_token,$openid){
print_r($openid);
$userinfo_url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$userinfo = $this->http_curl($userinfo_url);
print_r($userinfo);
}
public function getcode(){
$appid= Env::get('wx_chat.wx_appid_fwh');
$redirect_url= 'http://'.$_SERVER['HTTP_HOST'].'/index/wxlogin/wxlogin';
$baseurl = urlencode($redirect_url);
$snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YOUBUS#wechat_redirect';
header("location:".$snsapi_base_url);
}
public function http_curl($url){
//用curl传参
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//关闭ssl验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch,CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}