官方demo文件:wx_sample.php
<?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;
}
}
}
?>
在此基础上封装的
<?php
require 'Wechat.class.php';
/**
* 微信接口文件
*/
//define your token
define("TOKEN", "token");
class WeiXin extends Wechat
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
public function responseMsg()
{
/**
* 处理微信服务器发送过来xml数据
*/
//get post data, May be due to the different environments
// 获取微信服务器发送过来的xml数据
$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);
// 将获取xml数据转成simple对象
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
/**
* 响应消息
*/
switch ($postObj->MsgType) {
case "text":
if($keyword == "文本"){
$this->sendText($fromUsername, $toUsername, "你要的是文本!");
}elseif($keyword == "图片"){
//$img = "Orlaq3o42ukYZG_6cPu5-RVKYiRneHaR-iIcQvrHzqPaLaK4JymWGYuVsbCR_5o-";
$file = dirname(__FILE__)."/pic/23.jpg"; // 返回的图片信息
$media_id = $this->getMediaId($file, 'image'); // 获取图片的media_id
$this->sendImg($fromUsername, $toUsername,$img);
}elseif($keyword == "视频"){
$vid1 = "5mYa7-YoFgHlAN09G0VVsFVf0rwec0D1_Ed1TfBv1vbl1UNH7KgBFpYVtL5DiG1F";
$this->sendVideo($fromUsername, $toUsername,$vid1,"^-^","看看这是谁");
}elseif($keyword == "音乐"){
$musicUrl1 = "http://47.106.71.212/music/TakeMeToYourHeart.mp3";
//音乐缩略图
$thumbMediaId1 = "3X4HZhK6Qvq9Dw_shLX5wslP3da6keykdtahtZzuy-qJ7iUnyzybYc8n6yv8a41u";
$this->sendMusic($fromUsername, $toUsername,"Take Me To Your Heart","动听的相思歌曲",$musicUrl1,$thumbMediaId1);
}elseif($keyword == "单图文"){
$test1 = array(
array(
"title" => "测试title",
"description" => "测试description",
"picurl" => "http://47.106.71.212/pic/23.jpg",
"url" => "http://www.nhphp.com"
)
);
$this->sendImgArticle($fromUsername, $toUsername,$test1);
}elseif($keyword == "多图文"){
$test2 = [
[
"title" => "测试多图文title",
"description" => "测试多图文description",
"picurl" => "http://47.106.71.212/pic/9.jpg",
"url" => "http://www.nhphp.com"
],
[
"title" => "美丽中国",
"description" => "中国很美丽",
"picurl" => "http://47.106.71.212/pic/c.jpg",
"url" => "http://47.106.71.212/密钥.txt"
],
[
"title" => "美丽肉肉",
"description" => "肉肉很可爱",
"picurl" => "http://47.106.71.212/pic/rr.jpg",
"url" => "http://www.nhphp.com"
]
];
$this->sendImgArticle($fromUsername, $toUsername,$test2);
}
break;
case "image":
$this->sendText($fromUsername, $toUsername, "你输入的是图片!");
break;
case "event":
if($postObj->Event == "subscribe"){
$this->sendText($fromUsername, $toUsername, "欢迎关注“PHP各种不明白^-^”!");
}elseif($postObj->Event == "unsubscribe"){
//$this->sendText($fromUsername, $toUsername, "欢迎再次关注!");
}elseif($postObj->Event == "CLICK" && $postObj->EventKey == "V1001_TODAY_MUSIC"){
$musicUrl1 = "http://47.106.71.212/music/TakeMeToYourHeart.mp3";
//音乐缩略图
$thumbMediaId1 = "3X4HZhK6Qvq9Dw_shLX5wslP3da6keykdtahtZzuy-qJ7iUnyzybYc8n6yv8a41u";
$this->sendMusic($fromUsername, $toUsername,"Take Me To Your Heart","动听的相思歌曲",$musicUrl1,$thumbMediaId1);
}elseif($postObj->Event == "CLICK" && $postObj->EventKey == "V1001_TODAY_TEX"){
$this->sendText($fromUsername, $toUsername, "这是一个美丽的故事......!");
}elseif($postObj->Event == "CLICK" && $postObj->EventKey == "V1001_TODAY_VOIDE"){
$vid1 = "5mYa7-YoFgHlAN09G0VVsFVf0rwec0D1_Ed1TfBv1vbl1UNH7KgBFpYVtL5DiG1F";
$this->sendVideo($fromUsername, $toUsername,$vid1,"^-^","看看这是谁");
}elseif($postObj->Event == 'CLICK' && $postObj->EventKey == 'V1001_TODAY_IMGARTICLE'){
$this->sendText($fromUsername, $toUsername, '图文还没写');
}
break;
default:
$this->sendText($fromUsername, $toUsername, "你输入的是我不认识的格式!");
break;
}
}else {
echo "网页访问显示";
exit;
}
}
//自定义响应函数
/**
* 回复文本消息
* @param string $fromUsername 微信用户
* @param string $toUsername 微信公众帐号
* @param string $content 回复文本的内容
*/
public function sendText($fromUsername, $toUsername, $content)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $content);
echo $resultStr;
}
/**
* 回复图片消息
* @param string $fromUsername 微信用户
* @param string $toUsername 微信公众帐号
* @param string $media_id 回复图片的media_id
*/
public function sendImg($fromUsername, $toUsername,$media_id)
{
$imgTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
$resultStr = sprintf($imgTpl, $fromUsername, $toUsername, time(), $media_id);
echo $resultStr;
}
/**
* 回复视频消息
* @param string $fromUsername 微信用户
* @param string $toUsername 微信公众帐号
* @param string $media_id 回复视频的media_id
* @param string $title 回复视频的标题
* @param string $description 回复视频的描述
*/
public function sendVideo($fromUsername, $toUsername,$media_id,$title,$description)
{
$videoTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
<Video>
<MediaId><![CDATA[%s]]></MediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>
</xml>";
$resultStr = sprintf($videoTpl, $fromUsername, $toUsername, time(), $media_id,$title,$description);
echo $resultStr;
}
/**
* 回复音乐消息
* @param string $fromUsername 微信用户
* @param string $toUsername 微信公众帐号
* @param string $content 回复文本的内容
* @param string $title 回复音乐的标题
* @param string $description 回复音乐的描述
* @param string $description 回复音乐的地址
* @param string $description 回复音乐的缩略图的mediaid
*/
public function sendMusic($fromUsername, $toUsername,$title,$description,$musicUrl,$thumbMediaId)
{
$musicTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
</Music>
</xml>";
$resultStr = sprintf($musicTpl, $fromUsername, $toUsername, time(),$title,$description,$musicUrl,$musicUrl,$thumbMediaId);
echo $resultStr;
}
/**
* 回复图文消息
* @param string $fromUsername 微信用户
* @param string $toUsername 微信公众帐号
* @param string $array 回复图文消息的数组['title','description','picurl','url']
*/
public function sendImgArticle($fromUsername, $toUsername,$array)
{
$artTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>";
foreach($array as $val){
$artTpl .= "<item>
<Title><![CDATA[{$val['title']}]]></Title>
<Description><![CDATA[{$val['description']}]]></Description>
<PicUrl><![CDATA[{$val['picurl']}]]></PicUrl>
<Url><![CDATA[{$val['url']}]]></Url>
</item>";
}
$artTpl .= "</Articles>
</xml>";
$resultStr = sprintf($artTpl, $fromUsername, $toUsername, time(),count($array));
echo $resultStr;
}
/**
* 验证加密签名
*/
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;
}
}
}
$wechatObj = new WeiXin();
//$wechatObj->valid();//验证服务器的方法,成功之后注释
$wechatObj->responseMsg(); //开启消息自动回复
?>
引用的封装Wechat.class.php内容如下
<?php
/**
* 微信工具类
*/
define("APPID", ''); // 开发者ID
define("SECRET", ''); // 开发者密钥
class Wechat{
/**
* 新增素材
* @param string $file 新增的素材
* @param string $type 新增的素材类型
* @return string 新增素材的media_id
*/
public function getMediaId($file, $type){
// 设置接口参数
$param = array(
'access_token' => $this->getAccessToken(),
'type' => $type
);
$api = "https://api.weixin.qq.com/cgi-bin/media/upload?".http_build_query($param);
$postData = array(
'media' => new CURLFile($file), #获取文件信息
);
// 发送请求
$rs = $this->httpRequest($api, $postData);
// 将json字符串转成php数组
$data = json_decode($rs, true);
return $data['media_id'];
}
/**
* 获取access_token
* @return string access_token值
*/
public function getAccessToken(){
// 设置接口参数
$param = array(
'appid' => APPID,
'secret' => SECRET,
);
$api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&'.http_build_query($param);
// 发送接口请求
$rs = $this->httpRequest($api);
// 将获取的json字符串转成php数组
$data = json_decode($rs, true);
return $data['access_token'];
}
/**
* 发送http请求
* @param string $url 请求地址
* @param array $postData 请求(post)发送的数据
* @return string 获取的数据
*/
public function httpRequest($url, $postData=array()){
// (1)初始化
$ch = curl_init();
// (2)设置选项
// 设置请求的url
curl_setopt($ch, CURLOPT_URL, $url);
// 将curl_exec()获取的数据以字符串返回,而不是直接输出。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($postData)){
// 设置请求方式为post
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
//curl注意事项,如果发送的请求是https,必须要禁止服务器端校检SSL证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// (3)执行
$result = curl_exec($ch);
// (4)关闭
curl_close($ch);
return $result;
}
}
$obj = new Wechat();
$res = $obj->getAccessToken();
var_dump($res);