1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| public function token(){ $code=input('post.code'); $ch=curl_init(); $appid="wxad72f080afae7980"; $secret="ebf7abfded334145e4de09d7ec2c3969"; $url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_HEADER,0);
$output=curl_exec($ch); if($output===false){ echo "CURL Error:".curl_error($ch); } curl_close($ch);
$curl_result=json_decode($output,true);
if(isset($curl_result['errcode'])){ return json([ 'status'=>0, 'msg'=>' Invalid parameter' ],400); } $model=User::get(['openid'=>$curl_result['openid']]);
if($model){ $userid=$model->id; }else{ $data=array( 'openid'=>$curl_result['openid'], 'nickName'=>input('post.nickName'), 'avatarUrl'=>input('post.avatarUrl') ); $model=User::create($data); $userid=$model->id; } $token=$this->generalToken(32); User::where('id',$userid)->update(['token'=>$token]); return[ 'token'=>$token ];
} public function generalToken($length){ $str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $result=""; for($i=0;$i<$length;$i++){ $result.=$str[rand(0,61)]; } $time=$_SERVER['REQUEST_TIME']; return md5($result.$time); }
|