本节教程将写一个微信公众号demo
- 申请微信公众号
- 新浪云,百度云或者其他方式申请一个域名
- 我的是新浪云,填写好url和token
- 微信客户端,向公众号发出信息,公众号回复信息。
</pre><pre name="code" class="php"><?php
//define your token//自己的key,聚合数据免费申请很简单还有示例代码直接运行就好。
require_once 'responseMultiNews.func.inc.php';
header('Content-type:text/html;charset=utf-8');
define("TOKEN", "****");
$wechatObj = new wechatCallbackapiTest();
if(!isset($_GET['echostr'])){
$wechatObj->responseMsg();
}else{
$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);
$type = trim($postObj->Event);
$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($type == "subscribe")
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[微信开发视频教程]]></Title>
<Description><![CDATA[欢迎大家参加微信开发视频教程]]></Description>
<PicUrl><![CDATA[http://p0.so.qhimg.com/t013971ecacef25bf25.jpg]]></PicUrl>
<Url><![CDATA[http://www.so.com/s?q=图片&src=se6_toolbar&ie=utf-8&_jmp=1]]></Url>
</item>
</Articles>
</xml>
";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time);
echo $resultStr;
}
if(!empty( $keyword ))
{
$msgType = "text";
if(mb_substr($keyword,0,2,'utf-8') == "天气")
{
$cityname=mb_substr($keyword,2,5,'utf-8');
$url="http://v.juhe.cn/weather/index?format=2&cityname=".$cityname."&key=****";
$str=file_get_contents($url);
$de_json = json_decode($str,TRUE);
$contentStr="城市:".$de_json['result']['today']['city']."\n日期:".$de_json['result']['today']['date_y'].$de_json['result']['today']['week']."当前温度:"
.$de_json['result']['sk']['temp']."度\n当前天气:". $de_json['result']['sk']['wind_strength'].$de_json['result']['sk']['wind_direction'].
"\n今日温度:".$de_json['result']['today']['temperature']."\n今日天气:".$de_json['result']['today']['weather']."";
}else if(mb_substr($keyword,0,2,'utf-8') == "菜谱")
{
//************1.菜谱大全************
$url = "http://apis.juhe.cn/cook/query.php";
$greens_name = mb_substr($keyword,2,5,'utf-8');
$params = array(
"menu" => $greens_name,//需要查询的菜谱名
"key" => "*****",
"dtype" => "",
"pn" => "",
"rn" => "",
"albums" => "",
);
$paramstring = http_build_query($params);
$content = juhecurl($url,$paramstring);
$result = json_decode($content,true);
if($result){
if($result['error_code']=='0'){
//print_r($result);
$de_json2 = json_decode("[$content]",TRUE);
$count_json2 = count($de_json2);
for ($i = 0; $i < $count_json2; $i++)
{
//$data = json_encode($de_json2[$i]['data']);
$title = $de_json2[0]['result']['data'][0]['title'];
$imtro = $de_json2[0]['result']['data'][0]['imtro'];
$albums = $de_json2[0]['result']['data'][0]['albums'];
$albums_xin = $albums[0];
$stepsimg1 = $de_json2[0]['result']['data'][0]['steps'][0]['img'];
$stepsstep1 = $de_json2[0]['result']['data'][0]['steps'][0]['step'];
$stepsimg2 = $de_json2[0]['result']['data'][0]['steps'][1]['img'];
$stepsstep2 = $de_json2[0]['result']['data'][0]['steps'][1]['step'];
$stepsimg3 = $de_json2[0]['result']['data'][0]['steps'][2]['img'];
$stepsstep3 = $de_json2[0]['result']['data'][0]['steps'][2]['step'];
$stepsimg4 = $de_json2[0]['result']['data'][0]['steps'][3]['img'];
$stepsstep4 = $de_json2[0]['result']['data'][0]['steps'][3]['step'];
$stepsimg5 = $de_json2[0]['result']['data'][0]['steps'][4]['img'];
$stepsstep5 = $de_json2[0]['result']['data'][0]['steps'][4]['step'];
$stepsimg6 = $de_json2[0]['result']['data'][0]['steps'][5]['img'];
$stepsstep6 = $de_json2[0]['result']['data'][0]['steps'][5]['step'];
}
//$contentStr = "菜谱来了!菜名" . $title."\n描述 " .$imtro." \n图片 " .$albums." \n步骤1 ". $stepsstep1;
$record[0]=array(
'title' =>$title,
'description' =>$imtro,
'picUrl' =>$albums_xin,
'url' =>''
);
$record[1]=array(
'title' =>$stepsstep1,
'description' =>'',
'picUrl' =>$stepsimg1,
'url' =>''
);
$record[2]=array(
'title' =>$stepsstep2,
'description' =>'',
'picUrl' =>$stepsimg2,
'url' =>''
);
$record[3]=array(
'title' =>$stepsstep3,
'description' =>'',
'picUrl' =>$stepsimg3,
'url' =>''
);
$record[4]=array(
'title' =>$stepsstep4,
'description' =>'',
'picUrl' =>$stepsimg4,
'url' =>''
);
$record[5]=array(
'title' =>$stepsstep5,
'description' =>'',
'picUrl' =>$stepsimg5,
'url' =>''
);
$record[6]=array(
'title' =>$stepsstep6,
'description' =>'',
'picUrl' =>$stepsimg6,
'url' =>''
);
$resultStr = _response_multiNews($postObj,$record);
echo $resultStr;
}else if(mb_substr($keyword,0,2,'utf-8') == "旅游")
{
$record[0]=array(
'title' =>'平江路',
'description' =>'平江路位于苏州古城东北,是一条傍河的小路,北接拙政园,南眺双塔,全长1606米,是苏州一条历史攸久的经典水巷。宋元时候苏州又名平江,以此名路...',
'picUrl' => 'http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg',
'url' =>'http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000056&itemidx=1&sign=ef18a26ce78c247f3071fb553484d97a#wechat_redirect'
);
$record[1]=array(
'title' =>'拙政园',
'description' =>'拙政园位于江苏省苏州市平江区,是苏州四大古名园之一,也是苏州园林中最大、最著名的一座,被列入《世界文化遗产名录》,堪称中国私家园林经典...',
'picUrl' => 'http://joythink.duapp.com/images/suzhouScenic/zhuozhengyuan.jpg',
'url' =>'http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000040&itemidx=1&sign=a6d4921f2d17ba2ea3ef577608db887b#wechat_redirect'
);
$record[2]=array(
'title' =>'周庄',
'description' =>'周庄历经900多年沧桑,仍完整地保存着原来的水乡集镇的建筑风貌,全镇百分之六十以上的民居仍为明清建筑,有近百座古典宅院和60多个砖雕门楼,最有代表性的当数沈厅、张厅...',
'picUrl' => 'http://joythink.duapp.com/images/suzhouScenic/zhouzhuang.jpg',
'url' =>'http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000042&itemidx=1&sign=f3781d7c1f83b5a440c7339d0b17586c#wechat_redirect'
);
//$resultStr = _response_multiNews($postObj,$record);
$resultStr =_response_multiNews($postObj,$record);
echo $resultStr;
}else{
echo $result['error_code'].":".$result['reason'];
}
}else{
echo "请求失败";
}
}else{
$record[0]=array(
'title' =>'平江路'.'平江路位于苏州古城东北,是一条傍河的小路,北接拙政园,南眺双塔,全长1606米,是苏州一条历史攸久的经典水巷。宋元时候苏州又名平江,以此名路...',
'description' =>'',
'picUrl' => 'http://mmbiz.qpic.cn/mmbiz/Gugib1CGulhzHNAnibPqvWPluvMnazvzqsGraxkkXLRUguMgvU43ia58Poicc8TqF9jzGRpaF2B2YKljfRDEQ2VRsg/0?tp=webp&wxfrom=5',
'url' =>'http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000056&itemidx=1&sign=ef18a26ce78c247f3071fb553484d97a#wechat_redirect'
);
//$resultStr = _response_multiNews($postObj,$record);
$resultStr = _response_multiNews($postObj,$record);
echo $resultStr;
//$contentStr = "欢迎参加本次微信视频教程!";
}
$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;
}
}
}
/**
* 请求接口返回内容
* @param string $url [请求的URL地址]
* @param string $params [请求的参数]
* @param int $ipost [是否采用POST形式]
* @return string
*/
function juhecurl($url,$params=false,$ispost=0){
$httpInfo = array();
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if( $ispost )
{
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
curl_setopt( $ch , CURLOPT_URL , $url );
}
else
{
if($params){
curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
}else{
curl_setopt( $ch , CURLOPT_URL , $url);
}
}
$response = curl_exec( $ch );
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
curl_close( $ch );
return $response;
}
?>
<?php
/**
* 微信公众平台-多图文回复函数
* ================================
* Copyright 2013-2014 David Tang
* http://www.cnblogs.com/mchina/
* http://www.joythink.net/
* ================================
* Author:David
* 个人微信:mchina_tang
* 公众微信:zhuojinsz
* Date:2013-10-11
*/
/**
* _response_news() 返回多图文格式信息
* @param $object 消息类型
* @param $newsContent 消息内容
* 传入数组格式(多维数组)
Array
(
[0] => Array
(
[title] => 观前街
[description] => 观前街位于江苏苏州市区...
[picUrl] => http://joythink.duapp.com/images/suzhou.jpg
[url] => http://mp.weixin.qq.com
)
[1] => Array
(
[title] => 拙政园
[description] => 拙政园位于江苏省苏州市平江区...
[picUrl] => http://joythink.duapp.com/images/suzhouScenic/zhuozhengyuan.jpg
[url] => http://mp.weixin.qq.com
)
)
* @return 处理过的具有格式的多图文消息
*/
function _response_multiNews($object,$newsContent)
{
$newsTplHead = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>";
$newsTplBody = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
$newsTplFoot = "</Articles>
<FuncFlag>0</FuncFlag>
</xml>";
$bodyCount = count($newsContent);
$bodyCount = $bodyCount < 10 ? $bodyCount : 10;
$header = sprintf($newsTplHead, $object->FromUserName, $object->ToUserName, time(), $bodyCount);
foreach($newsContent as $key => $value){
$body .= sprintf($newsTplBody, $value['title'], $value['description'], $value['picUrl'], $value['url']);
}
$FuncFlag = 0;
$footer = sprintf($newsTplFoot, $FuncFlag);
return $header.$body.$footer;
}
?>
参考大神的代码更详细: http://www.cnblogs.com/mchina/p/3364377.html
入门课程: http://www.chuanke.com/v1324475-111278-232540.html
聚合数据: https://www.juhe.cn/
新浪云平台部署代码,直接上传php文件就好了通过url访问看看没错,公众号直接发送消息
注册新浪云的话用下这个链接:http://t.cn/RGWYJ9U
咱们都有200云豆,一天只要10云豆。
代码下载:https://pan.baidu.com/s/1o7rvX8I