PHP implementation of WeChat PC QR code to share

Source: Internet
Author: User
Tags openid
This article mainly and we introduce PHPPC two-dimensional code landing of the realization of ideas, with a certain reference value, interested in small partners can refer to, hope to help everyone.

First, the idea:

The key idea is how to interact with the end, after all, the current login can only be on the end.

But there is a special way to generate a custom QR code, which allows us to display the QR code on the PC, and the value of the QR code can be defined by us. In addition, there is a scan event in the development documentation that detects the user using the scan QR code and obtains the value. In fact, the crux of the problem is this value, this value is a Unicom PC and communication ID.

second, the specific implementation process (the following code uses the TP5 framework, there is a major premise is the existence of a service number of the public number)

1. Generate two-dimensional code for PC:

The code is as follows:

Controller:


namespace App\home\controller;class recognition extends base{public  function Seeloginqrcode () {    $qrcode _ return = Model (' recognition ')->getloginqrcode ();    if ($qrcode _return[' Error_code ') {      return $this->returnjson ("Get failed! ", 0);    } else{      $data =array (          ' url ' = + $qrcode _return[' ticket '],          ' qrcode_id ' + $qrcode _return[' id '],      ) ;      return $this->returnjson ("Get success! ", 1, $data);}}}  

Model


namespace App\common\model;use think\model;class recognition extends model{protected $autoWriteTimestamp = false; Generate login with temporary QR code public Function Getloginqrcode () {$appid = config (' think_sdk_weixin.    App_key '); $appsecret = Config (' think_sdk_weixin.    App_secret '); if (Empty ($appid) | | empty ($appsecret)) {return (' Error_code ' =>true, ' msg ' = ' = ' Please contact the administrator to configure "AppID" "Appsecret"    ));    } $database _login_qrcode = Model (' Loginqrcode '); $database _login_qrcode->where (Array (' Add_time ' =>array (' lt ', ($_server[' Request_time ']-604800)))    Delete ();    $data _login_qrcode[' add_time '] = $_server[' request_time '];    $database _login_qrcode->save ($data _login_qrcode);    $qrcode _id = $database _login_qrcode->getlastinsid (); if (Empty ($qrcode _id)) {return (Array (' Error_code ' =>true, ' msg ' = ' = ' Get the QR code error! Unable to write data to the database. Please try again.    '));    } import (' Net.http ');    $http = new \http (); Authorization to obtain Access_token $access _token_array = Model (' Accesstokenexpires ')->getaccesstoken (); if ($access _token_array[' Errcode ') {return (Array (' Error_code ' =>true, ' msg ' = ' = ' Get access_token Error: Error code '. $ access_token_array[' Errcode ']. ', return error message: '.    $access _token_array[' errmsg '));    } $access _token = $access _token_array[' Access_token ');    $qrcode _url= ' https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token= '. $access _token;    $post _data[' expire_seconds '] = 604800;    $post _data[' action_name '] = ' qr_scene ';    $post _data[' action_info ' [' Scene '] [' scene_id '] = $qrcode _id;    $json = $http->curlpost ($qrcode _url,json_encode ($post _data));      if (! $json [' Errcode ']) {$condition _login_qrcode[' id ']= $qrcode _id;      $data _login_qrcode[' id '] = $qrcode _id;      $data _login_qrcode[' ticket ') = $json [' Ticket ']; if ($database _login_qrcode->isupdate (True)->save ($data _login_qrcode)) {return (Array (' Error_code ' =>false , ' id ' = $qrcode _id, ' ticket ' = ' https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket= '. UrlEncode ($json ['      Ticket ']));      }else{  $database _login_qrcode->where ($condition _login_qrcode)->delete (); Return (Array (' Error_code ' =>true, ' msg ' = ' = ' Get the QR code error! Failed to save QR code. Please try again.      '));      }}else{$condition _login_qrcode[' id '] = $qrcode _id;      $database _login_qrcode->where ($condition _login_qrcode)->delete ();    Return (Array (' Error_code ' =>true, ' msg ' = ' = ' ERROR: Error code '. $json [' Errcode ']. ', return error message: '. $json [' errmsg ']); }  }}

You can see that after success, return:

Copy the Code code as follows:

Return (Array (' Error_code ' =>false, ' id ' = = $qrcode _id, ' ticket ' = ' https://mp.weixin.qq.com/cgi-bin/' Showqrcode?ticket= '. UrlEncode ($json [' ticket ']));

There is an ID value, which in fact represents the value of the QR code!

Then ticket is the link to the QR code. That is, scanning this QR code in the scan event gets the value is this ID.

View End processing below

1, after scanning QR code:


namespace App\mobile\controller;class Wechat extends base{public Function index () {import (' wechat.wechat ');    $wechat = new \wechat ();    $data = $wechat->request ();    List ($content, $type) = $this->reply ($data);    if ($content) {$wechat->response ($content, $type);    } else {exit ();      }} public Function reply ($data) {if ($data [' msgtype '] = = ' event ') {$id = $data [' Eventkey '];        Switch (Strtoupper ($data [' Event ')]) {case ' SCAN ': Return $this->scan ($id, $data [' fromusername ']);          Case ' CLICK '://reply?          Return Array (' Click ', ' text ');        Break          Case ' SUBSCRIBE '://Focus on return Array (' Welcome ', ' text ');        Break        Case ' unsubscribe '://Take off return Array (' Bye-bye ', ' text ');      Case ' location '://locate break; }} else {if ($data [' msgtype '] = = ' text ') {return array ("Test succeeded!      ", ' text '); } if ($data [' MsGType '] = = ' location ') {} if (import (' @.org. '. $data [' Msgtype '].  ' Messagereply ')) {}} return false;       Private function Scan ($id, $openid = ", $issubscribe = 0) {if ((1000000000 < $id) && $openid) {           if ($user = Model (' Member ')->field (' id ')->where (Array (' third_id ' = = $openid))->find ()) {$data =array (         ' id ' = $id, ' uid ' = ' $user [' id ']);         Model (' Loginqrcode ')->isupdate ()->save ($data);       Return Array (' Login successful ', ' text ');       } $data =array (' id ' = = $id, ' uid ' =>-1);      Model (' Loginqrcode ')->isupdate (True)->save ($data); $return [] = Array (' Click to authorize login ', ' ', config (' Site_logo '), config (' Site_url '). '/mobile/wechatbind/ajaxweblogin?qrcode_id= '.      $ID);    Return Array ($return, ' News '); }  }}

The scan method above has this judgment and can be seen as:

if ((1000000000 < $id) && $openid) {

The $id is the value of the corresponding QR code, that is, the ID we generated earlier (in fact, in order to distinguish the various events in the scan, the ID of the Login_qrcode table is deliberately set to increment the ID from 1000000000).
Then look at the handle after the IF:


if ($user = Model (' Member ')->field (' id ')->where (Array (' third_id ' = = $openid))->find ()) {         $data =array (           ' id ' = $id,           ' uid ' = ' $user [' id ']         );         Model (' Loginqrcode ')->isupdate ()->save ($data);         Return Array (' Login successful ', ' text ');       }

If the condition is met and the user exists for the OpenID, the Login_qrcode table is updated and the UID is changed to the user ID. (Here is the key, why update the ID corresponding to the data UID for the user ID even if logged in).

3, continue to look at the PC side, the PC segment in the acquisition of 1 of the QR code and did not stop the request, but rotation a method:


* Sign-in asynchronous request * @return \think\response\json * Created by sunnier<xiaoyao_xiao@126.com> */Public function AJAXWEC        Hatlogin () {for ($i = 0; $i < 6; $i + +) {$database _login_qrcode = model (' Loginqrcode ');        $condition _login_qrcode[' id '] = input (' get.qrcode_id '); if (Empty ($condition _login_qrcode[' id ')) {return $this->returnjson (' not acquired to qrcode_id!        ', 0);        } $now _qrcode = $database _login_qrcode->field ("UID")->where ($condition _login_qrcode)->find ();            if (!empty ($now _qrcode[' uid ')) {if ($now _qrcode[' uid ') = =-1) {$data _login_qrcode[' uid '] = 0;            $database _login_qrcode->where ($condition _login_qrcode)->isupdate (True)->save ($data _login_qrcode); return $this->returnjson (' Please sign in at the public number!          ', 0);          } $database _login_qrcode->where ($condition _login_qrcode)->delete ();          $result = Model (' Member ')->autologin (' id ', $now _qrcode[' uid ']); if (empty($result [' Error_code '])) {return $this->returnjson (' Login successful!          ', 1, $result [' User ']; } else if ($result [' error_code '] = = 1001) {return $this->returnjson (' No user found, please rescan QR code!          ', 0); } else if ($result [' Error_code ']) {return $this->returnjson (' Login failed!          ', 0);        }} if ($i = = 5) {return $this->returnjson (' Login failed ', 0);      } sleep (3); }  }

You can see that the above method gets the qrcode_id, which is the ID returned in 1, and the other return is the QR code.
Rotation process is to use this ID to constantly view the status of the Login_qrcode table, if there is a UID so that the success of the landing! You can also use the UID to automatically log in.

4, above

The key is Login_qrcode this intermediate table plays the role of the bridge, one side used to generate two-dimensional code, the side used to insert the user UID at the end, while the PC-side detection table status changes to achieve the login.

Related recommendations:

Registration binding page and QR Code landing page Development project summary _html/css_web-itnose

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.