protected $appid = '****************'; //微信 appid
protected $appsecrt = '******************'; //微信 appsecrt
//-----------靜默授權 (不能獲取用戶的昵稱、頭像,要獲取用戶的昵稱和頭像使用 用戶確認授權)
public function getBaseInfo()
{
//獲取code
$redirect_uri = urlencode("http://www.******.com/index/index/getWxCode");//回調地址
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=123#wechat_redirect"; //state 可任意
$this->redirect($url, 302);// tp5的重定向方法
}
public function getWxCode()
{
//獲取access_token
//獲取openID
$code = $_GET['code'];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecrt . "&code=$code&grant_type=authorization_code";
$r = http_curl($url);
$openid = $r['openid'];
$access_token = $r['access_token'];
var_dump('access_token是:' . $access_token . '=========' . 'openid是:' . $openid);
}
//-------------------------------end-----------------------------------
//-----------用戶確認授權
public function getCodeUserInfo($temp)
{
//獲取code
$redirect_uri = urlencode("http://zs.zs13ce.gx.cn/index/index/getWxUserInfo");//回調地址
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=$temp&connect_redirect=1#wechat_redirect"; //state 可任意
$this->redirect($url, 302);// tp5的重定向方法
}
public function getWxUserInfo()
{
//換取網頁授權access_token
//獲取openid
$code = $this->request->param('code');
$state = $this->request->param('state');
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecrt . "&code=" . $code . "&grant_type=authorization_code";
$rjson = http_curl($url);
$access_token = $rjson['access_token'];//得到access_token ( 網頁的)
$openId = $rjson['openid'];//得到openid
$userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=" . $this->appid . "&lang=zh_CN";//獲取用戶信息
$result = http_curl($userInfoUrl);
// var_dump($result);//打印用戶詳細信息
// die;
if (empty($result)) {
echo 0;die;
}
$user = Db::name("user")->where("openid", $result["openid"])->find();
if (empty($user)) {
//如果表里沒有,則插入
}
$this->_user = $user;
$this->setIsSq($user);
$this->redirect(url($state), 302);// tp5的重定向方法
}
function http_curl($url, $data=[])
{
$curl = curl_init();//初始化
curl_setopt($curl, CURLOPT_URL, $url);//設置抓取的url
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);// https請求 不驗證證書和hosts
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_HEADER, 0);// 設置頭文件的信息作為數據流輸出 設置為1 的時候,會把HTTP信息打印出來 不要http header 加快效率
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//設置獲取的信息以文件流的形式返回,而不是直接輸出。 如果設置是0,打印信息就是true
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data,true));
$data = curl_exec($curl);//執行命令
$result = json_decode($data, true);
if ($data == false) {
echo "Curl Error:" . curl_error($curl);
exit();
}
curl_close($curl);//關閉URL請求
return $result;
}