有沒有想過,向一個公眾號發送長鏈接,然后公眾號給你回復一個短網址?
其實很簡單:
<?phpdefine("TOKEN", "xiao");//用于回復用戶消息function responseMsg(){ $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $MsgT = $postObj->MsgType; $time = time(); //如果用戶發的text類型 if($MsgT=="text"){ $key = trim($postObj->Content); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; $msgType = "text"; //生成短網址 $dwzapi = "http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=".$key; $dwzpost = file_get_contents($dwzapi); $dwzjsondecode = json_decode($dwzpost,true); //發送 $contentStr = $dwzjsondecode[0]['url_short']; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; exit; }else{ $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; $msgType = "text"; //發送 $contentStr = "請發送鏈接"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; exit; } //如果用戶發的event(事件)類型 if($MsgT=="event"){ $Event = $postObj->Event; if ($Event==subscribe) { $contentStr = "歡迎關注"; }else{ $contentStr = "希望您下次關注,但您收不到此條消息了"; } $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; $Title = $postObj->Title; $Description = $postObj->Description; $Url = $postObj->Url; $msgType = 'text'; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; exit; } }else{ echo "不對"; exit; }} $echoStr = $_GET["echostr"]; //如果有$echoStr說明是對接 if (!empty($echoStr)) { //對接規則 $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ echo $echoStr; }else{ echo ""; exit; } }else{ responseMsg(); }?>
配置方法:
1、登錄公眾號
2、打開基本配置
3、填寫上面代碼的url
Token在代碼里面自己設置,要對應的,EncodingAESKey隨機生成。
4、然后啟用這個配置,然后去公眾號發送一個url看看!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答