📖 File Reader
<?php
namespace app\api\controller;
use app\BaseController;
use app\common\Common_wechat;
use think\facade\Db;
class Wechat extends BaseController
{
/**
* 公众号服务器配置访问地址(验证通过之后注释掉)
* 我的放到了:http://域名/api/Wechat/index
*/
// public function index()
// {
// //校验token,请改为你自己的
// $str_token = 'weixin';
// //AES 密钥,请改为你自己的
// $str_aes_key = base64_decode('st1DJiNSL2lLs4Bc9dCp7Uid1DwF1t5BK73bFFr7grg');
// //校验请求
// $str_nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
// $str_timestamp = isset($_GET['timestamp']) ? $_GET['timestamp'] : '';
// $str_signature = isset($_GET['signature']) ? $_GET['signature'] : '';
// $str_sha1 = $this->_gen_sha1($str_token, $str_timestamp, $str_nonce);
// if ($str_sha1 != $str_signature) {
// //api_log('签名校验失败:'.$str_sign, WEB_ELVL_ERR, 6016);
// exit;
// }
//
// //接口验证:显示的指定的字符串
// $str_echostr = isset($_GET['echostr']) ? $_GET['echostr'] : '';
// if ($str_echostr != '') {
// die($str_echostr);
// } else {
// $str_content_type = isset($_SERVER['HTTP_CONTENT_TYPE']) ? $_SERVER['HTTP_CONTENT_TYPE'] : '';
// if (strpos($str_content_type, 'text/xml') !== false) {
// $str_xml = file_get_contents('php://input');
// $str_encrypt_type = isset($_GET['encrypt_type']) ? trim($_GET['encrypt_type']) : '';
// //如果是加密数据,先解密
// if ($str_encrypt_type == 'aes') {
// $str_msg_signature = isset($_GET['msg_signature']) ? trim($_GET['msg_signature']) : '';
//
// //解释密文XML
// $arr_data = $this->_parse_xml($str_xml);
// $str_encrypt = $arr_data['Encrypt'];
// $str_tousername = $arr_data['ToUserName'];
//
// $str_sha1 = $this->_gen_sha1($str_token, $str_timestamp, $str_nonce, $str_encrypt);
// if ($str_sha1 != $str_msg_signature) {
// //api_log('消息内容签名校验失败:'.$str_sign, WEB_ELVL_ERR, 6016);
// exit;
// }
//
// //解密密文
// $str_iv = substr($str_aes_key, 0, 16);
// $str_plain_text = openssl_decrypt($str_encrypt, 'AES-256-CBC', $str_aes_key, OPENSSL_ZERO_PADDING, $str_iv);
// if (strlen($str_plain_text) > 16) {
// //去除16字节的随机字符串
// $str_plain_text = substr($str_plain_text, 16);
// $arr_len = unpack('N', substr($str_plain_text, 0, 4));
// $int_xml_len = $arr_len[1];
// $str_xml = substr($str_plain_text, 4, $int_xml_len);
// $str_appid = substr($str_plain_text, 4 + $int_xml_len);
// } else {
// //api_log('解密数据失败。', WEB_ELVL_ERR, 0);
// exit;
// }
// }
//
// //解释XML
// if ($str_xml != '') {
// $arr_data = $this->_parse_xml($str_xml);
// //TODO: 进行相应事件的处理
// print_r($arr_data);
// }
//
// } else {
// //api_log('无效的内容类型: '.$str_content_type, WEB_ELVL_ERR, 5015);
// exit;
// }
// }
// }
/*公众号接收到的消息或事件并解析*/
public function index()
{
$postStr = file_get_contents("php://input");//返回回复数据
if (!empty($postStr)) {
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = trim($postObj->FromUserName);//获取用户OpenID
$toUsername = trim($postObj->ToUserName); //获取公众号原始ID
$keyword = trim($postObj->Content); //用户发送的消息
$MsgType = trim($postObj->MsgType);//消息类型
//参数二维码接参处理
$qrscene = trim($postObj->EventKey);
if (!empty($qrscene)){
$qrscene = str_replace("qrscene_","",$qrscene);
}
$time = time(); //获取当前时间戳
$info = [
'fromUsername'=>$fromUsername,
'ToUserName'=>$toUsername,
'keyword'=>$keyword,
'msg_type'=>$MsgType,
'value'=>json_encode($postObj),
'qrscene'=>$qrscene,
'time_add'=>$time,
];
db::name("wechat_push_log")->insertGetId($info);
if ($MsgType == 'event') {
$MsgEvent = $postObj->Event;//获取事件类型
if ($MsgEvent == 'subscribe') { //订阅事件
$msgType = 'text'; //回复消息类型为文本
$content = '【993同城快车】
***'. date("Y-m-d H:i",$time).'***
尊敬的用户,您当前联系手机号为:未设置。如需叫车服务点击下方”一键叫车“按钮,如需更换手机号请点击下方”绑定手机“按钮。';//回复消息内容
$template = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
$info = sprintf($template, $fromUsername, $toUsername, $time, $msgType, $content); //构造回复消息XML
echo $info; //返回回复消息给微信服务器
} else if ($MsgEvent == 'unsubscribe') { //取消订阅
}
}else if($MsgType == 'location'){ //发送导航事件
}else if($MsgType == 'text'){ //发送文本事件
}
}else{
echo '没有任何消息传递';
}
}
/*公众号消息发送*/
public function message_push(Common_wechat $common_wechat)
{
/*群发,当前发送的是文本形式其它格式看文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html*/
$data = [
'filter' => [
'is_to_all' => true,
],
'text' => [
'content' => 'Hello, World!',
],
'msgtype' => 'text'
];
$data = json_encode($data);
$message_push_all = $common_wechat->message_push_all($data);
/*指定人发送,当前发送的是文本形式其它格式看文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html*/
$content = "搜索连接:<a href='https://www.baidu.com'>百度一下</a>";
$open_id = 'oGGRX6mOQefGpjVNmviWXLGMJNcI';
$data = '{
"touser":"'.$open_id.'",
"msgtype":"text",
"text":{
"content":"' . $content . '"
}
}';
$message_push = $common_wechat->message_push($data);
}
/*公众号模板消息*/
public function message_template(Common_wechat $common_wechat)
{
$openid = 'oGGRX6mOQefGpjVNmviWXLGMJNcI';
$template_id = 'rWN0cdsVnFG0G_lmbmwnkTyUYZQWExvVoW4aHA3HNt4';
$data = [
'character_string9'=>[
'value'=>'1000103101001010101310000',
],
'thing2'=>[
'value'=>'小超',
],
'time4'=>[
'value'=>date("Y-m-d H:i:s",time()),
],
];
$res = $common_wechat->message_template($openid,$template_id,$data);
}
/*设置公众号自定义菜单栏*/
public function menu_bar(Common_wechat $common_wechat)
{
//菜单栏格式
$jsonmenu = '{
"button":[
{
"name": "发送位置",
"type": "location_select",
"key": "rselfmenu_2_0"
},
{
"name": "发图",
"sub_button": [
{
"type": "pic_sysphoto",
"name": "系统拍照发图",
"key": "rselfmenu_1_0",
"sub_button": []
},
{
"type": "pic_photo_or_album",
"name": "拍照或者相册发图",
"key": "rselfmenu_1_1",
"sub_button": []
},
{
"type": "pic_weixin",
"name": "微信相册发图",
"key": "rselfmenu_1_2",
"sub_button": []
}
]
},
{
"name": "扫码",
"sub_button": [
{
"type": "scancode_waitmsg",
"name": "扫码带提示",
"key": "rselfmenu_0_0",
"sub_button": []
},
{
"type": "scancode_push",
"name": "扫码推事件",
"key": "rselfmenu_0_1",
"sub_button": []
},
{
"name": "跳页",
"type": "view",
"url": "https://www.php.cn/"
}
]
}
]
}';
$menu_bar = $common_wechat->menu_bar($jsonmenu);
header("Content-Type:text/html; charset=utf-8");
echo "<pre>";
print_r($menu_bar);
echo "</pre>";
exit();
}
//计算sha1校验码
function _gen_sha1($str_token, $str_timestamp, $str_nonce, $str_encrypt = '')
{
$arr_src = array($str_encrypt, $str_token, $str_timestamp, $str_nonce);
sort($arr_src, SORT_STRING);
return sha1(implode($arr_src));
}
//解释XML
function _parse_xml($str_xml)
{
$arr_data = array();
$obj_xml = new DOMDocument();
$obj_xml->loadXML($str_xml);
$obj_node = $obj_xml->childNodes->item(0);
for ($i = 0; $i < $obj_node->childNodes->length; $i++) {
$obj_sub = $obj_node->childNodes->item($i);
if ($obj_sub->nodeType == XML_ELEMENT_NODE) {
$arr_data[$obj_sub->tagName] = $obj_sub->nodeValue;
}
}
return $arr_data;
}
}