## 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令牌生成接口**

~~~
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驗證接口