/** * 检查配置token */
public function check_server() {
//这个echostr呢 只有说验证的时候才会echo 如果是验证过之后这个echostr是不存在的字段了 if($_GET['echostr']){
$echoStr = $_GET["echostr"];
if ($this->checkSignature()) {
ob_clean();//防止之前缓存区数据影响
echo $echoStr;
exit;
}
}else{
$this->response_msg(); //如果没有echostr,则返回消息
}
}
/** * 验证微信开发者模式接入是否成功 */
private function checkSignature() {
//signature 是微信传过来的签名
$signature = $_GET["signature"];
//微信发过来的时间戳
$timestamp = $_GET["timestamp"];
//微信传过来的值随机字符串
$nonce = $_GET["nonce"];
//定义你在微信公众号开发者模式里面定义的token 这里举例为weixin
$token = "baigebao";
//三个变量 按照字典排序 形成一个数组
$tmpArr = array(
$token,
$timestamp,
$nonce
);
// 字典排序
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
//哈希加密 在laravel里面是Hash::
$tmpStr = sha1($tmpStr);
//哈希加密后的数据 和微信服务器传过来的签名比较
if ($tmpStr == $signature) {
return true;
} else {
return false;
}
}
/** * @name 消息接收 * @author weikai */
public function response_msg() {
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr) && is_string($postStr)){
//禁止引用外部xml实体
//libxml_disable_entity_loader(true);
//$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$postArr = json_decode($postStr,true);
if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){
//文本消息
$fromUsername = $postArr['FromUserName']; //发送者openid
$toUserName = $postArr['ToUserName']; //小程序id
$textTpl = array(
"ToUserName"=>$fromUsername,
"FromUserName"=>$toUserName,
"CreateTime"=>time(),
"MsgType"=>"transfer_customer_service",
);
exit(json_encode($textTpl));
}elseif(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){
//图文消息
$fromUsername = $postArr['FromUserName']; //发送者openid
$toUserName = $postArr['ToUserName']; //小程序id
$textTpl = array(
"ToUserName"=>$fromUsername,
"FromUserName"=>$toUserName,
"CreateTime"=>time(),
"MsgType"=>"transfer_customer_service",
);
exit(json_encode($textTpl));
}elseif($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){
//进入客服动作
$fromUsername = $postArr['FromUserName']; //发送者openid
$content = '您好,有什么能帮助你?';
$data=array(
"touser"=>$fromUsername,
"msgtype"=>"text",//
"msgtype"=>"transfer_customer_service",
"text"=>array("content"=>$content)
);
/* POST发送https请求客服接口api */
$json = json_encode($data,JSON_UNESCAPED_UNICODE); //php5.4+
$access_token = $this->mini_customer_service->get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
$output = $this->mini_customer_service->curl_get($url,$json);
if($output == 0){
echo 'success';exit;
}
}else{
exit('aaa');
}
}else{
echo "";
exit;
}
}
小程序消息推送token验证PHP代码
最新推荐文章于 2023-08-10 16:50:08 发布