Login.php 2.0 KB
<?php


namespace app\api\controller;


use app\admin\model\Third;
use app\common\controller\Api;
use fast\Http;
use think\Config;
use think\Db;

/**
 * 登录
 */
class Login extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 登录
     *
     * @ApiTitle    (登录)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type=string, required=true, description="登录code")
     * @ApiParams   (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams   (name="avatar", type="string", required=true, description="头像")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function Login()
    {
        $code = $this->request->post('code');
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar');
        if (!$code || !$nickname || !$avatar){
            $this->error('后台所需参数缺失请完善参数');
        }
        $param = [];
        $param['js_code'] = $code;
        $param['grant_type'] = 'authorization_code';
        $param['secret'] = Config::get('site.secret');
        $param['appid'] = Config::get('site.appid');
        $wxapi = Http::get('https://api.weixin.qq.com/sns/jscode2session',$param);//请求openid
        $wxapi = json_decode($wxapi,true);
        if (isset($wxapi['errcode'])){
            $this->error($wxapi['errmsg']);
        }
        $third = new Third();
        $userid = $third->where('openid',$wxapi['openid'])->value('user_id');
        if ($userid){
            $this->auth->direct($userid);
            $this->success('登录成功',['token'=>$this->auth->getToken()]);
        }else{
            $userid = $this->auth->register($nickname,'','','',['avatar'=>$avatar]);
            if ($userid){
                $third->save(['openid'=>$wxapi['openid'],'user_id'=>$userid]);
                $this->success('登陆成功',['token'=>$this->auth->getToken()]);
            }else{
                $this->error('注册失败');
            }
        }
    }
}