php-微信授權登錄


原生php 微信授權登錄:

index.php頁面:

<?php

session_start();

if($_SESSION['openid']){
exit('已經授權登錄過了。。。');

} {
include_once "weixin.class.php";
$wx_login = new Wxlogin();
echo '1';exit;
$userinfo = $wx_login->getUserInfo();

if($userinfo['openid']){

$_SESSION['openid'] = $userinfo['openid'];

var_dump($userinfo);

} else {
exit('授權失敗');
}
}

 

weixin.class.php 頁面:

<?php
class Wxlogin{

//private $login_page_url = "https://open.weixin.qq.com/connect/qrconnect?";//微信登錄界面
private $login_page_url = "https://open.weixin.qq.com/connect/oauth2/authorize?";//微信登錄界面
private $get_accessToken_url = "https://api.weixin.qq.com/sns/oauth2/access_token?";//后去token的url
//private $get_openId_url = 'https://graph.qq.com/oauth2.0/me';//獲取openid的url
private $get_user_info = "https://api.weixin.qq.com/sns/userinfo?";//獲取用戶信息的url
private $app_id = 'wxefb884843af5be20';
private $app_key = 'fcf28113f7b223622544459a25c56daa'; //app_secret
public $redirect_url = 'www.demo2.php';
private $access_token;

//QQ登錄頁面
private function get_wx_login_page()
{
$state = md5(rand(1,1000));
$query = [
'appid' => $this->app_id,
'redirect_uri' => $this->redirect_url,
'response_type' => 'code',
'scope' => 'snsapi_userinfo',
'state' => $state,
];
$_SESSION['state'] = $state;//保存state驗證

$url= $this->login_page_url.http_build_query($query).'#wechat_redirect';

header("Location:$url");
exit;
}

//獲取access_token
private function get_code()
{

//獲取code
@$code = $_GET['code'];
if(!$code){
$this->get_wx_login_page();
}
$state = $_GET['state'];
/*
if($state != $_SESSION['state']){
echo "state is wrong!";
exit;
}
*/
$_SESSION['state'] = null;
$query = [
'grant_type' => 'authorization_code',
'code' => $code,
'secret' => $this->app_key,
'appid' => $this->app_id,
];
return $this->get_curl($this->get_accessToken_url, http_build_query($query));

}

//獲取token
private function get_token_info()
{
//獲取access_token
/* {
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
} */
$data = json_decode($this->get_code(),true);
//參數組裝數組


$this->access_token = $data["access_token"];

$array = array(
'access_token' => $data["access_token"],
'openid' => $data['openid'],
);

return $this->get_curl($this->get_user_info, http_build_query($array));
}

//獲取openid&&獲取用戶信息
public function getUserInfo()
{
$data = $this->get_token_info();


$data = json_decode($data, true);
$data['access_token'] = $this->access_token;
return $data;
}

//curl GET請求
private function get_curl($url,$query)
{
$url_request = $url.$query;
$curl = curl_init();

//設置抓取的url
curl_setopt($curl, CURLOPT_URL, $url_request);
//設置頭文件的信息作為數據流輸出
curl_setopt($curl, CURLOPT_HEADER, 0);
//設置獲取的信息以文件流的形式返回,而不是直接輸出.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//執行命令
$data = curl_exec($curl);
//關閉URL請求
curl_close($curl);
return $data;

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM