php 公众号回复天气预报,微信公众号开发天气自动回复

当用户输入一个地名的时候,回复该地区的当前天气预报。使用的api接口为https://www.sojson.com/open/api/weather/json.shtml?city=北京返回的数据为json。自己提取相关的信息,为了方便演示,我只是回复了天气情况,有需要的可以自己添加相关的功能。

实例代码:<?php

namespace Wx\Controller;

use Think\Controller;

class IndexController extends Controller {

public function index(){

//获得参数 signature nonce token timestamp echostr

$nonce = $_GET['nonce'];

$token = 'xxxx';

$timestamp = $_GET['timestamp'];

$echostr = $_GET['echostr'];

$signature = $_GET['signature'];

//形成数组,然后按字典序排序

$array = array();

$array = array($nonce, $timestamp, $token);

sort($array);

//拼接成字符串,sha1加密 ,然后与signature进行校验

$str = sha1( implode( $array ) );

if( $str == $signature && $echostr ){

//第一次接入weixin api接口的时候

echo $echostr;

exit;

}else{

$this->reponseMsg();

}

}

public function reponseMsg(){

//1.获取到微信推送过来post数据(xml格式)

$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];

//2.处理消息类型,并设置回复类型和内容

$postObj = simplexml_load_string( $postArr );//xml转换成对象

//判断是否是用户回复过来的消息

//用户发送过来消息后回复图文消息或者是单文本消息

if( strtolower($postObj->MsgType) == 'text' ){

$toUser = $postObj->FromUserName;

$fromUser = $postObj->ToUserName;

$content = $this->weather($postObj->Content);

$toUser = $postObj->FromUserName;

$fromUser = $postObj->ToUserName;

$time = time();

$msgType = 'text';

$template = "

%s

";

$info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);

echo $info;

}

}

public function weather($city){

//1.初始化curl

$ch = curl_init();

$url = 'https://www.sojson.com/open/api/weather/json.shtml?city='.$city;

//2.设置curl的参数

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//3.采集

$output = curl_exec($ch);

//4.关闭

curl_close($ch);

$wt = (array) json_decode($output,true);

$wet = $wt["data"]["forecast"][0]["type"];

return $wet;

}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值