<?php
// 定义token
define("TOKEN","youdian");
// 实例化当前的微信类
$wechat = new Wechat();
// 判断是通过微信后台点击提交按钮进行验证,还是通过微信客户端输入内容进行响应
if($_GET['echostr']){
//验证
echo $wechat->checkSignature();
}else{
//响应
echo $wechat->response();
}
//创建一个微信类
class Wechat{
//检测是否为微信服务器传过来的数据
function checkSignature(){
//获取相应的参数
$signature = $_GET['signature']; // 获取加密签名
// 获取时间戳
$timestamp = $_GET['timestamp'];
// 获取随机数
$nonce = $_GET['nonce'];
//创建数组
$arr = array($timestamp, $nonce,TOKEN);
//对数组进行字典排序
sort($arr, SORT_STRING);
//对数组进行拆分
$str = implode( $arr );
// 进行加密
$strSha1 = sha1($str);
//进行检测 生成的加密字符窜与传过来的微信加密签名是否一致
if( $strSha1 == $signature ){
return $_GET['echostr'];
}
}
//响应
function response(){
// echo 123;
/*
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
*/
// 原生的post数据 字符窜 xml
$poststr = $GLOBALS['HTTP_RAW_POST_DATA'];
//将原生的post字符串数据变成对象
$postobj = simplexml_load_string($poststr, 'SimpleXMLElement', LIBXML_NOCDATA);
//返回hello world
$touser = $postobj->ToUserName; // 接收时的接收方,返回时的发送方
$fromuser = $postobj->FromUserName; // 接收时的发送方,返回时的接收方
switch($postobj->MsgType){
case "text":
$content = $postobj->Content;// 接收到的文本内容
$xml = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
// return sprintf($xml,$fromuser,$touse,time(),"hello world!");
break;
case "image":
$content = $postobj->MediaId;
$xml = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
break;
}
return sprintf($xml,$fromuser,$touse,time(),$content);
}
}
//调用相应的函数
// echo checkSignature();
?>
联接ngrok内网穿透软件+微信开发实现前台交互效果
最新推荐文章于 2024-06-17 17:38:07 发布