WeChat JSSDK page Authorization implementation class PHP ssdb redis ssdb command ssdb Redis ratio

Source: Internet
Author: User
Tags sha1
Page Authorization – (JS-SDK using a rights-signing algorithm)
Use method: Instantiate this class, and then call the Getsignpackage () method in it.
Note: These involve getting access_token and jsapi_ticket need their own cache and cannot be retrieved frequently!


    /** * Author:helen * CREATETIME:2016/4/11 10:39 * Description: Page authorization-(JS-SDK use Rights signature Algorithm) */ classjssdk{Private$appId;Private$appSecret; Public function__construct($appId, $appSecret) {$this->appid =$appId;$this->appsecret =$appSecret; }/* * Get Access_token * (requires cache, can take advantage of database storage, do not refresh get frequently) * HTTP request method: Get Https://api.weixin.qq.com/cgi-bin/token?gr Ant_type=client_credential&appid=appid&secret=appsecret * Interface Request parameter * parameter must indicate if grant _type is to obtain Access_token fill client_credential AppID is a third-party user unique credential secret is a third-party user unique credential key, which is Appsecre     T * Interface return description * {"Access_token": "Access_token", "expires_in": 7200} Access_token obtained voucher expires_in voucher valid time in seconds * Interface Error description * {"Errcode": 40013, "errmsg": "Invalid AppID"} * * /Private functiongetaccesstoken(){$appId=$this->appid;$appSecret=$this->appsecret;$url=' https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= '.$appId.' &secret= '.$appSecret;$res=$this->api_request ($url);if(isset($res->access_token)) {returnArray(' Errcode '=0,' ErrMsg '=' Success ',' Access_token '=$res->access_token,' expires_in '=$res-&GT;EXPIRES_IN); }Else{returnArray(' Errcode '=$res->errcode,' ErrMsg '=$res->errmsg,' Access_token '=NULL,' expires_in '=NULL); }    }/* * Get Jsapi_ticket * (valid for 7,200 seconds, developers must be in their own service global cache Jsapi_ticket) * Request method: Https://api.weixin.qq.com/cgi-bin/tick ET/GETTICKET?ACCESS_TOKEN=ACCESS_TOKEN&TYPE=JSAPI * Interface return value: JSON * {"Errcode": 0, "ErrMsg"            : "OK", "Ticket": "Bxldikrxvbtpdhsm05e5u5suoxnkd8-41zo3mhkoyn5ofkwitdggnr2fwj0m9e8nyzwkvzvdvtaugwvsdshfka", "Expires_in": 7200} * */Private functiongetjsapiticket(){$access _token_data=$this->getaccesstoken ();if($access _token_data[' Errcode ']==0){$access _token=$access _token_data[' Access_token '];$url=' https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token= '.$access _token.' &type=jsapi ';$res=$this->api_request ($url);if($res->errcode==0){returnArray(' Errcode '=$res->errcode,' ErrMsg '=$res->errmsg,' Ticket '=$res->ticket,' expires_in '=$res-&GT;EXPIRES_IN); }Else{returnArray(' Errcode '=$res->errcode,' ErrMsg '=$res->errmsg,' Ticket '=NULL,' expires_in '=NULL); }        }Else{returnArray(' Errcode '=$access _token_data[' Errcode '],' ErrMsg '=$access _token_data[' ErrMsg '],' Ticket '=NULL,' expires_in '=NULL); }    }/* Signature Algorithm * Signature generation rules are as follows: The fields participating in the signature include NONCESTR (random string), valid jsapi_ticket, timestamp (timestamp), url (the URL of the current Web page, does not contain # and its subsequent parts). * 1, for all parameters to be signed according to the field name of the ASCII code from small to Large (dictionary order), * 2, using the format of the URL key value pairs (that is, key1=value1&key2=value2 ...     ) stitching into string string1. * It is important to note that all parameter names are lowercase characters.     String1 is SHA1 encrypted, the field names and field values are in the original values and are not URL escaped. * *//* * Get random String * Mt_rand () returns a random integer using the Mersenne Twister algorithm.     * Mt_rand (Min,max) if no optional parameter min and Max,mt_rand () are supplied returns the pseudo-random number between 0 and Rand_max.     * Want a random number between 5 and 15 (including 5 and 15), with Mt_rand (5, 15). * This function rand () four times times faster * *// * * 1. The NONCESTR and timestamp for signing must be the same as NONCESTR and timestamp in Wx.config.     * 2. The URL of the signature must be the full URL of the page that invokes the JS interface.     * 3. For security reasons, the developer must implement the signature logic on the server side.     * Note: * Make sure that the URL you get for signing is dynamically fetched, and the dynamic page can be found in the instance code in PHP implementation. * If the static page of HTML in the front end through the Ajax URL to the background signature, the front end needs to use JS to get the current page to remove the ' # ' hash portion of the link (available location.href.split (' # ') [0] to obtain,     and need encodeuricomponent), * Because once the page is shared, the client will add other parameters at the end of your link, and if not dynamically get the current link, it will cause the page signature to fail after sharing. * */ Public functiongetsignpackage() {$jsapiTicket _data=$this->getjsapiticket ();$nonceStr=$this->getnoncestr ();$timestamp= time ();$url=$this->geturl ();if($jsapiTicket _data[' Errcode ']==0){$jsapiTicket=$jsapiTicket _data[' Ticket '];//The order of the parameters should be sorted by the ASCII code of the key value.$string="Jsapi_ticket= $jsapiTicket &n/span>;$signature= SHA1 ($string);returnArray("AppId"=$this->appid,"Noncestr"=$nonceStr,"Timestamp"=$timestamp,"url"=$url,"Signature"=$signature,"Rawstring"=$string,"Errcode"=$jsapiTicket _data[' Errcode '],"ErrMsg"=$jsapiTicket _data[' ErrMsg ']            ); }Else{returnArray("AppId"=$this->appid,"Noncestr"=$nonceStr,"Timestamp"=$timestamp,"url"=$url,"Signature"=NULL,"Rawstring"=NULL,"Errcode"=$jsapiTicket _data[' Errcode '],"ErrMsg"=$jsapiTicket _data[' ErrMsg ']            ); }    }/ * * Get NONCESTR * */Private functiongetnoncestr($length = +) {$chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";$nonceStr=""; for($i=0;$i<$length;$i++) {$nonceStr. = substr ($chars, Mt_rand (0, strlen ($chars) -1),1); }return$nonceStr; }/* * Get URL * URL (the URL of the current page, not including # and its subsequent parts) * */Private functiongetUrl(){$protocol= (!Empty($_server[' HTTPS ']) &&$_server[' HTTPS '] !==' off '||$_server[' Server_port '] ==443) ?"https://":"http //";$url="$protocol $_server[http_host]$_server[request_uri]";return$url; }/ * * API Call Method * */Private functionapi_request($url,$data=null){//Initialize Curl method$ch= Curl_init ();//Set Curl parameters (Basic parameters)$opts=Array(You need to set the following two items to turn off SSL authentication when you visit HTTPS sites within the LAN! //These two are officially on-line and need to be changed (do not check and verify the certification)Curlopt_ssl_verifypeer =false, Curlopt_ssl_verifyhost =false, Curlopt_timeout = -, Curlopt_returntransfer =true, Curlopt_url =$url,        ); Curl_setopt_array ($ch,$opts);//post Request Parametersif(!Empty($data) {curl_setopt ($ch, Curlopt_post,true); curl_setopt ($ch, Curlopt_postfields,$data); }//Perform curl Operation$output= Curl_exec ($ch);if(Curl_errno ($ch)) {error handling occurs with the//curl operation. Var_dump (Curl_error ($ch)); die; }//Turn off CurlCurl_close ($ch);$res= Json_decode ($output);return($res);//Return JSON data}}

'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
  • '). Text (i)); }; $numbering. FadeIn (1700); }); });

    The above describes the JSSDK page authorization implementation class PHP, including the content of the PHP,SSD, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    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.