WeChat developed web authorization PHP

WeChat development documentation: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

1. Public account configuration

Before requesting the user's webpage authorization from the WeChat official account, the developer needs to go to the "Development-Interface Permissions-Web Service-Web Account-Web Account-Web Authorization to Obtain User Basic Information" configuration option on the official website of the public platform to modify the authorization callback domain name. Please note that the domain name (a string) is filled in here, not the URL, so please do not add http: // and other protocol headers;

 There are two types of authorized login: one is the silent login of snsapi_base, and the authorization pop-up window will not pop up when logging in, but this method can only get the openid; the other is the snsapi_userinfo, which will pop up the authorization box and require the user to manually agree , You can get the user's detailed information
access_token: the access_token used for web page authorization is different from the ordinary access_token obtained by the "get access_token" interface in basic support

Second, the authorization process

 1. The user agrees to authorization and obtains the code
to guide the user to the authorization page where authorization is required

 After the user agrees to the authorization, the page will jump to the callback page filled in before, and the code parameter will be carried after the callback address url, and the code can be obtained by intercepting the url.
Note: The code carried by each authorization is different and has an expiration time

 2.
Exchange the webpage authorization access_token with code. If the previously selected authorization scope is snsapi_base, then at the same time as the access_token is obtained in this step, the openid will also be obtained, then the webpage authorization in snsapi_base mode will end here; snsapi_userinfo, then continue.
It should be noted that the access_token has an expiration time, so pay attention to this time to avoid the expiration of the access_token.

3. Obtain user information

Through the access_token and openid obtained in the previous steps, to request the interface, you can get the user's detailed information

Three, sample code

wechat.php This class is the basic operation class of WeChat

<? php 
namespace app \ index \ controller; 
use think \ Controller; 

/ * * 
 * WeChat class 
 * / 
class Wechat extends Controller 
{ 

    protected   $ APPID = 'wx9daa4e0c5c26375d' ;
     protected   $ APPSECRET = 'ce3950067aacfb39c997d5def023be98' ; 

    / * * 
    * WeChat server Verify the url of the token during configuration 
    * / 
    public  function checkToken () 
    { 
        header ("Content-type: text / html; charset = utf-8" ); 

        // 1. Sort timestamp, nonce, toke in lexicographic order 
        $ timestamp =$ _GET ['timestamp' ];
         $ nonce = $ _GET ['nonce' ];
         $ token = 'asd123456zxc' ;
         $ signature = $ _GET ['signature' ];
         $ array = array ( $ timestamp , $ nonce , $ token );
         // 2. After concatenating the three sorted parameters, encrypt them with sha1 
        $ tmpstr = implode ('', $ array );
         $ tmpstr = sha1 ( $ tmpstr );
         //3. Compare the encrypted string with the signature to determine whether the request comes from WeChat 
        if ( $ tmpstr == $ signature ) {
             echo  $ _GET ['echostr' ];
             exit ; 
        } 
    } 

    / * * 
    * curl request 
    * / 
    public  function http_curl ( $ url , $ type = 'get', $ res = 'json', $ arr = '' ) { 
        
      $ cl = curl_init (); 
      curl_setopt ( $ cl , CURLOPT_URL, $ url ); 
      curl_setopt ( $ cl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
      if($type == 'post'){
        curl_setopt($cl, CURLOPT_POST, 1);
        curl_setopt($cl, CURLOPT_POSTFIELDS, $arr);
      }
      $output = curl_exec($cl);
      curl_close($cl);
      return json_decode($output, true);
      if($res == 'json'){
        if( curl_error($cl)){
          return curl_error($cl);
        }else{
          return json_decode($output, true);
        }
      }
    }

    /**
     * 获取 AccessToken
     */
    public function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->APPID."&secret=".$ this-

         > APPSECRET; // First determine whether the token in the access_token file expires, continue to use it without expiry, update 
        $ data = json_decode ( $ this-> get_php_file (ROOT_PATH. "public" .DS. "wxtxt" .DS . "access_token.txt" ));
         // Expired update 
        if ( $ data-> expire_time < time ()) { 
            
            $ res = $ this-> http_curl ( $ url );
             $ access_token = $ res ['access_token' ];
             if ( $ access_token ) {
                 // Add 7000s (two hours) to the current timestamp 
                $ data->expire_time = time() + 7000;
                $data->access_token = $res['access_token'];
                $this->set_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt",json_encode($data));
            }
        }else{
            // 未过期 直接使用
            $access_token = $data->access_token;
        }
        
        return $access_token;
    }
    
