微信開發很簡單,官網也提供DEOM文檔,但難在如何從數據庫讀取整合到文檔中,也就是數據拼接。本代碼是我司開發中實現原理分享出來的,如果你正在開發那么一起來學習吧。
實現功能:當用戶輸入聊天內容給公眾號時根不同詞從數據庫讀取新聞或產品以圖文形式返回給用戶。當然如果你也是網站建設從業者可以購買我司的建站系統平臺版,可二次開發。詳情登陸:http://www.yx10011.com/design/#websites-taocan 1880元起(單用戶),多用戶版(8000元,自助建站平臺)
<?phpdefine("TOKEN", "dy_website");//與管理平臺的TOKEN設置一致$wechatObj = new wechatCallbackapiTest();//$wechatObj->valid();if(isset($_GET["echostr"])){$wechatObj->valid();}else{ session_start();require_once("../common/init.php");$web=get_web(); $wechatObj->responseMsg(); }class wechatCallbackapiTest{ public function valid()//驗證接口用,管理平臺后臺設置的時候請調用此方法進行驗證 { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg()//接受用戶信息并返回圖文信息 { $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input"); if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $msgType=$postObj->MsgType; $latitude=$postObj->Location_x; $longitude=$postObj->Location_y; $event=$postObj->Event; $eventKey=$postObj->EventKey; $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; //加載圖文模版 $picTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <ArticleCount>%s</ArticleCount> %s <FuncFlag>1</FuncFlag> </xml> "; if($msgType == "event" and $Event == "subscribe")//判斷是否是新關注 { $msgType = "text"; $contentStr = "您好,歡迎您關注巔云智能建站系統PHP開發網"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }elseif($msgType == "event" and $event=="CLICK" or !empty($keyword))//用戶輸入的內容 { $msgType = "news"; session_start();require_once("../common/init.php");$web=get_web();$con=mysql_connect(DB_SERVER,DB_LOGIN,DB_PW) or die("Unable to connect to the MySQL!");$db = mysql_select_db(DB_NAME,$con); $sqlF = "select * from products where show_index=0 and Type='product' and user='$web' and (ProductName like '%$keyword%' or txtDetail like '%$keyword%' or ProductIntro like '%$keyword%' or Price like '%$keyword%') "; $rsF = mysql_query($sqlF);$countF = mysql_num_rows($rsF);//產品if(strpos($keyword, "產品") !== false or $countF>=1 ){ if(strpos($keyword, "產品") !== false){ $wheres=""; } else{ $wheres="and (ProductName like '%$keyword%' or txtDetail like '%$keyword%' or ProductIntro like '%$keyword%' or Price like '%$keyword%')"; } $sqlc = "select * from products where show_index=0 and Type='product' and user='$web' $wheres";$rsc = mysql_query($sqlc);$countpro = mysql_num_rows($rsc);if($countpro>8) {$countpro=7;}$sql = "select * from products where show_index=0 and Type='product' and user='$web' $wheres order by rand() limit 40 ";$rs = mysql_query($sql); $strpro='<Articles>';while($row_p=mysql_fetch_assoc($rs)){ $Content1=mb_substr(strip_tags(str_replace(' ','',str_replace('"','', $row_p['txtDetail']))),0,25,'utf-8')."";$row_p['ProductName'] = mb_substr($row_p['ProductName'],0,12,'utf-8').""; $Contentall1=$row_p['txtDetail'];$PInfo=PInfo($row_p['IDProduct']);if($PInfo['iPrice']){$PInfo['iPrice']=" ¥".$PInfo['iPrice'];}else{$PInfo['iPrice']=$PInfo['iPrice'];}$query1 ="select pro_open_pageid from notes where showIndex=1 and pro_open_pageid !='' and note_class='product' and user='$web' and mobile='1' ";$rscp = mysql_query($query1);$rscpageid = mysql_fetch_row($rscp);$page_open=$rscpageid[0];$httpurl=$httpurl1="http://".$_SERVER['HTTP_HOST'];$pics = json_decode($row_p['pics'], true); if (isset($pics)) { foreach ($pics as $key=>$v) {$picinfo[$key]= $picinfo[$key];$row_p['pic']=$pics[0];}}$src1 = $row_p['pic']; if($src1==""){ $src1 = "/admin/images/dingdan.png";} if(stripos($src1,'http://') !== false){$httpurl="";} $strpro.="<item> <Title><![CDATA[{$row_p['ProductName']}{$PInfo['iPrice']} ]]></Title> <Description><![CDATA[{$Content1}]]></Description> <PicUrl><![CDATA[{$httpurl}/{$src1}]]></PicUrl> <Url><![CDATA[{$httpurl1}/mobile/index.php?proID={$row_p['IDProduct']}&page_id={$page_open}]]></Url> </item>";} $strpro.='</Articles>'; $resultStr = sprintf($picTpl, $fromUsername, $toUsername, strtotime($row_p['dtCreate']), $msgType,$countpro, $strpro);if($countpro==0){ $msgType = "text"; $contentStr = "沒找到任何相關內容產品!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); }}//產品overelse {$sqlc = "select * from news where showIndex=1 and user='$web' and (NewsID like '%$keyword%' or Title like '%$keyword%' or Content like '%$keyword%') ";$rsc = mysql_query($sqlc);$countnews = mysql_num_rows($rsc);if($countnews>8) {$countnews=7;}$sql = "select * from news where showIndex=1 and user='$web' and (NewsID like '%$keyword%' or Title like '%$keyword%' or Content like '%$keyword%') limit 40 ";$rs = mysql_query($sql); $strnews='<Articles>';while($row_p=mysql_fetch_assoc($rs)){ $Content1=mb_substr(strip_tags(str_replace(' ','',str_replace('"','', $row_p['Content']))),0,25,'utf-8')."";$row_p['Title'] = mb_substr($row_p['Title'],0,12,'utf-8').""; $Contentall1=$row_p['Content'];preg_match_all('/<img[^>]*src\s?=\s?[\'|"]([^\'|"]*)[\'|"]/is', $Contentall1, $picarr); $query1 ="select news_open_pageid from notes where showIndex=1 and news_open_pageid !='' and note_class='news' and user='$web' and mobile='1' ";$rscp = mysql_query($query1);$rscpageid = mysql_fetch_row($rscp);$page_open=$rscpageid[0];$httpurl=$httpurl1="http://".$_SERVER['HTTP_HOST'];$src1 = $picarr[1][0]; if(stripos($src1,'http://') !== false){$httpurl="";}if($src1!=""){ $strnews.="<item> <Title><![CDATA[{$row_p['Title']}]]></Title> <Description><![CDATA[{$Content1}]]></Description> <PicUrl><![CDATA[{$httpurl}/{$src1}]]></PicUrl> <Url><![CDATA[{$httpurl1}/mobile/index.php?NewsID={$row_p['NewsID']}&page_id={$page_open}]]></Url> </item>";}} $strnews.='</Articles>'; $resultStr = sprintf($picTpl, $fromUsername, $toUsername, strtotime($row_p['dtCreate']), $msgType,$countnews, $strnews);if($countnews==0){ $msgType = "text"; $contentStr = "沒找到任何相關內容!!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); }} echo $resultStr; }else{ echo "說點什么吧!"; } }else { echo "請輸入任意文字!"; exit; } } //封裝的驗證 private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } }}?>
文章內容
重慶楚捷科技有限公司 一佰互聯.巔云建站.(www.firstissue.net )@ 版權所有 網站備案:渝ICP備16004678號-2
企業文化
價值理念
做有價值的建站軟件 不止是建立網站,更提高網站建設公司價值
企業精神
以更簡單的方法服務于網站制作行業, 美工與SEO融合做健康的網站
工作時間: 8:45-17:45
微信客服