你如果关注天下网吧微信公众号,那么有游戏更新突发事件时你应该有收到相关的公众号推送预警信息。如下图:
那么这个功能怎么实现的呢。下面就分享下后端公众号消息推送的源码吧:
<?php /** * Description [ 微信小程序消息推送 ] */ include_once 'inc.php'; class WxMessage { public function getwxacodeunlimit($scene, $page = '', $width = 200) { $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $this->_getAccessToken(WMAPI_APPID, WMAPI_APPSECRET); $data = array( 'scene' => $scene, //接收者(用户)的 openid 'page' => $page, //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 'width' => $width, //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } ); $data = json_encode($data); //file_put_contents('2.txt',$data, FILE_APPEND); $result = $this->_requestPost($url, $data); return $result; } public function sendMessageWmapi_quote($touser, $page = '', $messagedata = array(), $state = 'formal', $lang = 'zh_CN') { $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this->_getAccessToken(WMAPI_APPID, WMAPI_APPSECRET); $data = array( 'touser' => $touser, //接收者(用户)的 openid 'template_id' => WMAPI_SUBTEMPLATE_ID_QUOTE, //所需下发的订阅模板id 'page' => $page, //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 'data' => $messagedata, //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } 'miniprogram_state' => $state, //跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版 'lang' => $lang //进入小程序查看的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN ); $data = json_encode($data); $result = $this->_requestPost($url, $data); //var_dump($result); return $result; } public function sendMessageWmapi($touser, $page = '', $messagedata = array(), $state = 'formal', $lang = 'zh_CN') { $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this->_getAccessToken(WMAPI_APPID, WMAPI_APPSECRET); $data = array( 'touser' => $touser, //接收者(用户)的 openid 'template_id' => WMAPI_SUBTEMPLATE_ID, //所需下发的订阅模板id 'page' => $page, //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 'data' => $messagedata, //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } 'miniprogram_state' => $state, //跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版 'lang' => $lang //进入小程序查看的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN ); $data = json_encode($data); $result = $this->_requestPost($url, $data); /* var_dump($result); */ return $result; } /** * [sendMessage 订阅消息推送] * @param [type] $appid [appid] * @param [type] $appsecret [appsecret] * @param [type] $touser [用户OPENID] * @param string $template_id [模板ID] * @param string $page [跳转页面] * @param array $messagedata [发送模板数据] * @param string $state [跳转小程序类型] * @param string $lang [语言] */ public function sendMessage($appid, $appsecret, $touser, $template_id = '', $page = '', $messagedata = array(), $state = 'formal', $lang = 'zh_CN') { $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this->_getAccessToken($appid, $appsecret); $data = array( 'touser' => $touser, //接收者(用户)的 openid 'template_id' => $template_id, //所需下发的订阅模板id 'page' => $page, //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 'data' => $messagedata, //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } 'miniprogram_state' => $state, //跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版 'lang' => $lang //进入小程序查看的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN ); $data = json_encode($data); //file_put_contents('2.txt',$data, FILE_APPEND); $result = $this->_requestPost($url, $data); return $result; } /** * 获取 access_tonken * @param string $token_file 用来存储token的临时文件 */ private function _getAccessToken($appid, $appsecret) { global $_G; $cacheKey = 'access_token_appid_' . $appid; loadcache($cacheKey); if ($_G['cache'][$cacheKey]) { if ($_G['cache'][$cacheKey]['expires_in'] > time()) { return $_G['cache'][$cacheKey]['value']; } } // 目标URL: $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret; //向该URL,发送GET请求 $result = $this->_requestGet($url); if (!$result) { return false; } // 存在返回响应结果 $result_obj = json_decode($result, true); $cacheArr = array( 'value' => $result_obj['access_token'], 'expires_in' => time() + $result_obj['expires_in'] ); // 写入 savecache($cacheKey, $cacheArr); return $result_obj['access_token']; } /** * 发送GET请求的方法 * @param string $url URL * @param bool $ssl 是否为https协议 * @return string 响应主体Content */ protected function _requestGet($url, $ssl = true) { // curl完成 $curl = curl_init(); //设置curl选项 curl_setopt($curl, CURLOPT_URL, $url); //URL $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4'; curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); //user_agent,请求代理信息 curl_setopt($curl, CURLOPT_AUTOREFERER, true); //referer头,请求来源 curl_setopt($curl, CURLOPT_TIMEOUT, 30); //设置超时时间 //SSL相关 if ($ssl) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //禁用后cURL将终止从服务端进行验证 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //检查服务器SSL证书中是否存在一个公用名(common name)。 } curl_setopt($curl, CURLOPT_HEADER, false); //是否处理响应头 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //curl_exec()是否返回响应结果 // 发出请求 $response = curl_exec($curl); if (false === $response) { echo '<br>', curl_error($curl), '<br>'; return false; } curl_close($curl); return $response; } /** * 发送GET请求的方法 * @param string $url URL * @param bool $ssl 是否为https协议 * @return string 响应主体Content */ protected function _requestPost($url, $data, $ssl = true) { //curl完成 $curl = curl_init(); //设置curl选项 curl_setopt($curl, CURLOPT_URL, $url); //URL $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4'; curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); //user_agent,请求代理信息 curl_setopt($curl, CURLOPT_AUTOREFERER, true); //referer头,请求来源 curl_setopt($curl, CURLOPT_TIMEOUT, 30); //设置超时时间 //SSL相关 if ($ssl) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //禁用后cURL将终止从服务端进行验证 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //检查服务器SSL证书中是否存在一个公用名(common name)。 } // 处理post相关选项 curl_setopt($curl, CURLOPT_POST, true); // 是否为POST请求 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // 处理请求数据 // 处理响应结果 curl_setopt($curl, CURLOPT_HEADER, false); //是否处理响应头 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //curl_exec()是否返回响应结果 // 发出请求 $response = curl_exec($curl); if (false === $response) { echo '<br>', curl_error($curl), '<br>'; return false; } curl_close($curl); return $response; } public function getSignPackage($url = "") { $jsapiTicket = $this->getJsApiTicket(); $url = $url ? $url : "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "appId" => WMAPI_APPID_GZH, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } private function getJsApiTicket() { global $_G; $accessToken = $this->_getAccessToken(WMAPI_APPID_GZH, WMAPI_APPSECRET_GZH); $cacheKey = 'js_ticket_appid_' . WMAPI_APPID_GZH; loadcache($cacheKey); if ($_G['cache'][$cacheKey]) { if ($_G['cache'][$cacheKey]['expires_in'] > time()) { return $_G['cache'][$cacheKey]['value']; } } $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=1&access_token=$accessToken"; $r = $this->_requestGet($url); $res = json_decode($r); $data = array(); $ticket = $res->ticket; if ($ticket) { $data['expires_in'] = time() + 7000; $data['value'] = $ticket; savecache($cacheKey, $data); } return $ticket; } }
上面源码保存为WxMessage.php
另外还有一个WeChat.php,核心发送消息代码为:
/** * 发送模板消息 * @param array $data 消息结构 * @return boolean|array获取 */ public function sendTemplateMessage($data) { if (!$this->access_token && !$this->checkAuth()) return false; $result = $this->http_post(self::API_URL_PREFIX . self::TEMPLATE_SEND_URL . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; if ($json['errcode'] == 40001) { if ($this->checkAuth('', '', '', true)) { $this->sendTemplateMessage($data); } } return false; } else { } return $json; } return false; }
然后调用的方法为:
$dataMessage = array( "touser" => $openId, "template_id" => WMAPI_SUBTEMPLATE_ID_GM_GZH, "url" => "", "miniprogram" => array( "appid" => WMAPI_APPID, "pagepath" => 'pages/detail/detail?tid=' . $tid ), "topcolor" => "#FF0000", "data" => array( "first" => array( "value" => "{$gmTitle}:告警啦", "color" => "#FF0000" //参数颜色 ), "keyword1" => array( "value" => $time ? $time : (date("Y-m-d H:i:s", time())), "color" => "#FF0000" ), "keyword2" => array( "value" => $title, "color" => "#FF0000" ), "remark" => array( 'value' => "点击查看详细信息->", "color" => "#FF0000" ) ) ); $txt = date('Y-m-d H:i:s') . "^_^{$total}^_^\r\n"; $c = new Wechat($data); $r = $c->sendTemplateMessage($dataMessage);