复制下面的php代码执行一下,得到access_token,一天上线2000次请求
$appid = "此处填写你的AppID(应用ID)"; $appsecret = "此处填写你的AppSecret(应用密钥)"; define("APPID",$appid); define("APPSECRET",$appsecret); $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET; $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 $access_token = $result['access_token']; echo $access_token;
下面这段代码已经调试好了,可直接运行,启用服务器配置。填写匹配Token(令牌)的关键代码。
/** * wechat php test */ //define your token define("TOKEN", "wudiphp"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->valid(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if ($this->checkSignature()) { echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $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>"; if (!empty($keyword)) { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } else { echo "Input something..."; } } 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; } } }
下面是关键的图灵聊天机器人接口函数,我放在function.php里面
/** * 机器人问答返回内容 * @param string $url [请求的URL地址] * @param string $params [请求的参数] * @param int $ipost [是否采用POST形式] * @return string */ function wenda($info){ header('Content-type:text/html;charset=utf-8'); //************1.问答************ $url = "http://op.juhe.cn/robot/index"; $params = array( "key" => "5e70fea5553d2deea473c13b516a564a",//您申请到的本接口专用的APPKEY "info" => $info,//要发送给机器人的内容,不要超过30个字符 "dtype" => "",//返回的数据的格式,json或xml,默认为json "loc" => "",//地点,如北京中关村 "lon" => "",//经度,东经116.234632(小数点后保留6位),需要写为116234632 "lat" => "",//纬度,北纬40.234632(小数点后保留6位),需要写为40234632 "userid" => "",//1~32位,此userid针对您自己的每一个用户,用于上下文的关联 ); $paramstring = http_build_query($params); $content = juhecurl($url,$paramstring); $result = json_decode($content,true)["result"]["text"]; $resulturl = json_decode($content,true)["result"]["url"]; if ($resulturl) { $result=$result.'请点击'.' '.$resulturl; } return $result; }