这里记一下小程序登录 通过token令牌的步骤
大概思路
前端提交code码 后端通过文件配置获取app_id app_secret login_url 向微信服务器发送请求 这里可能返回值为空字符串 并不是错误 将值转化为数组判断信息 将获取到的openid session_key 以及用户枚举权限 通过tp5.1 cache 缓存 用一组随机字符串作为key 其他的作为value 保存后 返回给小程序端 token 就是key 这样每次登录就能获取用户token了
<?php
namespace app\weChatApi\model;
use app\weChatApi\model\User;
use think\cache;
class UserToken extends BaseModel
{
//定义成员属性变量
protected $LoginUrl;
protected $appid;
protected $app_secert;
protected $code;
public function __construct($code)
{
// parent::__construct($data);
$this->appid=config('web.app_id');
$this->app_secert=config('web.app_secret');
$this->code=$code;
$this->LoginUrl=sprintf(config('web.login_url'),$this->appid,$this->app_secert,$this->code);
}
public function getToken()
{
//发送http请求
// var_dump( $this->LoginUrl);
$result=curl_get($this->LoginUrl);
$wxresult=json_decode($result,true);
// halt( $wxresult);
if(empty($wxresult))
{
return show('400','微信服务器错误','38');
}
//判断微信服务器是否有errorcode
$no=array_key_exists('errorcode',$wxresult);
// halt($no);
if(!$no)
{
//生成令牌
return $this->grantToken($wxresult);
}
else
{
//返回错误
return show('400','微信服务器错误','');
}
}
//
public function grantToken($result)
{
$openid=$result['openid'];
//判断数据库中是否存在该用户
$is_null=User::getUserInfo($openid);
if($is_null)
{
//获取uid
// $res=User::getUserInfo()
$uid=$is_null->id;
}
else
{
//创建新用户
$res=User::saveUser($openid);
$uid=$res->id;
}
//准备需要缓存的数据
$cachedValue=$this->prepareCachedValue($result,$uid);
$token=$this->cacheValue($cachedValue);
return $token;
}
public function prepareCachedValue($result,$uid)
{
$cacheValue=$result;
$cacheValue['uid']=$uid;
$cacheValue['scope']=config('web.user');
return $cacheValue;
}
public function cacheValue($cacheValue)
{
$key=$this->generateToken();
$value=json_encode($cacheValue);
$expire_in=config('web.expire_in');
$res=cache($key,$value,$expire_in);
if(!$res)
{
return show('400','缓存错误','');
}
return $key;
}
//生成key
public static function generateToken()
{
$randChars=getRandChar(32); //生成32个随机字符串
//加强安全性 用三组字符串 md5
$timestamp=$_SERVER['REQUEST_TIME_FLOAT'];
//salt 盐 加密信息
$salt=config('secure.salt_token');
return md5($randChars.$timestamp.$salt);
}
}