微信公众号添加天气预报功能

首先打开微信公众平台,登录自己的账号,


然后将自己的外网的url路径写入,写入token值,加入方式选为明文方式,并用fz上传你要写入的token值判断是否正确。

<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "weixin");
$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)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$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()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>

当审核通过通过token值的时候在源代码上添加天气查询的功能

<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
//$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);
                $RX_TYPE = trim($postObj->MsgType);

                switch($RX_TYPE)
                {
                    case "text":
                        $resultStr = $this->handleText($postObj);
                        break;
                    case "event":
                        $resultStr = $this->handleEvent($postObj);
                        break;
                    default:
                        $resultStr = "Unknow msg type: ".$RX_TYPE;
                        break;
                }
                echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    public function handleText($postObj)
    {
        $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";
			$url="http://api.k780.com:88/?app=weather.future&appkey=14323&sign=0111aa8a973785f0f0926aff75f5af52&format=json&weaid=".$keyword;
				$str=file_get_contents($url);
				$s=json_decode($str);
				$a=$s->result;
				$date=date("Y-m-d");
				foreach($a as $k => $v){
					if($v->days == $date){
						$today=$a[$k];
					}
				}
				$msgType = "text";
				if($today->citynm==""){
					$contentStr='请正确输入城市名';
				}else{
					$contentStr = '城市:'.$today->citynm.',时间:'.$today->days.',星期:'.$today->week.',温度:'.$today->temperature.',风向:'.$today->wind.',风级:'.$today->winp;
				}				
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
				echo $resultStr;
        }else{
            echo "Input something...";
        }
    }

    public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
                $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待...";
                break;
            default :
                $contentStr = "Unknow Event: ".$object->Event;
                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }
    
    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }


    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;
        }
    }
}

?>

完成!!!!

### 创建和配置微信公众号的二级菜单栏 在Java环境中开发微信公众号时,为了实现更复杂的功能并提升用户体验,开发者可以通过API调用来创建包含子项(即二级菜单)的一级菜单。具体来说,在构建`menuJson`字符串期间,应当遵循特定结构来表示多层菜单体系[^1]。 #### JSON格式说明 对于每一级菜单而言,都需指定名称(`name`)以及链接地址(`url`);如果该选项作为父节点,则还需声明其下的子集数组(`sub_button`)。下面是一个用于描述带有一个或多个子按钮的一级项目的JSON片段: ```json { "button": [ { "type": "click", "name": "一级菜单名", "key": "V1001_HELLO_WORLD" }, { "name": "更多服务", "sub_button": [ { "type": "view", "name": "天气预报", "url": "http://www.weather.com.cn/" }, { "type": "miniprogram", "name": "小游戏中心", "url": "https://mp.weixin.qq.com/", "appid": "wx286b93c14bbf93aa", "pagepath": "/index/index" } ] } ] } ``` 此示例展示了如何通过定义`sub_button`属性为一个列表的方式添加两个不同类型的二级菜单——一个是跳转至网页视图(`view`),另一个则是启动小程序(`miniprogram`)。值得注意的是,当涉及到URL参数传递时,应确保对其进行适当编码处理以防止特殊字符引起解析错误[^3]。 #### Java代码实现 以下是基于上述逻辑编写的部分Java方法概览,负责组装最终发送给微信公众平台服务器的消息体: ```java public class WeChatMenuCreator { public static String createSubMenu(String parentName, List<MenuItem> items){ StringBuilder sb = new StringBuilder(); sb.append("{\"name\":\"").append(parentName).append("\",\"sub_button\":["); boolean firstItem=true; for(MenuItem item : items){ if(!firstItem)sb.append(","); else firstItem=false; switch(item.getType()){ case CLICK: sb.append("{ \"type\": \"click\", "); break; case VIEW: sb.append("{ \"type\": \"view\", "); break; default: throw new UnsupportedOperationException("Unsupported menu type."); } sb.append("\"name\":\"").append(item.getName()).append("\","); if (item.getUrl()!=null && !item.getUrl().isEmpty()) sb.append("\"url\":\"").append(URLEncoder.encode(item.getUrl(), StandardCharsets.UTF_8)).append("\""); if (item.getKey()!=null && !item.getKey().isEmpty()) sb.append("\"key\":\"").append(item.getKey()).append("\""); sb.append("}"); } sb.append("]}"); return sb.toString(); } // ...其他辅助函数... } class MenuItem { private MenuType type; // 枚举类型:CLICK,VIEW等 private String name; private String url; private String key; // Getters and Setters omitted. } ``` 这段程序片段提供了创建带有子菜单条目的功能,并且考虑到了不同类型菜单之间的差异性。例如点击事件触发(`CLICK`)与页面浏览(`VIEW`)的区别在于后者通常会携带具体的网络资源定位符(URL),而前者则关联到预设好的消息键值(KEY)。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值