小程序不需要授权的简单登录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]);

}

温馨提示: 本文最后更新于2024-12-31 21:09:53,某些文章具有时效性,若有错误或已失效,请在下方 留言或联系 蚂蚁官方
© 版权声明
THE END
喜欢就支持一下吧
点赞9赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容