这两天要被request请求搞死了,一直从服务器那边请求不到session,后面看来网上的解决办法才知道少了session_id,下面是我的解决方式:
服务器php:
public function index(){
//从微信客户端获取小程序的code
$code =input('code');
if (!$code) {
die();
}
// //用appod和secre以及code向微信服务器获取openid和session_key
$url="https://api.weixin.qq.com/sns/jscode2session?appid=你的APPID&secret=你的小程序密钥&js_code=".$code."&grant_type=authorization_code";
$res=file_get_contents($url);
$res=json_decode($res,true);
$session_key=$res['session_key'];
$openid=$res['openid'];
// //设定一个16位随记字符串
$str="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
$max=strlen($str)-1;
$third_session='';
// //拼接
for($i=0;$i<16;$i++){
$third_session .=substr($str, rand(0,$max),1);
}
//拼接openid和session_key
$value=$openid;
//写入session
session($third_session,$value);
$data=[$third_session,session_id(),$openid];
echo json_encode($data);
// echo "$session_key";
}
public function check(){
$thirdsession=input('thridsession');
//获取session值
$thirdsession2=session($thirdsession);
if ($thirdsession2) {
echo 'session存在';
}
else{
echo 'session不存在';
}
}
小程序:
//得到thridsession和session_id
var thridsession=wx.getStorageSync('thridsession');
//如果thridsession存在则取服务器验证登入是否失效
var session_id=wx.getStorageSync('session_id');
if(thridsession){
console.log('thridsession存在');
wx.request({
url: 'https://www.ctychen.cn/wx/index/Login/check',
data:{
'thridsession':thridsession
},
//加上session_id判断是同一绘画操作
header: { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + session_id },
success:function(data){
console.log(data)
}
})
}else{
console.log('thridsession不存在');
//如果session不存在就去执行登入操作
wx.login({
success:function(res){
wx.request({
url: 'https://www.ctychen.cn/wx/index/Login/index',
data:{
'code':res.code
},
success:function(data){
thridsession=data.data[0];
session_id=data.data[1];
console.log(thridsession);
console.log(session_id);
//两者都存在的话就存入stroge
if(thridsession && session_id ){
wx.setStorageSync('thridsession', thridsession);
wx.setStorageSync('session_id', session_id);
}
}
})
}
})