微信授权


//微信授权
public function getOpenid()
{

$openid = Session('openid');
if (!$openid) {
if (!isset($_GET['code'])) {
$url = $this->getAuthorizeUrl();
Header("Location: $url");
exit();
} else {
$state = Session('state');
if ($state == $_GET['state']) {

$code=$_GET['code'];

$token = $this->getAccessToken($code);
$access_token=$token['access_token'];
$open=$token['openid'];
$acctoken="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$open&lang=zh_CN";
$userinfo = $this->httpsRequest($acctoken);
$info = json_decode($userinfo, true);
$openid = isset($token['openid']) ? $token['openid'] : '';
if ($openid) {
Session("openid", $openid);
}
}
}
}
return $info;
}
public function getAuthorizeUrl()
{
$redirect_uri ="http://lk.a40.com.cn/api.php/api/login";

$redirect_uri = urlencode($redirect_uri);

$state =rand(1000,9999);
Session('state', $state);
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe040024d0d8d6c1e&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
}

public function getAccessToken($code = '')
{

$ret ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxe040024d0d8d6c1e&secret=4ce2185589f1a7e0906341d10f8f42b4&code=$code&grant_type=authorization_code";
$token_info = $this->httpsRequest($ret);
$token_info = json_decode($token_info, true);
return $token_info;
}
public function httpsRequest($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}


posted @ 2020-07-23 16:19  php毛宏历的博客  阅读(160)  评论(0编辑  收藏  举报