## 1.token生成接口
#### 接口地址:
|接口地址|参数|备注|
|---|---|---|
|Route::post('api/:version/token/user','api/:version.user/getToken');|code|code为客户端调用wx.login后返回的代码|
#### token接口流程
1).访问微信openid接口获取openid
2).自定义规则生成token
3).信息写入缓存'token' 指向Openid uid scope
**token令牌生成接口**
![](https://box.kancloud.cn/cc4ad4ac7d8c9b4f2d7f49e2555e4b33_599x376.png)
~~~
class User
{
public function getToken($code=""){
//验证参数
// $code='061U2DeH1VExG80YQJaH1KjgeH1U2De9';
$code=request()->post('code');
(new TokenGet())->goCheck(['code'=>$code]);
$user=new UserToken($code);
$token=$user->getToken();
return ['token'=>$token];
}
.......
}
class UserToken extends Token
{
protected $code;
protected $wxAppId;
protected $wxAppSecrete;
protected $wxloginUrl;
public function __construct($code='')
{
$this->wxAppId=config('weixin.app_id');
$this->wxAppSecrete=config('weixin.app_secret');
$s=config('weixin.openid_url');
$this->wxloginUrl=sprintf($s,$this->wxAppId,$this->wxAppSecrete,$code);
}
public function getToken(){
// 获取openId
$openId=curl_request($this->wxloginUrl);
$openIdArr=json_decode($openId,true);
if(empty($openIdArr)){
throw new Exception('获取openId异常,微信内部错误');
}else{
if(array_key_exists('errcode',$openIdArr)){
// 抛出异常
throw new WxException([
'msg'=>$openIdArr['errmsg'],
'errCode'=>$openIdArr['errcode']
]);
}else{
//
return $this->openId2Token($openIdArr);
}
}
}
private function openId2Token($wx){
$openid=$wx['openid'];
//调用模型判断openid是否存在
$res=UserModel::findOpenId($openid);
if(!$res){
$user=UserModel::create([
'openid'=>$openid
]);
$uid=$user->id;
}else{
$uid=$res->id;
}
//生态token码
$token=$this->produceToken();
//写入缓存前的准备
$result=$wx;
$result['uid']=$uid;
$result['scope']=16;
$resultJ=json_encode($result);
$expire=config('security.token_expire');
//信息写入缓存中
$cacheRes=cache($token,$resultJ,$expire);
if(!$cacheRes){
// 抛出异常
throw new CateException([
'msg'=>'服务器缓存异常',
'errCode'=>1005
]);
}
return $token;
}
~~~
## 2.token验证接口