search
HomeBackend DevelopmentPHP TutorialRestfual api 架构的第三方登录

序言

第三方登录的使用在当今非常普遍,不管是PC端还是手机端都很常见。因为它有着一号多用的特点,不管是在什么网站什么软件上只要有了这个第三方登录的功能就无需再次走注册步骤,直接用第三方的账号登录就可以了,方便吧?开发程序看重的是用户体验,为用户打造一款“麻雀虽小,五脏俱全”,使用便利的产品是我们的职责。那么话又说回来,在Restfual api 上如何实现第三方登录呢?我在Segmentfault上找不到我想要的答案,不过最终我也实现了,我把我的实现思路写出来,当然这只是我的一种实现方式,要是大家有更好的方法呢,乐意交流。

需求分析

1、用Restfual api的架构实现第三方登录,如QQ,微信登录等。

效果图

实现思路

1、建两个表,user表和user_login表。user表我就不详说了,这是基本表,我重点说一下user_login表。user_login表字段:

id                    iduser_id               用户idtype                  登录类型(如:QQ,weixin)  qq_access_token       QQ授权access_tokenqq_openid             QQ openidwx_access_token       微信授权access_tokenwx_openid             微信openid

要是还有微博或者淘宝之类的其他第三方登录就如以上的规律加上对应的字段就行了。

2、gii生成UserLogin.php model如下:

<?phpclass UserLogin extends /yii/db/ActiveRecord{    /**     * @inheritdoc     */    public static function tableName()    {        return 'user_login';    }    /**     * @inheritdoc     */    public function rules()    {        return [            [['user_id'], 'integer'],            [['type'], 'string', 'max' => 30],            [['qq_access_token', 'wx_access_token'], 'string', 'max' => 220],            [['qq_openid', 'wx_openid'], 'string', 'max' => 100]        ];    }    /**     * @inheritdoc     */    public function attributeLabels()    {        return [            'id' => Yii::t('yii', 'ID'),            'user_id' => Yii::t('yii', 'User ID'),            'type' => Yii::t('yii', 'Type'),            'qq_access_token' => Yii::t('yii', 'Qq Access Token'),            'qq_openid' => Yii::t('yii', 'Qq Openid'),            'wx_access_token' => Yii::t('yii', 'Wx Access Token'),            'wx_openid' => Yii::t('yii', 'Wx Openid'),        ];    }     }

3、控制器里的方法如下:QQ登录

  public function actionQqLogin()      {           $_model = new UserLogin();          $model = new TUser();          $post = Yii::$app->request->post();          if(!empty($post))          {             $t_nickname = !empty($post['t_nickname']) ? trim($post['t_nickname']) : '';             $access_token = !empty($post['access_token']) ? trim($post['access_token']) : '';             $openid = !empty($post['openid']) ? trim($post['openid']) : '';             $t_photo = !empty($post['t_photo']) ? trim($post['t_photo']) : '';//头像             $res = UserLogin::find()                      ->where(['type'=>'qq','qq_openid'=>$openid])                      ->one();            //判断是否已存在用户信息,存在则返回该条用户信息             if(!empty($res))             {                 $res->qq_access_token = $access_token;                 $res->save();                //获取一条用户信息                 $user = $model->getUserrow($res->user_id);                 if(!empty($user)){                    return $user;                 }else{                     ErrorMsg::Info(Yii::t('yii','Login fail'));                 }                            }else{                   //保存新用户                  $user = $this->saveUser($t_nickname,$t_nickname,$openid,'','',$t_photo);                  if(empty($return['error_code'])){                       $_model->user_id = $user->t_id;                      $_model->type = 'qq';                      $_model->qq_access_token = $access_token;                      $_model->qq_openid = $openid;                       $_model->save();                      $user = $model->getUserrow($user->t_id); //保证返回数据字段一致                  }                  return $user;              }          }else{              ErrorMsg::Info(Yii::t('yii','Login fail'));          }       }

微信登录

 public function actionWxLogin()      {           $_model = new UserLogin();          $model = new TUser();          $post = Yii::$app->request->post();          if(!empty($post))          {             $t_nickname = !empty($post['t_nickname']) ? trim($post['t_nickname']) : '';             $access_token = !empty($post['access_token']) ? trim($post['access_token']) : '';             $openid = !empty($post['openid']) ? trim($post['openid']) : '';             $t_photo = !empty($post['t_photo']) ? trim($post['t_photo']) : '';//头像             $res = UserLogin::find()                      ->where(['type'=>'weixin','wx_openid'=>$openid])                      ->one();             //判断是否已存在用户信息,存在则返回该条用户信息             if(!empty($res))             {                  $res->wx_access_token = $access_token;                 $res->save();                 //获取一条用户信息                 $user = $model->getUserrow($res->user_id);                 if(!empty($user)){                    return $user;                 }else{                     ErrorMsg::Info(Yii::t('yii','Login fail'));                 }                            }else{                   //保存新用户                  $user = $this->saveUser($t_nickname,$t_nickname,$openid,'','',$t_photo);                  if(empty($return['error_code'])){                      $_model->user_id = $user->t_id;                      $_model->type = 'weixin';                      $_model->wx_access_token = $access_token;                      $_model->wx_openid = $openid;                      $_model->save();                      $user = $model->getUserrow($user->t_id);//保证返回数据字段一致                  }                  return $user;              }          }else{              ErrorMsg::Info(Yii::t('yii','Login fail'));          }       }

保存用户信息方法:

    public function saveUser($t_username,$t_nickname,$openid,$email,$phone,$t_photo)    {                  $access_token = sha1(time().$openid);        $data = array(          "t_nickname"=> $t_nickname,          "t_password"=> base64_encode($openid),          "t_state"   => 0,          "t_photo"   => $t_photo?$t_photo:"/images/upload/100x100/no_photo.jpg",          "t_timezone"=> "PRC",          "t_language"=> "zh_cn",          "access_token"=> $access_token,          "rent_user_type"=>"3",          't_add_time'=>time(),        );        $model = new $this->modelUser;        $model->attributes = $data;          if(!empty($t_nickname) && !empty($openid)){              if(!$model->save()){                 ErrorMsg::Info(Yii::t('yii','Reg fail'));            }             return $model;        }else{             ErrorMsg::Info(Yii::t('yii','m-log-2'));        }    }

第三方登录获取用户基本信息方法,TUser model里:

    public function getUserrow($uid)     {              $user = $this->find()                ->select(['access_token','t_password'])                ->where(['t_id'=>$uid])                ->one();          if(!empty($user)){              $result['access_token']= !empty($access_token=$user->access_token)?$access_token:"";              $result['appsercert']  = !empty($t_password=$user->t_password)?$t_password:"";                             return $result;  //返回给手机端用,只返回access_token和appsercert。          }     }

好了,到这里Restfual api 架构的第三方登录已经实现了,微博,淘宝等第三方登录实现的思路也如此,就是要对传入的参数进行改进一下就OK了。这是我实现Restfual api架构的第三方登录的思路,不足的提议,好的点赞哈,我们一起交流。

设想与问题

1、直接在user表里加上QQ、weixin的type,openid和access_token字段,这种做法拓展性不好,以后要是再增加如:微博,淘宝等第三方登录的话,又要操作user表,对user表操作过于频繁容易出问题,而且也不是每一个用户都会使用第三方登录,会造成大量空缺字段,浪费。我之所以独立创建user_login表也正是基于这些考虑的。2、返回给手机端所有的用户信息。其实手机端不需要那些,你只要返回给手机端access_token和appsercert这两个字段就可以了,手机端会自己获取用户信息。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.