我开发两个公众平台的应用,一个是天气宝宝,一个是翻译宝宝,其中天气宝宝返回的是图文信息、翻译宝宝返回的是文字信息,接下来将以这两个应用为例讲解公众平台应用的开发。
翻译宝宝使用的是有道翻译的api,但是有道翻译的api是有使用限制的,每个小时不超过1000次,对于大部分人来说,这已经够了,申请的地址:http://fanyi.youdao.com/openapi?path=data-mode ,申请完后就有API Key了。
下面是翻译宝宝第一版本的源码:
<!--?php /** * wechat php test */ //
define your token define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj--->responseMsg();
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 = $keyword;
// 判断是否首次关注
if ( $keyword == "Hello2BizUser" ) {
$contentStr = "欢迎关注翻译宝宝,请输入你要翻译的单词或句子!";
}else {
$contentStr =YouDaoTranslate($keyword);
}
$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;
}
}
}
/**
*
* http://fanyi.youdao.com/openapi.do?keyfrom=&key=&type=data&doctype=json&version=1.1&q=翻译
{
"errorCode":0
"query":"翻译",
"translation":["translation"], // 有道翻译
"basic":{ // 有道词典-基本词典
"phonetic":"fān yì",
"explains":[
"translate",
"interpret"
]
},
"web":[ // 有道词典-网络释义
{
"key":"翻译",
"value":["translator","translation","translate","Interpreter"]
},
{...}
]
}
*/
function YouDaoTranslate($keyword) {
$url="http://fanyi.youdao.com/openapi.do?keyfrom=*****&key=*******&type=data&doctype=json&version=1.1&q=".urlencode($keyword);
//初始化一个cURL对象
$curl=curl_init();
//设置要抓取的URL
curl_setopt($curl,CURLOPT_URL,$url);
//设置cURL参数,要求结果保存到字符串中还是输出到屏幕上
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
//运行cURL,请求网页
$output=curl_exec($curl);
//解析返回的结果,设置true是在php中将其转为数组
$youdaoResult=json_decode($output,true);
$errorcode=$youdaoResult['errorCode'];
foreach ($explains as $value){
$translation=$translation."\n".$value;
}
return $youdaoResult['translation'][0];
}
?>
没有评论:
发表评论