生活随笔
收集整理的這篇文章主要介紹了
微信小程序客服自动回复——PHP实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先說怎么用,然后使用成功了自己研究代碼,驅動式學習多好。
首先將這個PHP程序的文件放在你 自己的服務器里面
注意php程序里的APP_ID的值改成你自己的appid。還有APP_SECRET 的值改成你自己的appSecret。還有記好配置的token令牌,等會配置用到。
然后打開消息推送
在小程序后臺“開發”->“開發設置”->下拉有一個消息推送,打開。
服務器地址填寫這個PHP文件的位置https://**********.php
TOKEN(令牌) ----這里隨便寫,反正與PHP程序里的開頭那里我 的是dertertsdf
define(“TOKEN”,“dertertsdf”);//自己設置的Token
密鑰隨機生成
然后模式選兼容模式
接受類型選“XML”
這是配置,然后如果你急著提交會發現“taken(令牌) 失效”。。。。。就對了
驗證
在250行左右有一個代碼,這是驗證用的,因為當你打開消息推送的時候騰訊的服務器會給你寫的地址發送一個請求進行驗證只有你返回正確的信息才能驗證成功,提交才不會出現“taken(令牌) 失效”字樣。然后才會提交成功,所以當提交時不要注釋
PS:建議把綁定的客服都解綁,因為我發現有時候會出現bug,會把用戶聯系 客服的消息轉發給客服了不發送給服務器也就是自動回復那里收不到。
修改
順利完成了上面的步驟后你打開客服應該會有自動打招呼了。
然后就自己看代碼發揮了,對應封裝一個$data變量調用官方文檔說的發送接口就可以了
如果想發送圖片,需要先把圖片發送給騰訊服務器,然后騰訊服務器會返回一個媒體的ID,用這個ID調用發送接口就可以了。程序里我也寫好了輸入上傳圖片地址返回ID的函數了。
不過我偷懶直接調用系統指令curl,所以需要PHP的shell_exec()這個函數。為了安全起見這個函數一般默認禁用的,所以需要在php配置文件里該一下,百度就可以。over
下面時所有代碼。可以直接復制粘貼用【手動滑稽】
<?php
define("TOKEN","dertertsdf");class wechatAPI{const APP_ID = 'wx***********'; const APP_SECRET = '017ec3*****************';public function isValid(){$echoStr = $_GET["echostr"];if ($this->checkSignature()) {echo $echoStr;exit
;}}public function checkSignature(){$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 ){return true;}else{return false;}}public function send($data){$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->getAccessToken();$data = urldecode(json_encode($data));$this->curl_post($url,$data);}public function xml2Array($contents = NULL, $encoding = 'UTF-8', $get_attributes = 1, $priority = 'tag'){if (!$contents) {return array();}if (!function_exists('xml_parser_create')){return array ();}$parser = xml_parser_create('');xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $encoding);xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);xml_parse_into_struct($parser, trim($contents), $xml_values);xml_parser_free($parser);if (!$xml_values)return array(); $xml_array = array ();$parents = array ();$opened_tags = array ();$arr = array ();$current = & $xml_array;$repeated_tag_index = array (); foreach ($xml_values as $data){unset
($attributes, $value);extract($data);$result = array ();$attributes_data = array ();if (isset
($value)){if ($priority == 'tag')$result = trim($value);else$result['value'] = trim($value);}if (isset
($attributes) && $get_attributes) {foreach ($attributes as $attr => $val){if ($priority == 'tag')$attributes_data[$attr] = $val;else$result['attr'][$attr] = $val; }}if ($type == "open"){ $parent[$level -1] = & $current;if (!is_array($current) || (!in_array($tag, array_keys($current)))) {$current[$tag] = $result;if ($attributes_data)$current[$tag . '_attr'] = $attributes_data;$repeated_tag_index[$tag . '_' . $level] = 1;if (isset($tag) && $tag && isset($current[$tag])) {$current = & $current[$tag];}}else{if (isset
($current[$tag][0])){$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;$repeated_tag_index[$tag . '_' . $level]++;}else{ $current[$tag] = array ($current[$tag],$result); $repeated_tag_index[$tag . '_' . $level] = 2;if (isset
($current[$tag . '_attr'])){$current[$tag]['0_attr'] = $current[$tag . '_attr'];unset
($current[$tag . '_attr']);}}$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;$current = & $current[$tag][$last_item_index];}}elseif ($type == "complete"){if (!isset
($current[$tag])){$current[$tag] = $result;$repeated_tag_index[$tag . '_' . $level] = 1;if ($priority == 'tag' && $attributes_data) {$current[$tag . '_attr'] = $attributes_data;}}else{if (isset
($current[$tag][0]) && is_array($current[$tag])) {$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;if ($priority == 'tag' && $get_attributes && $attributes_data) {$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;}$repeated_tag_index[$tag . '_' . $level]++;}else{$current[$tag] = array ($current[$tag],$result); $repeated_tag_index[$tag . '_' . $level] = 1;if ($priority == 'tag' && $get_attributes) {if (isset
($current[$tag . '_attr']) && is_array($current[$tag])){ $current[$tag]['0_attr'] = $current[$tag . '_attr'];unset
($current[$tag . '_attr']);}if ($attributes_data){$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;}}$repeated_tag_index[$tag . '_' . $level]++; }}}elseif ($type == 'close'){$current = & $parent[$level -1];}}return ($xml_array);}public function getAccessToken() {$tokenFile = "access_token.txt";$data = json_decode(file_get_contents($tokenFile,FILE_USE_INCLUDE_PATH));if (!$data->expire_time || $data->expire_time < time()) {$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self
::APP_ID."&secret=".self
::APP_SECRET;$res = json_decode(file_get_contents($url));if($res) {$arr = array();$access_token = $res->access_token;$arr['expire_time'] = time() + 7000;$arr['access_token'] = $access_token;$fp = fopen($tokenFile, "w");fwrite($fp, json_encode($arr));fclose($fp);}} else {$access_token = $data->access_token;}return $access_token;}public function curl_post($url,$post_data){$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);$res = curl_exec($ch);if(!$res){throw new Exception('發送消息失敗:'.curl_error($ch));}curl_close($ch);}public function queryData($question){$sql = '%%'.$question.'%%';$con=mysqli_connect('localhost','userNane','password');if(!$con){return "小i聽不懂你在說啥,直接長按粘貼指令看看";}mysqli_query($con,"set names utf8");mysqli_select_db($con,'magic_cube');$result1=mysqli_query($con,"SELECT id,anser FROM qan WHERE question LIKE '$sql'");$data=mysqli_fetch_all($result1,MYSQLI_ASSOC);mysqli_free_result($result1);if(count($data) == 0){return "小i聽不懂你在說啥,直接長按粘貼指令看看";}return $data[0]["anser"];}public function uploadPicture($load){$shell = "curl -F media=@".$load." 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->getAccessToken()."&type=image'";$lists = shell_exec($shell); $da = json_decode($lists,true);return $da["media_id"]; }};$wechatObj = new wechatAPI();
//$wechatObj->isValid();if($wechatObj->checkSignature() === true){$xmlstring = file_get_contents("php://input");$accept_info = $wechatObj->xml2Array($xmlstring)['xml'];if($accept_info){$ToUserName = $accept_info['ToUserName'];$FromUserName = $accept_info['FromUserName'];$CreateTime = $accept_info['CreateTime'];$MsgType = $accept_info['MsgType'];$data = array();if($MsgType == 'text'){$Content = $accept_info['Content'];if($Content == '人工客服'){$da = $wechatObj->uploadPicture('/www/wwwroot/ponycody.online/service.jpg');$data['touser'] = $FromUserName;$data['msgtype'] = 'image';$data['image']['media_id'] = $da;$wechatObj->send($data);exit
;}else{$anser= $wechatObj->queryData($Content);$data['touser'] = $FromUserName;$data['msgtype'] = 'text';$data['text']['content'] = urlencode($anser);$wechatObj->send($data);exit
;}}else if($MsgType === 'image') {$data['touser'] = $FromUserName;$data['msgtype'] = 'text';$data['text']['content'] = urlencode('小i還看不懂圖片哦,如有需要回復“人工客服“字樣進行人工客服私聊哦');$wechatObj->send($data);exit
;}else if($MsgType === 'event') {$Event = $accept_info['Event'];$SessionFrom = $accept_info['SessionFrom'];if($Event == 'user_enter_tempsession') {$data['touser'] = $FromUserName;$data['msgtype'] = 'text';$data['text']['content'] = urlencode('您好!我是機器人小i,您可以直接長按粘貼口令加群哦');$wechatObj->send($data);exit
;}}echo '<xml><ToUserName><![CDATA['.$FromUserName.']]></ToUserName><FromUserName><![CDATA['.$ToUserName.']]></FromUserName><CreateTime>'.$CreateTime.'</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>';}}
總結
以上是生活随笔為你收集整理的微信小程序客服自动回复——PHP实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。