      /**
     * 获取 JsApiTicket
     */
      public function getJsApiTicket()
      { 
          // Judge whether jsapi_ticket has expired and continue to use it. If it expires, update 
          $ data = json_decode ( $ this-> get_php_file (ROOT_PATH. "Public" .DS. "Wxtxt" .DS. "Jsapi_ticket.txt" )); 

          if ( $ data-> expire_time < time ()) {
               // expired update 
              $ accessToken = $ this- > getAccessToken ();
               $ url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket ? type = jsapi & access_token = $ accessToken " ;
               $ res = $ this-> http_curl ( $ url );
              $ticket =  $ res['ticket'];
              if ($ticket) {
                  $data->expire_time = time() + 7000;
                  $data->jsapi_ticket = $ticket;
                  $this->set_php_file(ROOT_PATH."public".DS."wxtxt".DS."jsapi_ticket.txt",json_encode($data));
              }
          }else{
              $ticket = $data->jsapi_ticket;
          }
          return $ticket;
      }


    //Get the token ticket 
    private  function in the stored file get_php_file ( $ filename ) {
         return  trim ( file_get_contents ( $ filename )); 
      } 
      // Store the token ticket in the file 
      private  function set_php_file ( $ filename , $ content ) {
         $ fp = fopen ( $ filename , "w" );
         fwrite ( $ fp ,   $ content );
         fclose ( $ fp ); 
      } 
      
}

wxopera.php This class is an authorized class

<? php 
namespace app \ index \ controller; 
use think \ Controller;
 use app \ index \ controller \ Wechat; 

/ * * 
 * WeChat function development 
 * / 
class Wxopera extends Wechat 
{ 
    / * * 
     * Web authorization 
     * / 
     public  function shouquan ( ) { 
         
         $ wx = new Wechat ();
          $ APPID = $ wx- > APPID;
          $ redirect = urlencode ("http://test.zizhuyou.site/index/Wxopera/callback" ); 
        
        // Call up WeChat authorization prompt 
         $ url= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=". $ APPID . "& redirect_uri =". $ redirect . "& response_type = code & scope = snsapi_userinfo & state = STATE # wechat_redirect" ;
         // jump sublicense page 
        $ the this -> the redirect ( $ URL ); 
     
     } 
     
     / * * 
     * page authorized callback 
     * / 
     public  function  the callback () { 
         
         $ WX = new new wechat ();
          $ the APPID = $ WX -> the APPID;
          $ appsecret = $ wx-
         
          > APPSECRET; //1. Get the code code in the user authorization callback only for five minutes 
        echo "<pre>" ;
          // Get the parameter part of the current url 
         $ params = $ _SERVER ["QUERY_STRING"];     // s = / index / Wxopera / callback & code = 071W7rvB0IcmQk2z3VuB0ZvNvB0W7rv6 & state = STATE 
         // Split into an array 
        $ arr = explode ('&', $ params );
         $ code = explode ('=', $ arr [1 ]);
         $ code = $ code [1 ]; 
        
        // Second, through the web page to obtain the authorization code is valid access_token 7200s, expired need to get, they will not deal with the issue here expired 
        $ url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$APPID&secret=$APPSECRET&code=$code&grant_type=authorization_code";
         $res = $wx->http_curl($url);
     
         // 三、获取用户信息
         $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";
         
         $userinfo = $wx->http_curl($url2);
         
         print_r($userinfo);
     }
    

}

 

Guess you like

Origin www.cnblogs.com/zxf100/p/12720983.html