記錄一下微信小程序開發,入坑比較晚,不過比較好入手,從接觸到做完項目大約有七天,還是挺好使的。
微信登錄
前端
var API_URL = "https://IP/wechat/isUserExist.php";
var that = this
wx.login({
success: function (res) {
if (res.code) {
var code = res.code;
wx.showToast({
title: '正在登錄...',
icon: 'loading',
duration: 10000
});
//請求服務器
wx.request({
url: API_URL,
data: {
js_code: code,
},
method: 'GET',
header: {
'content-type': 'application/json'
}, // 設置請求的 header
success: function (res) {
// success
wx.hideToast();
//用戶登錄全局變量 1已登錄 2未登錄
that.globalData.userSign=
res.data.result;
//將數據存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個異步接口
wx.setStorage({
key: "openid",
data: res.data.openid
})
console.log('服務器返回' + res.data.result);
console.log('服務器返回' + res.data.msg);
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
} else {
console.log('獲取用戶登錄態失敗!' + res.errMsg)
}
}
})
後端
<?php
require_once 'config.php';
header('Content-type: application/json; charset=UTF-8');
$APPID="wx-------------";
$SECRET="c78b------------------------";
$JSCODE="";
if(isset($_GET['js_code'])){
$JSCODE=$_GET['js_code'];
$url="https://api.weixin.qq.com/sns/jscode2session?appid=".$APPID
."&secret=".$SECRET."&js_code=".$JSCODE."&grant_type=authorization_code";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
$data = curl_exec($curl);
$array=json_decode($data,true);
curl_close($curl);
$openid=isset($array['openid'])?$array['openid']:$array['errcode'];
//openid不可用
if($openid=="40029"){
$response["result"] = 0;
$response["msg"] = "invalid code";
$response["openid"] = $openid;
echo json_encode($response);
}else{
$sql="select * from users where openid='$openid'";
$result = mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
//用戶已經註冊,返回openid
if ($num){
$response["result"] = 1;
$response["msg"] = "user exist";
$response["openid"] = $openid;
echo json_encode($response);
}
//用戶未註冊,返回openid
else{
$response["result"] = 2;
$response["msg"] = "user not exist";
$response["openid"] = $openid;
echo json_encode($response);
}
}
}
?>
微信登錄邏輯:
進入微信小程序,部分功能不需登錄即可瀏覽,部分功能需要登錄,此處我們記錄了 是否處於登錄狀態標記 that.globalData.userSign 1已登錄 2未登錄,
wx.setStorage({key: "openid",data: res.data.openid})
在需要獲取openid的地方使用如下代碼
wx.getStorage({
key: 'openid',
success: function (res) {
var openid = res.data;
}
})
openid作爲用戶唯一id,登錄成功後存儲在本地,作爲向服務器請求數據的唯一標記。