Restfual 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这两个字段就可以了,手机端会自己获取用户信息。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.
