WeChat background code, get user nickname-PHP source code

Source: Internet
Author: User
Tags openid
Background code to get the nickname of a user

[PHP] code
 Valid ();} else {$ wechatObj-> responseMsg ();} class wechatCallbackapiTest {// source verification public function valid () {$ echoStr = $ _ GET ["echostr"]; if ($ this-> checkSignature () {echo $ echoStr; exit ;}} private function checkSignature () {$ signature = $ _ GET ["signature"]; $ timestamp = $ _ GET ["timestamp"]; $ nonce = $ _ GET ["nonce"]; $ token = TOKEN; $ tmpArr = array ($ token, $ timestamp, $ nonce); sort ($ tmpArr); $ tmpStr = im Plode ($ tmpArr); $ tmpStr = sha1 ($ tmpStr); if ($ tmpStr ==$ signature) {return true;} else {return false ;}} // message processing // only implements the public function responseMsg () {$ postStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; if (! Empty ($ postStr) {$ postObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA); $ RX_TYPE = trim ($ postObj-> MsgType); switch ($ RX_TYPE) {case "text": $ resultStr = $ this-> receiveText ($ postObj); break; case "image": $ resultStr = $ this-> receiveImage ($ postObj ); break; case "location": $ resultStr = $ this-> cancelocation ($ postObj); break; case "voice": $ resultStr = $ this-> cancevoice ($ postObj ); break; case "video": $ resultStr = $ this-> receiveVideo ($ postObj); break; case "link": $ resultStr = $ this-> cancelink ($ postObj ); break; case "event": $ resultStr = $ this-> receiveEvent ($ postObj); break; default: $ resultStr = "unknow msg type :". $ RX_TYPE; break;} echo $ resultStr;} else {echo ""; exit;} function receiveText ($ object) {$ funcFlag = 0; $ contentStr = $ this-> get_name ($ object ). ", you sent text with the following content :". $ object-> Content; $ resultStr = $ this-> transmitText ($ object, $ contentStr, $ funcFlag); return $ resultStr;} public function get_name ($ object) {$ access_token = $ this-> readtoken (); // Here we need to solve the problem that the access_token is valid for two hours. // One idea is to define a new function, if you call this function, you can find the time when an access_token was generated in the database. compare the current time with the current time. // if the time exceeds 2 hours, you can get the new access_token in get mode, then, a new access_token is returned and stored in the database; // if less than two hours are returned, the latest access_token stored in the database is extracted and returned; $ openid = $ object-> FromUserName; // Construct an SSL get API link for getting user information $ infourl =" https://api.weixin.qq.com/cgi-bin/user/info?access_token= ". $ Access_token. "& openid = ". $ openid. "& lang = zh_CN"; $ result = $ this-> https_get ($ infourl); // var_dump ($ result); // echo $ result; $ utfresult = utf8_encode ($ result); $ mm = json_decode ($ result, true); return trim ($ mm ['nickname']);} public function newtoken () {// $ appid = "wx2b558d720b186565"; // appid corresponding to the ipad mini account // $ appsecret = "fe9f74ef9abf75a63d6750e365d49cad "; // This is the secret $ appid = "wx66c888ff7a867359" for the ipad mini account; // This is the appid for the iphone $ appsecret = "fad178aa420ceef67e16dd6a4812e6dc "; // This is the secret corresponding to the iphone account $ access_token_url =" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= ". $ Appid. "& secret = ". $ appsecret; // echo $ access_token_url; $ access_json = $ this-> https_get ($ access_token_url); // $ access_json = '{"access_token": "sXr18Q9qklWbLFuBAi5w6B-kWeXVXW2dtHwb53Iy2wdgnebSDFs8r4NwT8uTafgB6rMXc00lsE5HayE28N9-KTHv5HyHG8b8UFxsvLBNgAU ", "expires_in": 7200} '; // echo $ access_json; $ access = json_decode ($ access_json, true); // var_dump ($ access ); // echo $ access_array ['Access _ token']; return $ access ['Access _ token'];} public function savetoken ($ token) {$ host = ""; // Database Server Name $ user = ""; // database connection username $ pw = ""; // database connection password $ db = ""; // database name // Connect to mysql database $ conn = mysql_connect ($ host, $ user, $ pw); // mysql_query ("set names 'utf8 '"); if ($ conn) {mysql_select_db ($ db); // mysql_set_charset ("gbk"); // $ SQL = "select * from token"; $ time = time (); // $ token = newtoken (); // echo $ time; $ SQL = "insert into token (time, token) VALUES ('$ time',' $ token ') "; $ result = mysql_query ($ SQL) or die (" Invalid query :". mysql_error (); // $ mm = mysql_fetch_array ($ result); // var_dump ($ mm); mysql_free_result ($ result );} else {echo "database connection KO" ;}} public function readtoken () {$ host = ""; // Database Server Name $ user = ""; // database connection username $ pw = ""; // database connection password $ db = ""; // database name // Connect to mysql database $ conn = mysql_connect ($ host, $ user, $ pw); // The database output encoding must be consistent with your database encoding // mysql_query ("set names 'utf8'"); if ($ conn) {// select the database mysql_select_db ($ db); // mysql_set_charset ("gbk"); // in the token table, sort by time in descending order, extract the first value (limit 1) of the time column $ SQL = "select time, token from token order by time desc limit 1 "; // execute the SQL statement $ result = mysql_query ($ SQL) or die ("Invalid query :". mysql_error (); // Obtain the execution result and save it as an array to the variable $ mm = mysql_fetch_array ($ result); mysql_free_result ($ result ); // access the array with the column header to obtain the last stored timestamp $ lasttime = $ mm ['Time']; // echo"




". $ Lasttime; // generate the current time, timestamp $ timenow = time (); // if the current time minus the time stamp of the last storage, if it is less than 7100, then, run the SQL statement again to obtain the token that has been stored in the table. if not, a new token is generated and stored in the database if ($ timenow-$ lasttime <7100) {$ tokenread = $ mm ['token']; return $ tokenread; // echo"




". $ Tokenread;} else {$ newtoken = $ this-> newtoken (); $ this-> savetoken ($ newtoken); $ tokenread = $ newtoken; return $ tokenread ;}}} public function https_get ($ url) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_URL, $ url); curl_setopt ($ curl, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt ($ curl, CURLOPT_SSL_VERIFYHOST, FALSE); // curl_setopt ($ curl, CURLOPT_POST, 1); // curl_setopt ($ curl, CURLOPT_POSTFIELDS, $ da Ta); curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, 1); $ result = curl_exec ($ curl); if (curl_errno ($ curl) {return 'errno '. curl_error ($ curl);} curl_close ($ curl); return $ result;} private function receiveEvent ($ object) {$ contentStr = ""; switch ($ object-> Event) {case "subscribe": // $ uername = json_decode ($ object, true); $ contentStr = "Welcome! ". $ This-> get_name ($ object); // after a user subscribes, the information of all users, such as openid, nickname, and address must be stored; // call the storage function, you must create a new one .... Break; case "unsubscribe": $ contentStr = ""; break; case "CLICK": switch ($ object-> EventKey) {case no_oauyy: // $ contentStr = no_oau2; $ contentStr = "[FromUserName. "'> My class] [FromUserName. "'> order record]"; break; case "oau2": $ contentStr = $ this-> toAuthMsg (); break; default: $ contentStr =" you have clicked the menu: ". $ object-> EventKey; break;} break; default: $ contentStr = "receive a new event :". $ object-> Event; break;} $ resultStr = $ this-> transmitText ($ object, $ contentStr); if ($ contentStr = no_oau2) {header ("location: https://www.php1.cn/ ". $ Object-> FromUserName); exit;} return $ resultStr;} private function transmitText ($ object, $ content, $ flag = 0) {$ textTpl =" %s %s % S text %s % D "; $ ResultStr = sprintf ($ textTpl, $ object-> FromUserName, $ object-> ToUserName, time (), $ content, $ flag); return $ resultStr ;} private function toAuthMsg () {$ resultStr = "bind now"; return $ resultStr ;}}?>
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.