<?php
class Weichat
{
private $db;
private $webdb;
private $validator;
private $appid;
private $secret;
private $access_token;
function __construct()
{
global $db,$webdb;
$this->appid = "****";
$this->secret = "****";
}
/**
*@desc 创建跳转地址
*@param $redirect_uri 跳转地址
*@return string
*/
function create_jumpurl($redirect_uri)
{
$wx_auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize";
$wx_auth_url.= "?appid=".$this->appid;
$wx_auth_url.= "&redirect_uri=".$redirect_uri;
$wx_auth_url.= "&response_type=code";
$wx_auth_url.= "&scope=snsapi_userinfo";
$wx_auth_url.= "&state=STATE#wechat_redirect";
return $wx_auth_url;
}
/**
*@desc 获取微信的 access_token
*@param $code 微信平台返回的code
*@return access_token
*/
public function get_weixin_access_token($code)
{
$url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->secret."&code=".$code."&grant_type=authorization_code";
$curl = curl_init($url);
//檢查 curl 有無作用
if (! $curl) {
die( "Cannot allocate a new PHP-CURL handle" );
}
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); //SSL
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//這個若是沒設 , curl_exec($curl) 會直接印出來
curl_setopt ($curl, CURLOPT_HEADER, 0); // 得到回傳的HTTP頁面.
$data = curl_exec($curl);
curl_close($curl);
$data = json_decode($data);
$this->access_token = $data->access_token;
return $this->access_token;
}
/**
*@desc 从微信获取用户的头像,昵称
*@param $code 回调地址返回的code
*@return array
*/
public function get_weixin_info()
{
if (empty($this->access_token)) {
return array('status'=>'fall','msg'=>'授权失效,请重新授权!');
}
//拉取用户信息(需scope为 snsapi_userinfo)
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$this->access_token.'&openid=OPENID&lang=zh_CN';
$curl = curl_init($url);
//檢查 curl 有無作用
if (! $curl) {
die( "Cannot allocate a new PHP-CURL handle" );
}
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); //SSL
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//這個若是沒設 , curl_exec($curl) 會直接印出來
curl_setopt ($curl, CURLOPT_HEADER, 0); // 得到回傳的HTTP頁面.
$data = curl_exec($curl);
curl_close($curl);
$wx_user = json_decode($data,true);
return $wx_user;
}
}
2.使用Weichat获取用户信息
$code=$_GET['code'];
$usersWeiChat = new UsersWeichat();
if(!isset($code))
{
$redirect_uri = urlencode(INDEX_DOMAIN."?m=wechat&act=onecent&detail=christmas_index");
$wx_auth_url = $usersWeiChat->create_jumpurl($redirect_uri);
//跳转到微信获取code
header("Location:".$wx_auth_url);
}
$usersWeiChat->get_weixin_access_token($code);
$wx_user = $usersWeiChat->get_weixin_info();
$_SESSION['wx_info'] = $wx_user;
$_SESSION['parent_id'] = 0;
$_SESSION['m_openid'] = $wx_user['openid'];
$_SESSION['m_nickname'] = $wx_user['nickname'];
$_SESSION['img']=$wx_user['headimgurl'];