/** * get token from db */ public static function getWxTokenFromDB() { // 因为在wxindex.php里面已经引用过inc.db.php,所以这里是能拿到db的 global $db; $tokenObj = $db->fetch($db->query("SELECT * FROM wx_token where id = 1")); if ($tokenObj) { // 如果不为空 $tokenFromDB = $tokenObj['token']; $updatetime = $tokenObj['updatetime']; $currenttime = DateUtil::getCurrentTime(); /*$days=floor((strtotime($currenttime)-strtotime($updatetime))/86400); $hour=floor((strtotime($currenttime)-strtotime($updatetime))%86400/3600); $minute=floor((strtotime($currenttime)-strtotime($updatetime))%86400/60); $second=floor((strtotime($currenttime)-strtotime($updatetime))%86400%60); $seconds = $days * 24 + $hour * 60 + $minute * 60 + $second;*/ $seconds = DateUtil::getTimeInterval($currenttime, $updatetime); LogUtil::logs("getWxTokenFromDB=====> " . $seconds, getLogFile("/business.log")); if ($seconds >= 6000) { // 如果当前操作时间的间隔已经大于或等于6500秒了 //LogUtil::logs("WxUtil getWxTokenFromDB :已超时,重新获取token", getLogFile('/business.log')); return self::initWxTokenToDB(); } //LogUtil::logs("WxUtil getWxTokenFromDB :未超时,使用数据库token", getLogFile('/business.log')); return $tokenFromDB; } //LogUtil::logs("WxUtil self getWxTokenFromDB :数据库不存在token,初始化token", getLogFile('/business.log')); return self::initWxTokenToDB(); }
public function deal($postData) { LogUtil::logs("TypeVoice deal=====> " . print_r($postData, true), getLogFile("/business.log")); $FromUserName = $postData["FromUserName"]; $Recognition = $postData["Recognition"]; $paramsData['Content'] = empty($Recognition) ? "没听清,请再说一次" : $Recognition; $paramsData['MsgType'] = 'text'; // 同步响应 echo parent::packageData($postData, $paramsData); }
/** * 支持https请求 */ static function httpPost($url, $data, $action) { // 模拟提交数据函数 /* $o=""; foreach ($data as $k=>$v) { $o.= "$k=".urlencode($v)."&"; } $data=substr($o,0,-1); */ $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在 curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer curl_setopt($curl, CURLOPT_POST, $action == 'post' ? true : false); // 发送一个常规的Post请求 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环 curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 $tmpInfo = curl_exec($curl); // 执行操作 LogUtil::logs(" RequestUtil.php httpPost =====> " . $tmpInfo, getLogFile('/business.log')); /* if (curl_errno($curl)) { LogUtil::logs(" RequestUtil.php httpGet =====> 最后一次错误的信息".curl_error($curl), getLogFile('/business.log')); }*/ curl_close($curl); // 关闭CURL会话 $arr = json_decode($tmpInfo, true); if (empty($arr)) { // 解决特殊字符问题 $tmpInfo = substr(str_replace('\\"', '"', json_encode($tmpInfo)), 1, -1); $arr = json_decode($tmpInfo, true); } return $arr; // 返回数据 }
/** */ public static function updateMsg($sql) { global $db; LogUtil::logs("saveMsg =======>" . $sql, getLogFile("/business.log")); $db->exec($sql); }
function checkSignature($signature, $timestamp, $nonce) { global $token; $logFile = dirname(__FILE__) . '/pay.log'; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if (strtoupper($tmpStr) == strtoupper($signature)) { LogUtil::logs(time() . " checkSignature =====> token验证成功", $logFile); return true; } else { LogUtil::logs(time() . " checkSignature =====> token验证失败", $logFile); return false; } }
$timestamp = $_GET["timestamp"]; } if (isset($_GET["nonce"])) { $nonce = $_GET["nonce"]; } LogUtil::logs(" index.php newwxindex=====> ", getLogFile('/business.log')); LogUtil::logs("数据检查" . print_r($GLOBALS["HTTP_RAW_POST_DATA"], true), getLogFile('/business2.log')); if (!empty($_GET)) { if (checkSignature($signature, $timestamp, $nonce)) { LogUtil::logs(" checkSignature =====> token验证成功", getLogFile('/business.log')); if ($echostr) { echo $echostr; exit; } } else { LogUtil::logs(" checkSignature =====> token验证失败", getLogFile('/business.log')); exit; } } dealRequest($GLOBALS["HTTP_RAW_POST_DATA"]); function dealRequest($postXml) { $postArray = xml2array($postXml); $postData = $postArray['xml']; //LogUtil::logs("dealRequest ====>".print_R($postData,true), getLogFile("/business.log")); if ($postData['MsgType'] == "event") { $te = new TypeEvent(); $te->dealByAychReturn($postData); } elseif ($postData['MsgType'] == "text") { $tt = new TypeText(); $tt->deal($postData);
function transactionSave($user_info_list) { $errorOpenids = ""; $successcount = 0; $failcount = 0; LogUtil::logs("要保存到数据库的用户信息数量====> " . count($user_info_list), getLogFile("/business.log")); //echo print_r($user_info_list); global $db; if (!empty($user_info_list)) { mysql_query('START TRANSACTION'); foreach ($user_info_list as $userinfo) { /*if(($successcount + $failcount) % 5000 == 0) { mysql_query('START TRANSACTION'); }*/ $openid = $userinfo["openid"]; if (!empty($openid)) { //echo print_r($userinfo); $nickname = base64_encode($userinfo["nickname"]); //$nickname = $userinfo["nickname"]; // 默认是/0 表示640*640的尺寸 有0、46、64、96、132 $headimgurl = $userinfo["headimgurl"]; $sex = $userinfo["sex"]; $subscribe = $userinfo["subscribe"]; $currtime = DateUtil::getCurrentTime(); $sql = "INSERT INTO `wx_user_info` (openid, nickname, sex, subscribe, subscribe_time, headimgurl) \r\n\t\t\t\t\tVALUES ('{$openid}', '{$nickname}', '{$sex}', '{$subscribe}', '{$currtime}', '{$headimgurl}')"; $execres = $db->exec($sql); if (!$execres) { $errorOpenids .= $openid . "; "; $failcount = $failcount + 1; } else { $successcount = $successcount + 1; } } /*if(($successcount + $failcount) % 5000 == 0) { mysql_query('COMMIT'); }*/ } // mysql_query('ROLLBACK '); mysql_query('COMMIT'); if (!empty($errorOpenids)) { LogUtil::logs("====>同步错误用户名单:" . $errorOpenids, getLogFile("/db.log")); } LogUtil::logs("事务提交:成功" . $successcount . "条,失败" . $failcount . "条", getLogFile("/business.log")); } }
/** * 调用客服接口接口,发送多条图文消息,服务号不限制次数,但是要限制48小时内与微信公众号有互动的用户才能收到 */ function sendmultinewmsgByService() { // 当前php文件所在目录 //define('DIR_ROOT', str_replace('\\', '/', dirname(__FILE__))); // 项目根目录 define('DIR_ROOT', $_SERVER['DOCUMENT_ROOT']); //define('DIR_ROOT', "/wwwroot/"); $courseids = $_POST["courseids"]; /*$inTemp = ""; foreach($courseids as $courseid){ $inTemp = $inTemp.$courseid.","; } $in = substr($inTemp, 0, strlen($inTemp) -1); */ // 根据courseid查询对应的课程(推送)信息 $querysql = "select * from cn_news where id in (" . $courseids . ")"; global $db; global $smarty; $res = $db->query($querysql); $rowlist = $db->fetch_all($res); // 先判断下是否存在不满足条件的数据 $errortitle = ""; foreach ($rowlist as $row) { if (empty($row["simage"])) { $errortitle .= "<font color='red'>\"" . $row["id"] . "\"</font><br />"; } } if (!empty($errortitle)) { echo "编号为:<br />" . $errortitle . "的信息不完善,请重新编辑,添加图片、缩略图信息"; return; } // TODO 先保存图片素材,得到media_id, 页面提示用户,图片素材数量上限 // 图片(image)、语音(voice)、视频(video)和缩略图(thumb) $meidaType = "image"; // // 循环所有的消息,制成成图片消息,拿到media id 数组 $articles = array(); $showcoverpic = "0"; // 是否显示封面,1为显示,0为不显示 foreach ($rowlist as $row) { //获取当前文件物理路径 $tmp_file = DIR_ROOT . "/" . $row["simage"]; //echo $tmp_file; if (file_exists($tmp_file)) { // 先循环制作所有的图片素材, 调素材管理接口上传图片,得到meidaid $response = WxUtil::uploadPicGetPicUrl($meidaType, $tmp_file); //echo print_r($response); if (!empty($response["url"])) { $picurl = $response["url"]; $title = $row["title"]; $sourceurl = "http://bangmaisiw.w107.mc-test.com/wap/Course-Details.php?id=" . $row["id"]; $content = $row["contents"]; $article = array("title" => $title, "description" => "", "url" => $sourceurl, "picurl" => $picurl); $articles[] = $article; } else { LogUtil::logs("批量创建图片素材失败:消息来源id:" . $row["id"] . ",错误信息:" . $response["errmsg"], getLogFile("/business.log")); } } else { LogUtil::logs("文件不存在:" . $row["image"], getLogFile("/business.log")); } } // 拿到mediaid, 就可以发起推送了 // 先获取openid列表 $openidsql = "select openid, nickname from wx_user_info where subscribe = '1' "; $openidres = $db->query($openidsql); // php的json格式:array(""=>"") $openidList = $db->fetch_all($openidres); // 循环下,转成无key的值数组 $openidarr = array(); $lognickname = ""; foreach ($openidList as $openid) { $lognickname .= $openid["nickname"] . ","; $openidarr[] = $openid["openid"]; } //echo print_r($openidarr); $tit = new TypeImageText(); echo $tit->sendMultiImageTextMsgToMultiUser($openidarr, $articles); echo "<br />消息发送到:" . $lognickname; }
/** * 普通消息公共调用 * MsgType : text image voice video 等 */ function autoReplay($postData) { $openid = $postData["FromUserName"]; $content = $postData["Content"]; $createtime = DateUtil::getCurrentTime(); $msgData = array(); if ($postData['MsgType'] == 'text' && !empty($content)) { // 判断是否修改信息 // $strrule = "/^更新信息+.*/"; $strrule = "/^备注#.*/"; LogUtil::logs("autoReplay content ====>" . $content, getLogFile("/business.log")); if (preg_match($strrule, $content)) { LogUtil::logs("autoReplay content ====>" . $content, getLogFile("/business.log")); //$arr = explode("+", $content); $arr = explode("#", $content); $returnmsg = ""; $backup = $arr[1]; if (!preg_match("/^.{0,30}\$/", $backup)) { $returnmsg .= " 亲备注信息不要超过30个字符哦/:,@-D"; $paramsData['Content'] = $returnmsg; $paramsData['MsgType'] = 'text'; return parent::packageData($postData, $paramsData); } /*$mobile = $arr[2]; if(!preg_match("/^1[3|4|5|7|8][0-9]\\d{8}$/", $mobile)){ $returnmsg .= " 手机号格式不正确"; }*/ if (empty($returnmsg)) { $returnmsg = "信息更新申请成功"; } global $db; //$db -> exec("update wx_user_info set localnickname='$localnickname', mobile='$mobile' where openid='$openid'"); $db->exec("update wx_user_info set backup='{$backup}', mobile='{$mobile}' where openid='{$openid}'"); // 用户申请更新信息 $paramsData['Content'] = $returnmsg; $paramsData['MsgType'] = 'text'; return parent::packageData($postData, $paramsData); } else { // 不更新信息的情况下,只要保存到后台即可 DBUtil::saveMsg($openid, $content, $createtime, "", "5", "0"); return getSuccessStr(); } // 用户发送的信息,要保存到数据库// 消息类型: 0表示用户发送 1表示管理员回复 2表示管理员群发消息 3 自动回复 4聊天室信息 5用户私聊管理员 } }
/** * 查到用户组里面的所有组员,再向其发送消息 */ function queryGroupUserAndReplyMsg($userGroupId, $postData) { global $db; // 发消息的人自己 $userSelfOpenid = $postData["FromUserName"]; $content = $postData["Content"]; $createtime = DateUtil::getCurrentTime(); $mediaid = $postData["MediaId"]; // 用户发送的信息,要保存到数据库 // 消息类型: 0表示用户发送 1表示管理员回复 2表示管理员群发消息 3 自动回复 4聊天室信息 DBUtil::saveMsg($userSelfOpenid, "图片消息", $createtime, "", "4", "0"); // 查询所有的组员 $arr = array(); // TODO 这个$res可以缓存到文件中 $res = $db->query("SELECT * FROM wx_group_user where groupid = '{$userGroupId}' and userisin = '0' "); $row = $db->fetch_all($res); foreach ($row as $val) { // 循环每个人推送一条消息 $openid = $val['openid']; // 从组中除去发信息者自己 if ($userSelfOpenid != $openid) { // 拼接 /*{ "touser":"******", "msgtype":"image", "image": { "media_id":"MEDIA_ID" } }*/ $paramContent = array("touser" => $openid, "msgtype" => "image", "image" => array("media_id" => $mediaid)); $data = JsonUtil::getJsonStrFromArray($paramContent); LogUtil::logs("queryGroupUserAndReplyMsg data ====>" . $data, getLogFile("/business.log")); parent::sendMsgByService($data); } } return getSuccessStr(); }
/** * 将用户信息同步到数据库 */ public function synchronizedUserInfo($userInfo, $Event) { global $db; $openid = $userInfo["openid"]; $subscribe = $userInfo["subscribe"]; $currtime = DateUtil::getCurrentTime(); $sql = ""; if ($Event == "subscribe") { LogUtil::logs("TypeEvent synchronizedUserInfo insert=====> ", getLogFile("/business.log")); $nickname = $userInfo["nickname"]; $nickname = base64_encode($nickname); //$nickname = str_replace("🌻", "*", $nickname); $sex = $userInfo["sex"]; $headimgurl = $userInfo["headimgurl"]; $sql = $sql . ", nickname='{$nickname}', sex='{$sex}'"; LogUtil::logs("TypeEvent.php synchronizedUserInfo :nickname ====>" . $nickname, getLogFile('/business.log')); // 关注的情况有关注和重新关注,所以使用on duplicate的方法 $sql = "INSERT INTO `wx_user_info` (openid, nickname, sex, subscribe, subscribe_time, headimgurl) \r\n\t\t\tVALUES ('{$openid}', '{$nickname}', '{$sex}', '{$subscribe}', '{$currtime}', '{$headimgurl}') \r\n\t\t\tON DUPLICATE KEY UPDATE subscribe='{$subscribe}', nickname='{$nickname}', subscribe_time='{$currtime}', headimgurl='{$headimgurl}'"; } else { // 取消关注 LogUtil::logs("TypeEvent synchronizedUserInfo update=====> ", getLogFile("/business.log")); $sql = "update `wx_user_info` set subscribe_time='{$currtime}', subscribe='{$subscribe}' where openid = '{$openid}' "; } $db->exec($sql); }