1
0
Fork 0
mirror of https://github.com/yunluo/gdk.git synced 2024-04-27 20:23:05 +02:00
gdk/class/wechat.php
2021-10-10 21:48:53 +08:00

105 lines
3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
//error_reporting(0);
class Wechat_Captcha
{
public function __construct($wx_token, $wx_captcha)
{
$this->token = $wx_token;
$this->captcha = $wx_captcha;
}
private function __checkSignature()
{
$signature = $_GET['signature'];
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
$token = $this->token;
$tmpArr = [$token, $timestamp, $nonce];
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
return $tmpStr == $signature ? true : false;
}
public function responseMsg()
{
//如果是验证请求,则执行签名验证并退出
if (!empty($_GET['echostr'])) {
$this->valid();
//验证签名是否有效
return;
//返回退出
}
if ('POST' != $_SERVER['REQUEST_METHOD']) {
echo '';
return;
}
//如果不是验证请求,则
//首先取得POST原始数据(XML格式)
//$postData = $GLOBALS["HTTP_RAW_POST_DATA"];
$postData = file_get_contents('php://input');
if (empty($postData)) {
echo '';
return;
}
//如果没有POST数据则退出
if (!empty($postData)) {
//解析POST数据(XML格式)
$object = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
$messgeType = trim($object->MsgType); //取得消息类型
$this->fromUser = $object->FromUserName;
$this->toUser = $object->ToUserName;
$keyword = trim($object->Content);
if ('text' == $messgeType && '验证码' == $keyword) {
$response_content = '您的验证码为:【'.$this->captcha.'】验证码有效期为2分钟请抓紧使用过期需重新申请';
$xmlTemplate = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>';
$xmlText = sprintf($xmlTemplate, $this->fromUser, $this->toUser, time(), $response_content, 0);
echo $xmlText;
}
} else {
echo '';
exit;
}
}
protected function _valid()
{
$echoStr = $_GET['echostr'];
//valid signature , option
if ($this->checkSignature()) {
echo $echoStr;
exit;
}
echo 'error signature';
}
}
function wx_process()
{
if (isset($_GET['signature'])) {
global $wx_captchas;
if (!isset($wx_captchas)) {
$wx_token = gdk_option('gdk_wxmp_token');
$wx_captchas = new Wechat_Captcha($wx_token, wx_captcha());
$wx_captchas->responseMsg();
exit;
}
}
}
add_action('parse_request', 'wx_process', 4);