此教程微信掃碼登錄 是打開新的二維碼頁面,掃完關閉二維碼頁面進入網站 建議參考之前先把官方文檔看下
本教程是通過yii框架
視圖層
第一步
設置微信掃碼的連接
<a class="third_item" id="wechat" target="_blank"><span class="icon-chat"></span></a>
第二步
設置回調和進入不同站點 回調redirect_uri 填寫你注冊的那個名字 也可以通過window.location.host 來獲取,
對于/login/callback 是返回你控制器login下的callback方法來進行業務處理
<script type="text/javascript">
$(document).ready(function()
{
var i =0;
//通過cookie進入不同頁面
var t1 = setInterval(function(){
var bindphone = getCookie('bindphone');
//這個是進入綁定手機頁面
if(bindphone == 128){
i=1;
delCookie('bindphone');
window.location.href = "/login/bindphone";
}
var login = getCookie('login');
//這個是進入個人中心頁面
if(login == 128){
i=1;
delCookie('login');
window.location.href = "/personal/info";
}
},1000);
if(i == 1){
window.clearInterval(t1);
}
//點擊微信掃碼登錄
$('#wechat').click(function(){
var url = encodeURIComponent("http://" + window.location.host + "/login/callback");
var appid = 'wx985c926fee0fb7a3';
//此state狀態是由你自己傳值的,隨便傳最好給個隨機數。記住這個值一定要給session,后面要驗證的
var state = "<?=$state?>";
window.open("https://open.weixin.qq.com/connect/qrconnect?appid="+appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_login&state="+state+"#wechat_redirect",'三立教育','width=400,height=700,left=30,top=10');
});
function getCookie(c_name){
if(document.cookie.length>0){
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1){
c_start=c_start + c_name.length+1 ;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function delCookie(name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
});
</script>
控制器層
public function actionCallback()
{
$code = $_GET["code"];
//state 是進行驗證處理的
$state = $_GET["state"];
$appid = "wx985c926fee0fb7a3";
$secret = "f73ecef46c7515cc7f53aac9369a1370";
//驗證的時候到了
if(empty($code) && (Yii::$app->session->get('state')!=$state)){
exit;
}
//將state的session清除
Yii::$app->session->remove('wx_state');
這個你直接復制好了。是獲取你微信的信息
//通過code獲得 access_token + openid
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
$jsonResult = file_get_contents($url);
$resultArray = json_decode($jsonResult, true);
$access_token = $resultArray["access_token"];
$openid = $resultArray["openid"];
//通過access_token + openid 獲得用戶所有信息,結果全部存儲在$infoArray里
$infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
$infoResult = file_get_contents($infoUrl);
$infoArray = json_decode($infoResult, true);
如果你后面頁面要使用到頭像和昵稱的話就設為session
Yii::$app->session->set('wechat_info', $infoArray);
下面條件是你數據庫的字段了。
這個是微信登陸的標識
$condition['oauth_id'] = $infoArray['unionid'];
這個說明是微信登陸
$condition['oauth_type'] = 3;
通過條件獲取學生的信息是否存在
$studentOauthObj = UserOauthInfo::find()->where($condition)->one();
if ($studentOauthObj) {
$studentOauthObj->last_time = $studentOauthObj->login_time;
$studentOauthObj->login_time = time();
$studentOauthObj->login_ip = CommonHelper::getIP();
$studentOauthObj->save();
$havePhone = UserStudentBase::find()
->where(['id' => $studentOauthObj->user_id])
->asArray()
->one();
// 將登錄信息和access token寫入session
$studentOauth = $studentOauthObj->toArray();
if (Yii::$app->session->get('loginRefer')) {
return $this->redirect(Yii::$app->session->get('loginRefer'))->send();
}
如果掃碼登錄過的話直接 跳轉到個人中心
setcookie("info", 128, time()+3600);
return $this->render('callback');
} else {
第一次掃碼綁定手機號碼 向數據庫寫入掃碼登錄記錄
setcookie("bindphone", 128, time()+3600);
return $this->render('callback');
}
}
//微信綁定手機
public function actionBindphone()
{
if (Yii::$app->request->isPost) {
$phone = Yii::$app->session->get('telephone');
$havePhone = UserStudentBase::getUserStudentinfoByPhone($phone);
$wechat_info = Yii::$app->session->get('wechat_info');
if(empty($havePhone)){
$db = Yii::$app->db;
$transaction = $db->beginTransaction();
try {
// add 表 user_student_base 一條記錄
$stuBase['phone'] = $phone;
$stuBase['register_time'] = time();
$db->createCommand()->insert('user_student_base', $stuBase)->execute();
// 查詢新增的學生id
$userBase = UserStudentBase::find()
->where(['phone' => $stuBase['phone']])
->asArray()
->one();
// add 表user_oauth_info 登錄信息
$userOauth['user_id'] = $userBase['id'];
$userOauth['user_type'] = 1; // 用戶類型:1=學員
$userOauth['oauth_type'] = 3; // 認證類型:1=手機號
$userOauth['oauth_id'] = $wechat_info['unionid'];
$userOauth['oauth_credential'] = $wechat_info['openid'];
$userOauth['login_time'] = time();
$userOauth['login_ip'] = CommonHelper::getIP();
$db->createCommand()->insert('user_oauth_info', $userOauth)->execute();
$transaction->commit();
// 成功跳轉到完善信息頁
return $this->redirect(Yii::$app->urlManager->createUrl(['register/completion']))->send();
} catch(\Exception $e) {
$transaction->rollBack();
return $this->redirect(Yii::$app->urlManager->createUrl(['register/index']))->send();
}
}else{
// add 表user_oauth_info 登錄信息
$userOauth['user_id'] = $havePhone['id'];
$userOauth['user_type'] = 1; // 用戶類型:1=學員
$userOauth['oauth_type'] = 3; // 認證類型:1=手機號
$userOauth['oauth_id'] = $wechat_info['unionid'];
$userOauth['oauth_credential'] = $wechat_info['openid'];
$userOauth['login_time'] = time();
$userOauth['login_ip'] = CommonHelper::getIP();
if(Yii::$app->db->createCommand()->insert('user_oauth_info', $userOauth)->execute()){
$whereCondition = [
'user_id' => $havePhone['id'],
'user_type' => 1,
'oauth_type' => 3,
];
$studentOauthObj = UserOauthInfo::find()->where($whereCondition)->one();
$studentOauth = $studentOauthObj->toArray();
CommonHelper::writeSessionOauth($havePhone, $studentOauth);
if (Yii::$app->session->get('loginRefer')) {
return $this->redirect(Yii::$app->session->get('loginRefer'))->send();
}
// 跳轉到個人中心
return $this->redirect(Yii::$app->urlManager->createUrl(['personal/info']))->send();
}
}
}
return $this->render('bindphone');
}
- Yii2使用Url組件
- Yii2的Html,Request組件詳解
- YII2.0框架, 多圖片上傳功能
- yii2-imagine配置
- 有潔癖的禁止默認YII自帶垃圾代碼(個人認為)、JS、CSS(新手教程)
- Yii2 API接口輸出統一Json和jsonp格式方法
- MySql 創建表的一些語句釋義
- Yii2聯合查詢(配合GridView)
- Yii 通用系統字典
- ArrayHelper的多維數組排序函數multisort,強大無比。
- 路由規則,在Url中替換使用'/'以外的符號連接
- 從excel文件中讀取表格內容,并批量寫入數據庫
- yii2注冊時驗證用戶名、郵箱等唯一性
- Yii2最全的實戰教程
- Composer安裝yii2-imagine 壓縮,剪切,旋轉,水印
- LinkPager增加總頁數 和總記錄數
- Yii2 獲取模塊名控制器名方法名
- Yii2使用yii2-adminlte+yii2-admin左側菜單子路徑不高亮問題又解
- 前端CSS框架
- Yii2 之 frontend 子模塊實踐之一:添加前后臺子模塊
- Yii2 之 frontend 子模塊實踐之二:構建子模塊的獨立配置
- Yii2 之 frontend 子模塊實踐之三:布局和語言配置
- 完美解決ajax驗證碼不刷新問題,讓驗證碼更加美觀,不修改任何源代碼
- yii2.0 表單小部件常用的默認選中
- Yii2 controller 傳值給layout
- yii2 dropDownList 二級和三級 聯動寫法
- 微信掃碼登錄 新窗口二維碼 掃完關閉二維碼頁面 進入登錄頁面
- yii2 實現 "上一篇,下一篇" 功能
- Yii 行為簡單應用
- SQL語句