微信公众平台体验(二)(单词翻译)
谢谢关注公众账号:baiducha
首先去官网注册,填写相关信息,并设置为开发者模式以及下载开发示例。
将文档上传至自己的空间,我用的是新浪的SAE。通过验证后,注释掉 示例代码中德$wechatObj->valid();并加上$wechatObj->responseMsg();
- //$wechatObj->valid();
- $wechatObj->responseMsg();
找到if(!empty( $keyword )){} 在这里处理用户发来的信息。。。
先来实现一个简单的单词翻译功能。
- $contentStr = youdao($keyword);//用户发来的词汇
- $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
- echo $resultStr;
调用了有道接口;;可以自己去申请一个。。。下面是接口函数:
- function youdao($word){
- $encode = mb_detect_encoding($word, array("ASCII","GB2312","GBK","UTF-8"));
- if ($encode != "UTF-8"){
- $word = iconv($encode,"UTF-8",$word);
- }
- $ydapi = "http://fanyi.youdao.com/openapi.do?keyfrom=(*此处为申请的key)&key=(*此处为申请的key值)&type=data&doctype=json&version=1.1&q=".$word;
- $fetch = new SaeFetchurl();
- $content = $fetch->fetch($ydapi);
- $de_con = json_decode($content,true);
- $ercode = $de_con['errorCode'];
- $phonetic = $de_con['basic']['phonetic'];
- $explain0 = $de_con['basic']['explains'][0];
- $explain1 = $de_con['basic']['explains'][1];
- $explain2 = $de_con['basic']['explains'][2];
- $result ="";
- if(isset($ercode)){
- switch($ercode){
- case 0:
- $result = $de_con['translation']['0'];
- break;
- case 20:
- $result = "要翻译的文本过长";
- break;
- case 30:
- $result = "无法进行有效翻译";
- break;
- case 40:
- $result = "不支持的翻译类型";
- break;
- case 50:
- $result = "功能被禁用";
- break;
- default:
- $result ="未知错误";
- break;
- }
- }
- return $result."\n".$phonetic."\n".$explain0."\n".$explain1."\n".$explain2;
- }
到这里已经可以翻译英文单词了
原帖:
微信公众平台搭建之一(单词翻译)
http://www.austgl.com/b/thread-297-1-1.html