您現在的位置是:首頁 > ThinkPHP

李清波 2019-06-01 ThinkPHP 357

小程序不需要授權的簡單登錄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]);

}


評論