记录一下微信小程序开发,入坑比较晚,不过比较好入手,从接触到做完项目大约有七天,还是挺好使的。
微信登录
前端
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,登录成功后存储在本地,作为向服务器请求数据的唯一标记。