微信小程序用戶授權,以及判斷登錄是否過期的方法
初始界面:

判斷用戶是否過期(如果未過期則重新登錄):

獲取用戶信息:

獲取用戶的信息并在前臺顯示:

主要實現(xiàn)兩個功能:
①判斷登錄是否過期,如果過期則就重新登錄,如果沒過期就提示未過期
②獲取用戶的信息,并在前臺顯示
index.wxml
<button bindtap="login">登錄</button>
<button bindtap="checksession">登錄是否過期</button>
<button open-type="getUserInfo" bindgetuserinfo="info">點擊授權</button>
<text>{{city}}</text>
<text>{{country}}</text>
<text>{{nickName}}</text>
<text>{{province}}</text>
index.js
//index.js
//獲取應用實例
const app = getApp()
Page({
data: {
city:'',
country:'',
nickName:'',
province:''
},
//發(fā)起http請求
login:function(){
wx.login({
success:function(res){
console.log(res.code)
//發(fā)送請求
wx.request({
url: '自己的域名', //僅為示例,并非真實的接口地址
data: {
code:res.code
},
header: {
'content-type': 'application/json' // 默認值
},
success(res) {
console.log(res)
}
})
}
})
},
//驗證登錄是否過期
checksession:function(){
wx.checkSession({
success:function(res){
console.log(res,'登錄未過期')
wx.showToast({
title: '登錄未過期啊',
})
},
fail:function(res){
console.log(res,'登錄過期了')
wx.showModal({
title: '提示',
content: '你的登錄信息過期了,請重新登錄',
})
//再次調(diào)用wx.login()
wx.login({
success: function (res) {
console.log(res.code)
//發(fā)送請求
wx.request({
url: '自己的域名', //僅為示例,并非真實的接口地址
data: {
code: res.code
},
header: {
'content-type': 'application/json' // 默認值
},
success(res) {
console.log(res)
}
})
}
})
}
})
},
//獲取用戶的信息
info:function(){
var that=this
wx.getUserInfo({
success:function(res){
console.log(res.userInfo)
var city = res.userInfo.city
var country = res.userInfo.country
var nickName = res.userInfo.nickName
var province = res.userInfo.province
that.setData({
city:city,
country:country,
nickName:nickName,
province:province
})
}
})
}
})
index.php
<?php
//聲明code,用來接收前臺傳過來的code
$code=$_GET['code'];
//獲取到appid
$appid="xxxxxxxxxxx"; //自己的appid
$secret="xxxxxxxxxxxx"; //自己的secret
$api="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code"; //可去小程序開發(fā)文檔中查看這個鏈接
//發(fā)送的代碼
function httpGet($url){
$curl=curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_URL, $url);
$res= curl_exec($curl);
curl_close($curl);
return $res;
}
$str=httpGet($api);
echo $str;
?>
關于這個php文件的說明:
①獲取appid和secret:

②當你點擊登錄的時候,出現(xiàn)這些東西就說明php文件調(diào)用成功

③登錄憑證校檢地址(該里面的參數(shù)即可):

④域名要合法
在小程序平臺上:

在web開發(fā)者工具里:

以上所述是小編給大家介紹的微信小程序用戶授權及判斷登錄是否過期詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
JavaScript 定義function的三種方式小結(jié)
JavaScript中定義function有以下三種方式.2009-10-10
javascript實現(xiàn)table選中的行以指定顏色高亮顯示的方法
這篇文章主要介紹了javascript實現(xiàn)table選中的行以指定顏色高亮顯示的方法,實例分析了javascript操作table表格元素與相關樣式的技巧,需要的朋友可以參考下2015-05-05
JS localStorage實現(xiàn)本地緩存的方法
JS localStorage實現(xiàn)本地緩存的方法,需要的朋友可以參考一下2013-06-06

