您现在的位置是:首页 > ThinkPHP

李清波 2019-06-01 ThinkPHP 241

小程序不需要授权的简单登录api接口

下面以Thinkphp框架为示例,写一个小程序免授权的登录接口,通过小程序穿过来的code直接登录。


简单登录模式

// 简单登录
public function simple(){
    $xcx = Config::get('config_api.xcx_user');
    $code = input('code');
 
    // expires_in,openid,session_key
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$xcx['app_id']."&secret=".$xcx['app_secret']."&js_code=".$code."&grant_type=authorization_code";
    $content = file_get_contents_by_curl($url);
    $res = object_array(json_decode($content)); //返回openid,expires_in,session_key

    if(!isset($res)) return json(['code'=>1,'msg'=>'请求失败','res'=>$res]);
    if(isset($res['errcode'])){
        return json(['code'=>1,'errmsg'=>$res['errmsg']]);
    }

    if(empty($res['openid'])) return json(['code'=>1,'msg'=>'获取openid错误']);

    $userInfo = UserModel::where('openid_xcx',$res['openid'])->find();
    
    if(empty($userInfo)){
        $createData['nickname'] = '';
        $createData['avatar_url'] = '';
        $createData['sex'] = '';
        $createData['unionid'] = $unionid;
        $createData['openid_xcx'] = $res['openid'];
        $createData['referrer'] = $referrer;
        $createData['last_login_time'] = time();
        $createData['last_login_ip'] = time();
        $createData['login_count'] = 1;
        $createData['subscribe'] = $subscribe;
        $createData['auth'] = 0;
        $userObj = UserModel::createUser($createData);
        $userInfo = UserModel::get($userObj->id);
    }

    return json(['code'=>0,'msg'=>'登录成功','userInfo'=>$userInfo,'res'=>$res]);

}


评论