php微信高级接口群发 多客服
程序员文章站
2024-02-22 11:08:34
本文实例为大家分享了php微信高级接口群发、多客服源码,供大家参考,具体内容如下
/**
* 微信接口调用
* 依赖
* 全局变量
* globa...
本文实例为大家分享了php微信高级接口群发、多客服源码,供大家参考,具体内容如下
/** * 微信接口调用 * 依赖 * 全局变量 * global $uid 公众号用户id, $wid 公众号id, $wechatid 粉丝唯一id; * 参数 * $poststr = $globals["http_raw_post_data"]; * $postobj = simplexml_load_string($poststr, 'simplexmlelement', libxml_nocdata); * 缓存类 自定义 * cache:set * cache:get * 具体业务修改 * 1.上传图文信息至微信素材库 * function uploadarticlestoweixinserver() * 2.关键字匹配图文回复 * function getarticledata() * * usage: * $options = array( * 'token'=>'tokenaccesskey', //填写你设定的key * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥 * ); */ class weixintool { private $appid; private $appsecret; private $access_token; private $mediatype = array('image' => array("jpg"), 'voice' => array('amr', 'mp3'), 'video' => array('mp4'), 'thumb' => array("jpg")); private $mediamaxsize = array('image' => 131072, 'voice' => 262144, 'video' => 1048576, 'thumb' => 65536); private $tem_file_path = ""; // 授权地址 const auth_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'; // 素材上传 const upload_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s"; const get_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s"; const upload_news_url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=%s"; public function __construct($options) { $this->appid = isset($options['appid']) ? $options['appid'] : ''; $this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : ''; //需修改 //上传图片临时文件目录自定义 $this->tem_file_path = yyuc_frame_path . yyuc_pub . '/' . session::get('upath'); } /** * 需修改 * 具体业务需求,图文信息上传至素材库 * 微站文章上传至微信素材 * @param type $wid * @param type $aid * @return int */ public function uploadarticlestoweixinserver($wid, $aid) { //具体图文组装过程,需修改 $m = new model('website_article'); $m_pubs = new model('pubs'); $m_pubs->find(array("id" => $wid)); $m->find(array("wid" => $wid, 'id' => $aid)); $res = array(); if ($m->has_id() && $m_pubs->has_id()) { $res[] = $m->get_model_array(); // var_dump($res); $m->votetouser = json_decode($m->votetouser, true); $articles = $m->votetouser[0]; $m_article = new model('website_article'); $ress = $m_article->where(array('wid' => $wid, 'id' => $articles))->list_all_array(); $res = array_merge($res, $ress); } else { $errarr = array(); $errarr['errcode'] = 44003; $errarr['errmsg'] = self::$errorno[$errarr['errcode']]; return $errarr; } $items = array(); foreach ($res as $k => $v) { $mediaid = $this->uploadmedia($v['picurl']); if ($mediaid['media_id']) { $thumb_media_id = $mediaid['media_id']; } else { return $mediaid; } $item = array( "thumb_media_id" => $thumb_media_id, "author" => $m_pubs->pubun, "title" => $v['title'], "content_source_url" => weixintool::complateurl(weisite::parsearticlelinkdata($v)), "content" => $v['reply_content'], //内容 富文本 "digest" => $v['description']//描述 ); $items[] = $item; } //以上具体图文组装过程,需修改 $postdata['articles'] = $items; $error = $this->uploadnews($postdata); return $error; } /** * 需修改 * 微站文章关键字匹配数据解析 */ public static function getarticledata($keyword) { global $wid; $m = new model('website_article'); $m->find(array('wid' => $wid, 'keyword@~' => " " . $keyword . " ")); $res = array(); if ($m->has_id()) { $res[] = array("tit" => $m->title, "pic" => $m->picurl, "dec" => $m->description, "url" => weisite::parsearticlelinkdata($m->get_model_array())); $m->votetouser = json_decode($m->votetouser, true); $articles = $m->votetouser[0]; if (!empty($articles)) { foreach ($articles as $v) { $m_article = new model('website_article'); $m_article->find(array('wid' => $wid, 'id' => $v)); $res[] = array("tit" => $m_article->title, "pic" => $m_article->picurl, "dec" => $m_article->description, "url" => weisite::parsearticlelinkdata($m_article->get_model_array())); } } return $res; } } /** * 获取accesstoken * @param type $flag 强制刷新accesstoken 开关 * @return type */ public function getaccesstoken($flag = false) { $url = sprintf(self::auth_url, $this->appid, $this->appsecret); $result = cache::get(md5($url)); if ($flag || empty($result)) { $result = $this->http_get($url); $result = json_decode($result, true); if ($result['errcode']) { return $result['errcode']; } cache::set(md5($url), $result, 1); } $this->access_token = $result['access_token']; return true; } /** * 上传媒体 * @param type $file 媒体文件 $url或者物理路径地址 * @param type $type 类型 * @return int * return array (size=3) 'type' => string 'image' (length=5) 'media_id' => string '-0lr3rx9mdybb7i5bdydvwfhhm3zw2uxt0oodfbpmgrfyiwckialqhh_dlp9jcm_' (length=64) 'created_at' => int 1400477181 */ public function uploadmedia($file, $type = "image") { $file = self::complateurl($file); $urlarr = parse_url($file); $filetype = explode(".", $urlarr['path']); $filetype = strtolower($filetype[count($filetype) - 1]); $resizesize = 100; //图片处理后另存质量 if (!key_exists($type, $this->mediatype) || !in_array($filetype, $this->mediatype[$type])) { // return 40005; //格式错误 $errarr = array(); $errarr['errcode'] = 40005; $errarr['errmsg'] = self::$errorno[$errarr['errcode']]; return $errarr; } $temp_file = $this->tem_file_path . 'uploadmedia.' . $filetype; $temp_file_resize = $this->tem_file_path . 'uploadmediaresize.' . $filetype; file_put_contents($temp_file, self::http_get($file)); $handle = fopen($temp_file, "r"); $fstat = fstat($handle); if ($fstat['size'] > $this->mediamaxsize[$type]) { $resizesize = intval($this->mediamaxsize[$type] / $fstat['size'] * 100); imagetool::resizeimage($temp_file_resize, $temp_file, 400, 400, $resizesize); //图片太大再处理压缩 $temp_file = $temp_file_resize; // return 40006; //大小错误 } $filepath = realpath($temp_file); $uploadurl = sprintf(self::upload_media_url, $this->access_token, $type); $postdata = array("r" => time(), 'media' => "@{$filepath}"); $result = self::http_post($uploadurl, $postdata); $result = json_decode($result, true); return $result; } /** * 群发图文信息 * @param type $touser 粉丝数组/粉丝组id * @param type $media_id * @return type */ public function sendarticles($touser, $media_id) { $errarr = array(); $postdata = array(); $postdata['mpnews'] = array("media_id" => $media_id); $postdata['msgtype'] = "mpnews"; if (is_array($touser)) { //用户列表群发 $postdata['touser'] = $touser; $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=%s'; } else { $group = intval($touser); $groups = $this->getgroups(true); if (key_exists($group, $groups['list'])) { $postdata['filter'] = array("group_id" => $group); } else { $errarr['errcode'] = 40050; //无效分组id $errarr['errmsg'] = self::$errorno[$errarr['errcode']]; return $errarr; } $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=%s'; } $url = sprintf($url, $this->access_token); $result = self::http_post($url, self::json_encode($postdata)); $result = json_decode($result, true); return $result; } /** * 删除群发信息 * @param type $msgid * @return type */ public function delsend($msgid) { $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=%s'; $url = sprintf($url, $this->access_token); $postdata = array('msgid' => $msgid, 'r' => time()); $result = self::http_post($url, self::json_encode($postdata)); $result = json_decode($result, true); return $result; } /** * 群发图文素材上传 $postdata = array('articles' => array($item, $item,...)); $item = array( "thumb_media_id" => "wmqubqcecmqwajqh8ci500lfhyog0vmttlkkjm5op-of0ulml1_2s26j8xeiordl", "author" => "xxx", "title" => "happy day", "content_source_url" => "www.qq.com", "content" => "content", "digest" => "digest" ); * return array (size=3) 'type' => string 'news' (length=4) 'media_id' => string 'ouxqv2dgzzxamk4z-tvstgr6ing18oillwkd6tj1qjzvrg-2f64fdu2d3j7dpths' (length=64) 'created_at' => int 1400477183 */ public function uploadnews($postdata) { $uploadurl = sprintf(self::upload_news_url, $this->access_token); $result = self::http_post($uploadurl, self::json_encode($postdata)); $result = json_decode($result, true); return $result; } /** * 获取粉丝列表 * @param type $nextopenid * @return type */ public function getallconnects($nextopenid = "") { $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s'; $url = sprintf($url, $this->access_token, $nextopenid); $result = self::http_get($url); $result = json_decode($result, true); $count = count($result['data']['openid']); $list = $result['data']['openid']; if ($result['data']['openid'][$count - 1] == $result['next_openid']) { return $result['data']['openid']; } else { $templist = $this->getallconnects($result['next_openid']); $list = array_merge($list, $templist); return $list; } } /** * 根据粉丝唯一id获取微信信息 * @param type $openid * @return type */ public function getfansinfo($openid) { $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_cn'; $url = sprintf($url, $this->access_token, $openid); $result = self::http_get($url); $result = json_decode($result, true); return $result; } /** * 更新粉丝组信息 * @param type $openid * @param type $groupid * @return type */ public function updatefansgroups($openid, $groupid) { $url = 'https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=%s'; $url = sprintf($url, $this->access_token); $postdata = array("to_groupid" => $groupid, 'openid' => $openid); $result = self::http_post($url, self::json_encode($postdata)); $result = json_decode($result, true); $this->getgroups(true); return $result; } /** * 获取粉丝组信息 * @param type $openid * @return type */ public function getfansgroupinfo($openid) { $url = 'https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=%s'; $url = sprintf($url, $this->access_token); $postdata = array("r" => time(), 'openid' => $openid); $result = self::http_post($url, self::json_encode($postdata)); $result = json_decode($result, true); return $result['groupid']; } /** * 获取唯一key * @param type $key * @return type */ public function getkey($key) { return md5($this->appid . $this->appsecret . $key); } /** * 获取媒体图片到本地 * @param type $mediaid * @return string */ public function getmedia($mediaid) { $url = sprintf(self::get_media_url, $this->access_token, $mediaid); $result = self::http_get($url); $temp_file = $this->tem_file_path . 'getmedia.jpg'; file_put_contents($temp_file, $result); return $temp_file; } /** * 用户组 * @param type $flag 强制刷新用户组 * @return type */ public function getgroups($flag = false) { $key = $this->appid . 'gasdfev' . $this->appsecret; $result = cache::get($key); if (empty($result) || $flag) { $url = 'https://api.weixin.qq.com/cgi-bin/groups/get?access_token=%s'; $url = sprintf($url, $this->access_token); $result = self::http_get($url); $result = json_decode($result, true); $temg = array(); $temlist = array(); foreach ($result['groups'] as $k => $v) { $temg[$v['id']] = $v; $temlist[$v['id']] = $v['name']; } $result['map'] = $temg; $result['list'] = $temlist; cache::set($key, $result); } return $result; } /** * 新增用户组 * @param type $name * @return type */ public function creategroup($name) { $url = 'https://api.weixin.qq.com/cgi-bin/groups/create?access_token=%s'; $url = sprintf($url, $this->access_token); $result = self::http_post($url, self::json_encode(array('group' => array('name' => $name)))); $result = json_decode($result, true); return $result; } /** * 修改用户组 * @param type $id * @param type $name * @return type */ public function modifygroup($id, $name) { $url = 'https://api.weixin.qq.com/cgi-bin/groups/update?access_token=%s'; $url = sprintf($url, $this->access_token); $result = self::http_post($url, self::json_encode(array('group' => array('id' => $id, 'name' => $name)))); $result = json_decode($result, true); return $result; } /** * 多客服接入 * @global type $wid * @param type $postobj */ public static function responseservice($postobj) { global $wid; $fromusername = $postobj->fromusername; $tousername = $postobj->tousername; $texttpl = "<xml> <tousername><![cdata[%s]]></tousername> <fromusername><![cdata[%s]]></fromusername> <createtime>%s</createtime> <msgtype><![cdata[transfer_customer_service]]></msgtype> </xml>"; $resstr = sprintf($texttpl, $fromusername, $tousername, time()); echo $resstr; } /** * 微信回复多图文 * @global type $wid * @param type $res * array(array(),array() * ); * @param type $rid * @param type $postobj */ public static function response_morearts($res, $postobj) { global $wid; $fromusername = $postobj->fromusername; $tousername = $postobj->tousername; $texttpl = "<xml> <tousername><![cdata[%s]]></tousername> <fromusername><![cdata[%s]]></fromusername> <createtime>%s</createtime> <msgtype><![cdata[%s]]></msgtype> <articlecount>%s</articlecount> <articles> item </articles> </xml>"; $resstr = sprintf($texttpl, $fromusername, $tousername, time(), "news", count($res)); $item = ''; $subitem = "<item> <title><![cdata[%s]]></title> <description><![cdata[%s]]></description> <picurl><![cdata[%s]]></picurl> <url><![cdata[%s]]></url> </item>"; foreach ($res as $r) { $r['url'] = self::parseurl($r['url']); $item .= sprintf($subitem, $r['tit'], $r['des'], self::complateurl($r['pic']), self::replacetowxurl(self::complateurl($r['url']), $postobj)); } $resstr = str_replace('item', $item, $resstr); echo $resstr; } /** * url解析 * @param type $url * @return string */ public static function complateurl($url) { if (false === stristr($url, "http://")) {//查找http:// 如果不存在 if (0 === strpos($url, '/')) {//查找首字母 如果存在 $url = substr($url, 1); //去除/ } $url = "http://" . $_server['http_host'] . '/' . $url; //拼接完整路径 } return $url; } /** * 微信url固定参数替换 * @param type $url * @param type $postobj * @return type */ public static function replacetowxurl($url, $postobj) { global $wechatid; return str_ireplace('fromusername', $wechatid, $url); } /** * 完成以下行为 * parseurlparam * seturlpublicparam * buildurlparam * @param type $url * @param type $other 附加参数 基础参数wid wxid wechatid */ public static function parseurl($url, $other = array()) { $url = self::parseurlparam($url); $url = self::seturlpublicparam($url); if (is_array($other) && !empty($other)) { $url['param'] = array_merge($url['param'], $other); } $url = self::buildurlparam($url); return $url; } /** * 分析url * @param type $url * @return type */ public static function parseurlparam($url) { $temp = explode("?", $url); $url0 = $temp[0]; $url1 = $temp[1]; $p = explode("&", $url1); $param = array(); foreach ($p as $v) { $tempp = explode("=", $v); $param[$tempp[0]] = $tempp[1]; } return array("url" => $url0, "param" => $param); } /** * 组装url * @param type $arr * @return type */ public static function buildurlparam($arr) { $url = $arr['url']; $param = $arr['param']; $param_arr = array(); foreach ($param as $k => $v) { if ($k == "") continue; $param_arr[] = $k . "=" . $v; } return $url . "?" . implode("&", $param_arr) . "#mp.weixin.qq.com"; } /** * 设置微信保留参数信息 * @global type $uid * @global type $wid * @global type $wechatid * @param type $url * @return type */ public static function seturlpublicparam($url) { global $uid, $wid, $wechatid; $url['param']['wid'] = $wid; $url['param']['wxid'] = $wechatid; $url['param']['wechatid'] = $wechatid; return $url; } public static $errorno = array( '-1' => '系统繁忙', '0' => '请求成功', '40001' => '获取access_token时appsecret错误,或者access_token无效', '40002' => '不合法的凭证类型', '40003' => '不合法的openid', '40004' => '不合法的媒体文件类型', '40005' => '不合法的文件类型', '40006' => '不合法的文件大小', '40007' => '不合法的媒体文件id', '40008' => '不合法的消息类型', '40009' => '不合法的图片文件大小', '40010' => '不合法的语音文件大小', '40011' => '不合法的视频文件大小', '40012' => '不合法的缩略图文件大小', '40013' => '不合法的appid', '40014' => '不合法的access_token', '40015' => '不合法的菜单类型', '40016' => '不合法的按钮个数', '40017' => '不合法的按钮个数', '40018' => '不合法的按钮名字长度', '40019' => '不合法的按钮key长度', '40020' => '不合法的按钮url长度', '40021' => '不合法的菜单版本号', '40022' => '不合法的子菜单级数', '40023' => '不合法的子菜单按钮个数', '40024' => '不合法的子菜单按钮类型', '40025' => '不合法的子菜单按钮名字长度', '40026' => '不合法的子菜单按钮key长度', '40027' => '不合法的子菜单按钮url长度', '40028' => '不合法的自定义菜单使用用户', '40029' => '不合法的oauth_code', '40030' => '不合法的refresh_token', '40031' => '不合法的openid列表', '40032' => '不合法的openid列表长度', '40033' => '不合法的请求字符,不能包含\uxxxx格式的字符', '40035' => '不合法的参数', '40038' => '不合法的请求格式', '40039' => '不合法的url长度', '40050' => '不合法的分组id', '40051' => '分组名字不合法', '40059' => '不合法的消息id', '41001' => '缺少access_token参数', '41002' => '缺少appid参数', '41003' => '缺少refresh_token参数', '41004' => '缺少secret参数', '41005' => '缺少多媒体文件数据', '41006' => '缺少media_id参数', '41007' => '缺少子菜单数据', '41008' => '缺少oauth code', '41009' => '缺少openid', '42001' => 'access_token超时', '42002' => 'refresh_token超时', '42003' => 'oauth_code超时', '43001' => '需要get请求', '43002' => '需要post请求', '43003' => '需要https请求', '43004' => '需要接收者关注', '43005' => '需要好友关系', '44001' => '多媒体文件为空', '44002' => 'post的数据包为空', '44003' => '图文消息内容为空', '44004' => '文本消息内容为空', '45001' => '多媒体文件大小超过限制', '45002' => '消息内容超过限制', '45003' => '标题字段超过限制', '45004' => '描述字段超过限制', '45005' => '链接字段超过限制', '45006' => '图片链接字段超过限制', '45007' => '语音播放时间超过限制', '45008' => '图文消息超过限制', '45009' => '接口调用超过限制', '45010' => '创建菜单个数超过限制', '45015' => '回复时间超过限制', '45016' => '系统分组,不允许修改', '45017' => '分组名字过长', '45018' => '分组数量超过上限', '46001' => '不存在媒体数据', '46002' => '不存在的菜单版本', '46003' => '不存在的菜单数据', '46004' => '不存在的用户', '47001' => '解析json/xml内容错误', '48001' => 'api功能未授权', '50001' => '用户未授权该api' ); /** * get 请求 * @param string $url */ public static function http_get($url) { if (!function_exists('curl_init')) { die('curl 未开启'); }; $ocurl = curl_init(); if (stripos($url, "https://") !== false) { curl_setopt($ocurl, curlopt_ssl_verifypeer, false); curl_setopt($ocurl, curlopt_ssl_verifyhost, false); } curl_setopt($ocurl, curlopt_url, $url); curl_setopt($ocurl, curlopt_returntransfer, 1); $scontent = curl_exec($ocurl); $astatus = curl_getinfo($ocurl); curl_close($ocurl); if (intval($astatus["http_code"]) == 200) { return $scontent; } else { return false; } } /** * post 请求 * @param string $url * @param array $param * @return string content */ public static function http_post($url, $param, $httpbuildquery = false) { if (!function_exists('curl_init')) { die('curl 未开启'); }; $ocurl = curl_init(); if (stripos($url, "https://") !== false) { curl_setopt($ocurl, curlopt_ssl_verifypeer, false); curl_setopt($ocurl, curlopt_ssl_verifyhost, false); } curl_setopt($ocurl, curlopt_url, $url); curl_setopt($ocurl, curlopt_returntransfer, 1); // curl_setopt($ocurl, curlopt_httpheader, $header);//设置http头 curl_setopt($ocurl, curlopt_post, 1); if ($httpbuildquery) { $param = http_build_query($param); } curl_setopt($ocurl, curlopt_postfields, $param); $scontent = curl_exec($ocurl); $astatus = curl_getinfo($ocurl); curl_close($ocurl); if (intval($astatus["http_code"]) == 200) { return $scontent; } else { return false; } } /** * 微信api不支持中文转义的json结构 * @param array $arr */ static function json_encode($arr) { $parts = array(); $is_list = false; //find out if the given array is a numerical array $keys = array_keys($arr); $max_length = count($arr) - 1; if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //see if the first key is 0 and last key is length - 1 $is_list = true; for ($i = 0; $i < count($keys); $i ++) { //see if each key correspondes to its position if ($i != $keys [$i]) { //a key fails at position check. $is_list = false; //it is an associative array. break; } } } foreach ($arr as $key => $value) { if (is_array($value)) { //custom handling for arrays if ($is_list) $parts [] = self::json_encode($value); /* :recursion: */ else $parts [] = '"' . $key . '":' . self::json_encode($value); /* :recursion: */ } else { $str = ''; if (!$is_list) $str = '"' . $key . '":'; //custom handling for multiple data types if (is_numeric($value) && $value < 2000000000) $str .= $value; //numbers elseif ($value === false) $str .= 'false'; //the booleans elseif ($value === true) $str .= 'true'; else $str .= '"' . addslashes($value) . '"'; //all other things // :todo: is there any more datatype we should be in the lookout for? (object?) $parts [] = $str; } } $json = implode(',', $parts); if ($is_list) return '[' . $json . ']'; //return numerical json return '{' . $json . '}'; //return associative json } }
以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。