PHP微信开发入门之关注回复(一)
这里用的是PHP的原生代码写的,怕初学者被一些框架所混淆,就选择了原生来展示
话不多说,先贴代码。后面有详情介绍
<?php
//定义一个TOKEN
define('TOKEN','g825482785');
//实例化类
$weobj = new wechatCallbackapiTest();
if(!isset($_POST['echostr']))
{
$weobj->responseMsg();
}
else
{
$weobj->valid();
}
$weobj->responseMsg();
//创建一个类
class wechatCallbackapiTest
{
public $fromUsername = '';
public $toUsername = '';
public $time = '';
public function valid()
{
$echostr = $_POST['echostr'];
if($this->checkSignature())
{
echo $echostr;
exit;
}
}
/*
* 检验signature
* 涉及PHP函数
* 1.sort()一组数据排序
* 2.implode()将一个一维数组转换为字符串
* 3.sha1()利用美国安全散列算法计算字符串的sha1散列值
*/
private function checkSignature()
{
$signature = $_POST['signature'];
$timestamp = $_POST['timestamp'];
$nonce = $_POST['nonce'];
$TOKEN = TOKEN;
$tmpArr = array($TOKEN , $timestamp , $nonce);
sort($tmpArr , SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if($tmpStr == $signature)
{
return true;
}
else
{
return false;
}
}
/**
* @author gf
* 接收收据返回数据
* 涉及函数
* 1.simplexml_load_string()把XML字符串载入对象中
* 2.trim()去除字符串两边空白字符
* 3.time()获得当前时间的时间戳
* 4.strtolower()将字符串转换为小写
* 5.sprintf()把格式化的字符串写入变量中
*/
public function responseMsg() {
//---------- 接 收 数 据 ---------- //
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据
//用SimpleXML解析POST过来的XML数据
$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)
$toUsername = $postObj->ToUserName; //获取接收方账号
$keyword = trim($postObj->Content); //获取消息内容
$type = $postObj->MsgType;
$time = time(); //获取当前时间戳
$PicUrl = $postObj->PicUrl;
$msgId = $postObj->msgId;
$event = $postObj->Event;
//判断类型
if(strtolower($type) == 'event') {
//subscribe事件 关注微信号即可触发。微信开发文档有详细说明
if ($event == 'subscribe') {
$msgType = 'text';
$content = '欢迎大家关注我的微信账号!';
//text格式的xml
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $content);
echo $resultStr;
}
}
}
}
涉及到的PHP函数:
1.define('常量名','常量值') 定义常量
2.sort()将一组数据排序
3.implode()将一个一维数组转换为字符串
4.sha1()利用美国安全散列算法计算字符串的sha1()散列值
5.simplexml_load_string()把XML字符载入对象中
6.trim()去除字符串首尾空白
7.time()获取当前时间的时间戳
8.strtolower()将字符串转换为小写
9.sprintf()把格式化的字符串写入变量中
这里要注意的也就是微信里的token一定要跟你定义的TOKEN值相同。
其余的可以在网页代码调试中断点排查出他的问题。
希望能帮到大家。
浙公网安备 33010602011771号