微信開放平台
https://open.weixin.qq.com/cgi-bin/index?t=home/index&lang=zh_CN
微信登陸網站——Oauth class
<?php
class Oauth{
private $errorMsg;
private $appMsg;
public function __construct(){
$this->errorMsg = array(
"20001" => "<h2>配置檔案損壞或無法讀取,請重新執行intall</h2>",
"30001" => "<h2>The state does not match. You may be a victim of CSRF.</h2>",
"50001" => "<h2>可能是伺服器無法請求https協定</h2>可能未開啟curl支援,請嘗試開啟curl支援,重新開機web伺服器,如果問題仍未解決,請聯系我們"
);
$this->appMsg = array(
"appid" => "appid",//微信開放平台申請的網站應用的appid和secret
"secret" => "secret",
"callback" => "http://www.jenny.com/wechatcallback"//回調位址,一定要加http或者https;
);
}
public function wechat_login(){
//-------生成唯一随機串防CSRF攻擊
$state = md5(uniqid(rand(), TRUE));
$_SESSION['state'] = $state;
//-------構造請求url
$callback = urlencode($this->appMsg['callback']);
$login_url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->appMsg['appid'] ."&redirect_uri=".$callback."&response_type=code&scope=snsapi_login&state=".$state."#wechat_redirect";
header("Location:$login_url");
}
public function wechat_callback(){
$state = $_SESSION['state'];
//--------驗證state防止CSRF攻擊
if($_GET['state'] != $state){
$this->showError("30001");
}
//-------請求參數清單
if(!empty($_GET['code'])){
//dosomething
$code = $_GET['code'];
$curl = curl_init();
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appMsg['appid']."&secret=".$this->appMsg['secret']."&code=".$code."&grant_type=authorization_code";
curl_setopt($curl, CURLOPT_URL, $url); // 要通路的位址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 對認證證書來源的檢查
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 擷取的資訊以檔案流的形式傳回
$result = curl_exec($curl);
curl_close($curl);
if( !empty($result)){
$result_array = json_decode($result,true);
$_SESSION['token'] = $result_array['access_token'];
$_SESSION['openid'] = $result_array['openid'];
header("location:/user/third?provider=wechat");
}else{
header("location:/login");
}
}else{
header("location: /login");
}
}
public function showError($code, $description = '$'){
echo "<meta charset=\"UTF-8\">";
if($description == "$"){
die($this->errorMsg[$code]);
}else{
echo "<h3>error:</h3>$code";
echo "<h3>msg :</h3>$description";
exit();
}
}
}
?>
微信登陸網站——callback控制檔案
require_once($this->lib_wechatoauth_path . 'wechatoauth.php');
$oauth = new Oauth();
$wechat_token = $oauth->wechat_callback();
微信登陸網站——login控制檔案
require_once($this->lib_wechatoauth_path . 'wechatoauth.php');
$oauth = new Oauth();
$wechat_token = $oauth->wechat_login();