wechatext.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. <?php
  2. /**
  3. * 微信公众平台PHP-SDK
  4. * Wechatext为非官方微信发送API
  5. * 注: 用户id为通过getMsg()方法获取的FakeId值
  6. * 主要实现如下功能:
  7. * send($id,$content) 向某用户id发送微信文字信息
  8. * getUserList($page,$pagesize,$groupid) 获取用户信息
  9. * getGroupList($page,$pagesize) 获取群组信息
  10. * sendNews($id,$msgid) 发送图文消息
  11. * getNewsList($page,$pagesize) 获取图文信息列表
  12. * uploadFile($filepath,$type) 上传附件,包括图片/音频/视频
  13. * addPreview($title,$author,$summary,$content,$photoid,$srcurl='') 创建新的图文信息
  14. * getFileList($type,$page,$pagesize) 获取素材库文件列表
  15. * sendImage($id,$fid) 发送图片消息
  16. * sendAudio($id,$fid) 发送音频消息
  17. * sendVideo($id,$fid) 发送视频消息
  18. * getInfo($id) 根据id获取用户资料
  19. * getNewMsgNum($lastid) 获取从$lastid算起新消息的数目
  20. * getTopMsg() 获取最新一条消息的数据, 此方法获取的消息id可以作为检测新消息的$lastid依据
  21. * getMsg($lastid,$offset=0,$perpage=50,$day=0,$today=0,$star=0) 获取最新的消息列表, 列表将返回消息id, 用户id, 消息类型, 文字消息等参数
  22. * 消息返回结构: {"id":"消息id","type":"类型号(1为文字,2为图片,3为语音)","fileId":"0","hasReply":"0","fakeId":"用户uid","nickName":"昵称","dateTime":"时间戳","content":"文字内容"}
  23. * getMsgImage($msgid,$mode='large') 若消息type类型为2, 调用此方法获取图片数据
  24. * getMsgVoice($msgid) 若消息type类型为3, 调用此方法获取语音数据
  25. * quickSetInterface($url, $token) 快速设置接口信息
  26. * getCommonInfo($dir) 获取公众账号基本信息, 其中包含:nickname,avatar,type,qrcode,appid,appsecret
  27. * @author dodge <dodgepudding@gmail.com>
  28. * @link https://github.com/dodgepudding/wechat-php-sdk
  29. * @version 1.2
  30. *
  31. */
  32. include "snoopy.class.php";
  33. class Wechatext
  34. {
  35. private $cookie;
  36. private $_cookiename;
  37. private $_cookieexpired = 3600;
  38. private $_account;
  39. private $_password;
  40. private $_datapath = './data/cookie_';
  41. private $debug;
  42. private $_logcallback;
  43. private $_token;
  44. public function __construct($options)
  45. {
  46. $this->_account = isset($options['account'])?$options['account']:'';
  47. $this->_password = isset($options['password'])?$options['password']:'';
  48. $this->_datapath = isset($options['datapath'])?$options['datapath']:$this->_datapath;
  49. $this->debug = isset($options['debug'])?$options['debug']:false;
  50. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  51. $this->_cookiename = $this->_datapath.$this->_account;
  52. $this->cookie = $this->getCookie($this->_cookiename);
  53. }
  54. /**
  55. * 主动发消息
  56. * @param string $id 用户的uid(即FakeId)
  57. * @param string $content 发送的内容
  58. */
  59. public function send($id,$content)
  60. {
  61. $send_snoopy = new Snoopy;
  62. $post = array();
  63. $post['tofakeid'] = $id;
  64. $post['type'] = 1;
  65. $post['token'] = $this->_token;
  66. $post['content'] = $content;
  67. $post['ajax'] = 1;
  68. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&tofakeid=$id&token={$this->_token}&lang=zh_CN";
  69. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  70. $submit = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response";
  71. $send_snoopy->submit($submit,$post);
  72. $this->log($send_snoopy->results);
  73. return $send_snoopy->results;
  74. }
  75. /**
  76. * 群发功能 纯文本
  77. * @param string $content
  78. * @return string
  79. */
  80. public function mass($content) {
  81. $send_snoopy = new Snoopy;
  82. $post = array();
  83. $post['type'] = 1;
  84. $post['token'] = $this->_token;
  85. $post['content'] = $content;
  86. $post['ajax'] = 1;
  87. $post['city']='';
  88. $post['country']='';
  89. $post['f']='json';
  90. $post['groupid']='-1';
  91. $post['imgcode']='';
  92. $post['lang']='zh_CN';
  93. $post['province']='';
  94. $post['random']= rand(0, 1);
  95. $post['sex']=0;
  96. $post['synctxnews']=0;
  97. $post['synctxweibo']=0;
  98. $post['t']='ajax-response';
  99. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/masssendpage?t=mass/send&token={$this->_token}&lang=zh_CN";
  100. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  101. $submit = "https://mp.weixin.qq.com/cgi-bin/masssend";
  102. $send_snoopy->submit($submit,$post);
  103. $this->log($send_snoopy->results);
  104. return $send_snoopy->results;
  105. }
  106. /**
  107. * 群发功能 图文素材
  108. * @param int $appmsgid 图文素材ID
  109. * @return string
  110. */
  111. function massNews($appmsgid){
  112. $send_snoopy = new Snoopy;
  113. $post = array();
  114. $post['type'] = 10;
  115. $post['token'] = $this->_token;
  116. $post['appmsgid'] = $appmsgid;
  117. $post['ajax'] = 1;
  118. $post['city']='';
  119. $post['country']='';
  120. $post['f']='json';
  121. $post['groupid']='-1';
  122. $post['imgcode']='';
  123. $post['lang']='zh_CN';
  124. $post['province']='';
  125. $post['random']= rand(0, 1);
  126. $post['sex']=0;
  127. $post['synctxnews']=0;
  128. $post['synctxweibo']=0;
  129. $post['t']='ajax-response';
  130. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/masssendpage?t=mass/send&token={$this->_token}&lang=zh_CN";
  131. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  132. $submit = "https://mp.weixin.qq.com/cgi-bin/masssend";
  133. $send_snoopy->submit($submit,$post);
  134. $this->log($send_snoopy->results);
  135. return $send_snoopy->results;
  136. }
  137. /**
  138. * 获取用户列表列表
  139. * @param $page 页码(从0开始)
  140. * @param $pagesize 每页大小
  141. * @param $groupid 分组id
  142. * @return array ({contacts:[{id:12345667,nick_name:"昵称",remark_name:"备注名",group_id:0},{}....]})
  143. */
  144. function getUserList($page=0,$pagesize=10,$groupid=0){
  145. $send_snoopy = new Snoopy;
  146. $t = time().strval(mt_rand(100,999));
  147. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=".$pagesize."&pageidx=".$page."&type=0&groupid=0&lang=zh_CN&token=".$this->_token;
  148. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  149. $submit = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=".$pagesize."&pageidx=".$page."&type=0&groupid=$groupid&lang=zh_CN&f=json&token=".$this->_token;
  150. $send_snoopy->fetch($submit);
  151. $result = $send_snoopy->results;
  152. $this->log('userlist:'.$result);
  153. $json = json_decode($result,true);
  154. if (isset($json['contact_list'])) {
  155. $json = json_decode($json['contact_list'],true);
  156. if (isset($json['contacts']))
  157. return $json['contacts'];
  158. }
  159. return false;
  160. }
  161. /**
  162. * 获取分组列表
  163. *
  164. */
  165. function getGroupList(){
  166. $send_snoopy = new Snoopy;
  167. $t = time().strval(mt_rand(100,999));
  168. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&lang=zh_CN&token=".$this->_token;
  169. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  170. $submit = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&lang=zh_CN&f=json&token=".$this->_token;
  171. $send_snoopy->fetch($submit);
  172. $result = $send_snoopy->results;
  173. $this->log('userlist:'.$result);
  174. $json = json_decode($result,true);
  175. if (isset($json['group_list'])){
  176. $json = json_decode($json['group_list'],true);
  177. if (isset($json['groups']))
  178. return $json['groups'];
  179. }
  180. return false;
  181. }
  182. /**
  183. * 获取图文信息列表
  184. * @param $page 页码(从0开始)
  185. * @param $pagesize 每页大小
  186. * @return array
  187. */
  188. public function getNewsList($page,$pagesize=10) {
  189. $send_snoopy = new Snoopy;
  190. $t = time().strval(mt_rand(100,999));
  191. $type=10;
  192. $begin = $page*$pagesize;
  193. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/masssendpage?t=mass/send&token=".$this->_token."&lang=zh_CN";
  194. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  195. $submit = "https://mp.weixin.qq.com/cgi-bin/appmsg?token=".$this->_token."&lang=zh_CN&type=$type&action=list&begin=$begin&count=$pagesize&f=json&random=0.".$t;
  196. $send_snoopy->fetch($submit);
  197. $result = $send_snoopy->results;
  198. $this->log('newslist:'.$result);
  199. $json = json_decode($result,true);
  200. if (isset($json['app_msg_info'])) {
  201. return $json['app_msg_info'];
  202. }
  203. return false;
  204. }
  205. /**
  206. * 获取与指定用户的对话内容
  207. * @param $fakeid
  208. * @return array
  209. */
  210. public function getDialogMsg($fakeid) {
  211. $send_snoopy = new Snoopy;
  212. $t = time().strval(mt_rand(100,999));
  213. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/masssendpage?t=mass/send&token=".$this->_token."&lang=zh_CN";
  214. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  215. $submit = "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&tofakeid=".$fakeid."&token=".$this->_token."&lang=zh_CN&f=json&random=".$t;
  216. $send_snoopy->fetch($submit);
  217. $result = $send_snoopy->results;
  218. $this->log('DialogMsg:'.$result);
  219. $json = json_decode($result,true);
  220. if (isset($json['page_info'])) {
  221. return $json['page_info'];
  222. }
  223. return false;
  224. }
  225. /**
  226. * 发送图文信息,必须从图文库里选取消息ID发送
  227. * @param string $id 用户的uid(即FakeId)
  228. * @param string $msgid 图文消息id
  229. */
  230. public function sendNews($id,$msgid)
  231. {
  232. $send_snoopy = new Snoopy;
  233. $post = array();
  234. $post['tofakeid'] = $id;
  235. $post['type'] = 10;
  236. $post['token'] = $this->_token;
  237. $post['fid'] = $msgid;
  238. $post['appmsgid'] = $msgid;
  239. $post['error'] = 'false';
  240. $post['ajax'] = 1;
  241. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/singlemsgpage?fromfakeid={$id}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN";
  242. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  243. $submit = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response";
  244. $send_snoopy->submit($submit,$post);
  245. $this->log($send_snoopy->results);
  246. return $send_snoopy->results;
  247. }
  248. /**
  249. * 上传附件(图片/音频/视频)
  250. * @param string $filepath 本地文件地址
  251. * @param int $type 文件类型: 2:图片 3:音频 4:视频
  252. */
  253. public function uploadFile($filepath,$type=2) {
  254. $send_snoopy = new Snoopy;
  255. $send_snoopy->referer = "http://mp.weixin.qq.com/cgi-bin/indexpage?t=wxm-upload&lang=zh_CN&type=2&formId=1";
  256. $t = time().strval(mt_rand(100,999));
  257. $post = array('formId'=>'');
  258. $postfile = array('uploadfile'=>$filepath);
  259. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  260. $send_snoopy->set_submit_multipart();
  261. $submit = "http://mp.weixin.qq.com/cgi-bin/uploadmaterial?cgi=uploadmaterial&type=$type&token=".$this->_token."&t=iframe-uploadfile&lang=zh_CN&formId= file_from_".$t;
  262. $send_snoopy->submit($submit,$post,$postfile);
  263. $tmp = $send_snoopy->results;
  264. $this->log('upload:'.$tmp);
  265. preg_match("/formId,.*?\'(\d+)\'/",$tmp,$matches);
  266. if (isset($matches[1])) {
  267. return $matches[1];
  268. }
  269. return false;
  270. }
  271. /**
  272. * 创建图文消息
  273. * @param array $title 标题
  274. * @param array $summary 摘要
  275. * @param array $content 内容
  276. * @param array $photoid 素材库里的图片id(可通过uploadFile上传后获取)
  277. * @param array $srcurl 原文链接
  278. * @return json
  279. */
  280. public function addPreview($title,$author,$summary,$content,$photoid,$srcurl='') {
  281. $send_snoopy = new Snoopy;
  282. $send_snoopy->referer = 'https://mp.weixin.qq.com/cgi-bin/operate_appmsg?lang=zh_CN&sub=edit&t=wxm-appmsgs-edit-new&type=10&subtype=3&token='.$this->_token;
  283. $submit = "https://mp.weixin.qq.com/cgi-bin/operate_appmsg?lang=zh_CN&t=ajax-response&sub=create&token=".$this->_token;
  284. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  285. $send_snoopy->set_submit_normal();
  286. $post = array(
  287. 'token'=>$this->_token,
  288. 'type'=>10,
  289. 'lang'=>'zh_CN',
  290. 'sub'=>'create',
  291. 'ajax'=>1,
  292. 'AppMsgId'=>'',
  293. 'error'=>'false',
  294. );
  295. if (count($title)==count($author)&&count($title)==count($summary)&&count($title)==count($content)&&count($title)==count($photoid))
  296. {
  297. $i = 0;
  298. foreach($title as $v) {
  299. $post['title'.$i] = $title[$i];
  300. $post['author'.$i] = $author[$i];
  301. $post['digest'.$i] = $summary[$i];
  302. $post['content'.$i] = $content[$i];
  303. $post['fileid'.$i] = $photoid[$i];
  304. if ($srcurl[$i]) $post['sourceurl'.$i] = $srcurl[$i];
  305. $i++;
  306. }
  307. }
  308. $post['count'] = $i;
  309. $post['token'] = $this->_token;
  310. $send_snoopy->submit($submit,$post);
  311. $tmp = $send_snoopy->results;
  312. $this->log('step2:'.$tmp);
  313. $json = json_decode($tmp,true);
  314. return $json;
  315. }
  316. /**
  317. * 发送媒体文件
  318. * @param $id 用户的uid(即FakeId)
  319. * @param $fid 文件id
  320. * @param $type 文件类型
  321. */
  322. public function sendFile($id,$fid,$type) {
  323. $send_snoopy = new Snoopy;
  324. $post = array();
  325. $post['tofakeid'] = $id;
  326. $post['type'] = $type;
  327. $post['token'] = $this->_token;
  328. $post['fid'] = $fid;
  329. $post['fileid'] = $fid;
  330. $post['error'] = 'false';
  331. $post['ajax'] = 1;
  332. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/singlemsgpage?fromfakeid={$id}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN";
  333. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  334. $submit = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response";
  335. $send_snoopy->submit($submit,$post);
  336. $result = $send_snoopy->results;
  337. $this->log('sendfile:'.$result);
  338. $json = json_decode($result,true);
  339. if ($json && $json['ret']==0)
  340. return true;
  341. else
  342. return false;
  343. }
  344. /**
  345. * 获取素材库文件列表
  346. * @param $type 文件类型: 2:图片 3:音频 4:视频
  347. * @param $page 页码(从0开始)
  348. * @param $pagesize 每页大小
  349. * @return array
  350. */
  351. public function getFileList($type,$page,$pagesize=10) {
  352. $send_snoopy = new Snoopy;
  353. $t = time().strval(mt_rand(100,999));
  354. $begin = $page*$pagesize;
  355. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/masssendpage?t=mass/send&token=".$this->_token."&lang=zh_CN";
  356. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  357. $submit = "https://mp.weixin.qq.com/cgi-bin/filepage?token=".$this->_token."&lang=zh_CN&type=$type&random=0.".$t."&begin=$begin&count=$pagesize&f=json";
  358. $send_snoopy->fetch($submit);
  359. $result = $send_snoopy->results;
  360. $this->log('filelist:'.$result);
  361. $json = json_decode($result,true);
  362. if (isset($json['page_info']))
  363. return $json['page_info'];
  364. else
  365. return false;
  366. }
  367. /**
  368. * 发送图文信息,必须从库里选取文件ID发送
  369. * @param string $id 用户的uid(即FakeId)
  370. * @param string $fid 文件id
  371. */
  372. public function sendImage($id,$fid)
  373. {
  374. return $this->sendFile($id,$fid,2);
  375. }
  376. /**
  377. * 发送语音信息,必须从库里选取文件ID发送
  378. * @param string $id 用户的uid(即FakeId)
  379. * @param string $fid 语音文件id
  380. */
  381. public function sendAudio($id,$fid)
  382. {
  383. return $this->sendFile($id,$fid,3);
  384. }
  385. /**
  386. * 发送视频信息,必须从库里选取文件ID发送
  387. * @param string $id 用户的uid(即FakeId)
  388. * @param string $fid 视频文件id
  389. */
  390. public function sendVideo($id,$fid)
  391. {
  392. return $this->sendFile($id,$fid,4);
  393. }
  394. /**
  395. * 发送预览图文消息
  396. * @param string $account 账户名称(user_name)
  397. * @param string $title 标题
  398. * @param string $summary 摘要
  399. * @param string $content 内容
  400. * @param string $photoid 素材库里的图片id(可通过uploadFile上传后获取)
  401. * @param string $srcurl 原文链接
  402. * @return json
  403. */
  404. public function sendPreview($account,$title,$summary,$content,$photoid,$srcurl='') {
  405. $send_snoopy = new Snoopy;
  406. $submit = "https://mp.weixin.qq.com/cgi-bin/operate_appmsg?sub=preview&t=ajax-appmsg-preview";
  407. $send_snoopy->set_submit_normal();
  408. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  409. $send_snoopy->referer = 'https://mp.weixin.qq.com/cgi-bin/operate_appmsg?sub=edit&t=wxm-appmsgs-edit-new&type=10&subtype=3&lang=zh_CN';
  410. $post = array(
  411. 'AppMsgId'=>'',
  412. 'ajax'=>1,
  413. 'content0'=>$content,
  414. 'count'=>1,
  415. 'digest0'=>$summary,
  416. 'error'=>'false',
  417. 'fileid0'=>$photoid,
  418. 'preusername'=>$account,
  419. 'sourceurl0'=>$srcurl,
  420. 'title0'=>$title,
  421. );
  422. $post['token'] = $this->_token;
  423. $send_snoopy->submit($submit,$post);
  424. $tmp = $send_snoopy->results;
  425. $this->log('sendpreview:'.$tmp);
  426. $json = json_decode($tmp,true);
  427. return $json;
  428. }
  429. /**
  430. * 获取用户的信息
  431. * @param string $id 用户的uid(即FakeId)
  432. * @return array {fake_id:100001,nick_name:'昵称',user_name:'用户名',signature:'签名档',country:'中国',province:'广东',city:'广州',gender:'1',group_id:'0'},groups:{[id:0,name:'未分组',cnt:20]}
  433. */
  434. public function getInfo($id)
  435. {
  436. $send_snoopy = new Snoopy;
  437. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  438. $t = time().strval(mt_rand(100,999));
  439. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token=".$this->_token;
  440. $submit = "https://mp.weixin.qq.com/cgi-bin/getcontactinfo";
  441. $post = array('ajax'=>1,'lang'=>'zh_CN','random'=>'0.'.$t,'token'=>$this->_token,'t'=>'ajax-getcontactinfo','fakeid'=>$id);
  442. $send_snoopy->submit($submit,$post);
  443. $this->log($send_snoopy->results);
  444. $result = json_decode($send_snoopy->results,true);
  445. if(isset($result['contact_info'])){
  446. return $result['contact_info'];
  447. }
  448. return false;
  449. }
  450. /**
  451. * 获得头像数据
  452. *
  453. * @param FakeId $fakeid
  454. * @return JPG二进制数据
  455. */
  456. public function getHeadImg($fakeid){
  457. $send_snoopy = new Snoopy;
  458. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  459. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token=".$this->_token;
  460. $url = "https://mp.weixin.qq.com/misc/getheadimg?fakeid=$fakeid&token=".$this->_token."&lang=zh_CN";
  461. $send_snoopy->fetch($url);
  462. $result = $send_snoopy->results;
  463. $this->log('Head image:'.$fakeid.'; length:'.strlen($result));
  464. if(!$result){
  465. return false;
  466. }
  467. return $result;
  468. }
  469. /**
  470. * 获取消息更新数目
  471. * @param int $lastid 最近获取的消息ID,为0时获取总消息数目
  472. * @return int 数目
  473. */
  474. public function getNewMsgNum($lastid=0){
  475. $send_snoopy = new Snoopy;
  476. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  477. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token=".$this->_token;
  478. $submit = "https://mp.weixin.qq.com/cgi-bin/getnewmsgnum?t=ajax-getmsgnum&lastmsgid=".$lastid;
  479. $post = array('ajax'=>1,'token'=>$this->_token);
  480. $send_snoopy->submit($submit,$post);
  481. $this->log($send_snoopy->results);
  482. $result = json_decode($send_snoopy->results,1);
  483. if(!$result){
  484. return false;
  485. }
  486. return intval($result['newTotalMsgCount']);
  487. }
  488. /**
  489. * 获取最新一条消息
  490. * @return array {"id":"最新一条id","type":"类型号(1为文字,2为图片,3为语音)","fileId":"0","hasReply":"0","fakeId":"用户uid","nickName":"昵称","dateTime":"时间戳","content":"文字内容","playLength":"0","length":"0","source":"","starred":"0","status":"4"}
  491. */
  492. public function getTopMsg(){
  493. $send_snoopy = new Snoopy;
  494. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  495. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&lang=zh_CN&token=".$this->_token;
  496. $submit = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&f=json&count=20&day=7&lang=zh_CN&token=".$this->_token;
  497. $send_snoopy->fetch($submit);
  498. $this->log($send_snoopy->results);
  499. $result = $send_snoopy->results;
  500. $json = json_decode($result,true);
  501. if (isset($json['msg_items'])) {
  502. $json = json_decode($json['msg_items'],true);
  503. if(isset($json['msg_item']))
  504. return array_shift($json['msg_item']);
  505. }
  506. return false;
  507. }
  508. /**
  509. * 获取新消息
  510. * @param $lastid 传入最后的消息id编号,为0则从最新一条起倒序获取
  511. * @param $offset lastid起算第一条的偏移量
  512. * @param $perpage 每页获取多少条
  513. * @param $day 最近几天消息(0:今天,1:昨天,2:前天,3:更早,7:五天内)
  514. * @param $today 是否只显示今天的消息, 与$day参数不能同时大于0
  515. * @param $star 是否星标组信息
  516. * @return array[] 同getTopMsg()返回的字段结构相同
  517. */
  518. public function getMsg($lastid=0,$offset=0,$perpage=20,$day=7,$today=0,$star=0){
  519. $send_snoopy = new Snoopy;
  520. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  521. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&lang=zh_CN&count=50&token=".$this->_token;
  522. $lastid = $lastid===0 ? '':$lastid;
  523. $addstar = $star?'&action=star':'';
  524. $submit = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&f=json&lang=zh_CN{$addstar}&count=$perpage&timeline=$today&day=$day&frommsgid=$lastid&offset=$offset&token=".$this->_token;
  525. $send_snoopy->fetch($submit);
  526. $this->log($send_snoopy->results);
  527. $result = $send_snoopy->results;
  528. $json = json_decode($result,true);
  529. if (isset($json['msg_items'])) {
  530. $json = json_decode($json['msg_items'],true);
  531. if(isset($json['msg_item']))
  532. return $json['msg_item'];
  533. }
  534. return false;
  535. }
  536. /**
  537. * 获取图片消息
  538. * @param int $msgid 消息id
  539. * @param string $mode 图片尺寸(large/small)
  540. * @return jpg二进制文件
  541. */
  542. public function getMsgImage($msgid,$mode='large'){
  543. $send_snoopy = new Snoopy;
  544. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  545. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token=".$this->_token;
  546. $url = "https://mp.weixin.qq.com/cgi-bin/getimgdata?token=".$this->_token."&msgid=$msgid&mode=$mode&source=&fileId=0";
  547. $send_snoopy->fetch($url);
  548. $result = $send_snoopy->results;
  549. $this->log('msg image:'.$msgid.';length:'.strlen($result));
  550. if(!$result){
  551. return false;
  552. }
  553. return $result;
  554. }
  555. /**
  556. * 获取语音消息
  557. * @param int $msgid 消息id
  558. * @return mp3二进制文件
  559. */
  560. public function getMsgVoice($msgid){
  561. $send_snoopy = new Snoopy;
  562. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  563. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token=".$this->_token;
  564. $url = "https://mp.weixin.qq.com/cgi-bin/getvoicedata?token=".$this->_token."&msgid=$msgid&fileId=0";
  565. $send_snoopy->fetch($url);
  566. $result = $send_snoopy->results;
  567. $this->log('msg voice:'.$msgid.';length:'.strlen($result));
  568. if(!$result){
  569. return false;
  570. }
  571. return $result;
  572. }
  573. /**
  574. * 开启开发者模式
  575. */
  576. public function openDevModel()
  577. {
  578. $send_snoopy = new Snoopy;
  579. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  580. $send_snoopy->referer = "https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&lang=zh_CN&token=".$this->_token;
  581. $submit = "https://mp.weixin.qq.com/misc/skeyform?form=advancedswitchform&lang=zh_CN";
  582. $post['flag']=1;
  583. $post['type']=2;
  584. $post['token']=$this->_token;
  585. $send_snoopy->submit($submit,$post);
  586. $result = $send_snoopy->results;
  587. $this->log($send_snoopy->results);
  588. $json = json_decode($result,true);
  589. if(!$result){
  590. return false;
  591. }
  592. return true;
  593. }
  594. /**
  595. * 关闭编辑模式
  596. */
  597. public function closeEditModel()
  598. {
  599. $send_snoopy = new Snoopy;
  600. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  601. $send_snoopy->referer = "https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&lang=zh_CN&token=".$this->_token;
  602. $submit = "https://mp.weixin.qq.com/misc/skeyform?form=advancedswitchform&lang=zh_CN";
  603. $post['flag']=0;
  604. $post['type']=1;
  605. $post['token']=$this->_token;
  606. $send_snoopy->submit($submit,$post);
  607. $result = $send_snoopy->results;
  608. $this->log($send_snoopy->results);
  609. $json = json_decode($result,true);
  610. if(!$result){
  611. return false;
  612. }
  613. return true;
  614. }
  615. /**
  616. * 配置接口信息
  617. * @param string $url 接口回调URL
  618. * @param string $token 接口Token
  619. */
  620. public function setUrlToken($url, $token)
  621. {
  622. $send_snoopy = new Snoopy;
  623. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  624. $send_snoopy->referer = "https://mp.weixin.qq.com/advanced/advanced?action=interface&t=advanced/interface&lang=zh_CN&token=".$this->_token;
  625. $submit = "https://mp.weixin.qq.com/advanced/callbackprofile?t=ajax-response&lang=zh_CN&token=".$this->_token;
  626. $post['url'] = $url;
  627. $post['callback_token'] = $token;
  628. $send_snoopy->submit($submit,$post);
  629. $result = $send_snoopy->results;
  630. $this->log($send_snoopy->results);
  631. $json = json_decode($result,true);
  632. if ($json && $json['ret']==0)
  633. return true;
  634. return false;
  635. }
  636. /**
  637. * 快速设置接口
  638. * @param string $url 接口回调URL
  639. * @param string $token 接口Token
  640. */
  641. public function quickSetInterface($url, $token)
  642. {
  643. if ($this->closeEditModel() && $this->openDevModel() && $this->setUrlToken($url, $token))
  644. return true;
  645. return false;
  646. }
  647. /**
  648. * 获取公众账号基本信息
  649. * @param [string] $dir [指定相对于网站根目录的下载路径,因为需要下载二维码和用户头像]
  650. * @return [array] [公众账号信息,其中包含:nickname,avatar,type,qrcode,appid,appsecret]
  651. */
  652. public function getCommonInfo($dir)
  653. {
  654. $userInfo = array();
  655. $send_snoopy = new Snoopy;
  656. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  657. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&lang=zh_CN&token=".$this->_token;
  658. $url = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=".$this->_token;
  659. $send_snoopy->fetch($url);
  660. $result = $send_snoopy->results;
  661. // 分析首页内容,获取nickname,avatar,usertype
  662. preg_match_all('/class=\"nickname\">(.*)<\/a>/', $result, $matches1);
  663. preg_match_all('/<img src=\"(.*)\" class=\"avatar\"/', $result, $matches2);
  664. preg_match_all('/<label for=\"\" class=\"type icon_service_label\">(.*)<\/label>/', $result, $matches3);
  665. $userInfo["nickname"] = $nickname = $matches1[1][0];
  666. if(strpos($nickname, '<') !== false)
  667. {
  668. $userInfo["nickname"] = $nickname = substr($nickname, 0, strpos($nickname, '<'));
  669. }
  670. $userInfo["avatar"] = $avatar = $matches2[1][0];
  671. if( ! empty($matches3[1][0]))
  672. {
  673. $userInfo["type"] = $usertype = $matches3[1][0];
  674. }
  675. else
  676. {
  677. $userInfo["type"] = $usertype = "订阅号";
  678. }
  679. $this->log('Analysis account info:'. "\nNickname:". $nickname. "\nAvatar:". $avatar. "\nUsertype:". $usertype);
  680. // 分析设置页面,获取二维码
  681. $send_snoopy = new Snoopy;
  682. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  683. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&lang=zh_CN&token=".$this->_token;
  684. $url = "https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&lang=zh_CN&token=".$this->_token;
  685. $send_snoopy->fetch($url);
  686. $result = $send_snoopy->results;
  687. // $this->log("QRCODE contents:". $result);
  688. preg_match_all('/<img src=\"(.*)\" width=\"150\"/', $result, $matches4);
  689. $userInfo["qrcode"] = $qrcode = $matches4[1][0];
  690. // downloads the avatar
  691. $send_snoopy = new Snoopy;
  692. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  693. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&lang=zh_CN&token=".$this->_token;
  694. $url = "https://mp.weixin.qq.com". $avatar;
  695. $send_snoopy->fetch($url);
  696. $result = $send_snoopy->results;
  697. $userInfo["avatar"] = $this->downloadImage($result, $dir. DIRECTORY_SEPARATOR. 'avatars');
  698. // downloads the qrcode
  699. $send_snoopy = new Snoopy;
  700. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  701. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&lang=zh_CN&token=".$this->_token;
  702. $url = "https://mp.weixin.qq.com". $qrcode;
  703. $send_snoopy->fetch($url);
  704. $result = $send_snoopy->results;
  705. $userInfo["qrcode"] = $this->downloadImage($result, $dir. DIRECTORY_SEPARATOR. 'qrcodes');
  706. // 获取appid和appsecret
  707. $send_snoopy = new Snoopy;
  708. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  709. $send_snoopy->referer = "https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&lang=zh_CN&token=".$this->_token;
  710. $url = "https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&lang=zh_CN&token=".$this->_token;
  711. $send_snoopy->fetch($url);
  712. $result = $send_snoopy->results;
  713. preg_match_all('/name:\"AppId\",value:\"(.*)\"/', $result, $matches_id);
  714. preg_match_all('/name:\"AppSecret\",value:\"(.*)\"/', $result, $matches_secret);
  715. $userInfo["appid"] = $AppId = $matches_id[1][0];
  716. $userInfo["appsecret"] = $AppSecret = $matches_secret[1][0];
  717. if(! empty($userInfo)){
  718. return $userInfo;
  719. }
  720. return false;
  721. }
  722. /**
  723. * 下载图片资源
  724. * @param [string] $from [资源链接]
  725. * @param [string] $dir [相对于网站根目录]
  726. * @return [string] [返回相对地址]
  727. */
  728. public function downloadImage($from, $dir)
  729. {
  730. $random_name = str_replace('.', '', microtime(true)). rand(2, 10000);
  731. if( ! is_dir($dir))
  732. {
  733. mkdir($dir, 0755, true);
  734. }
  735. $savefile = preg_replace('/[\\\\\/]+/', DIRECTORY_SEPARATOR, $dir. '/'. $random_name);
  736. file_put_contents($savefile, $from);
  737. $filesize = filesize($savefile);
  738. $avatar_type = $this->checkImgType($savefile);
  739. if ($filesize <= 0 || $avatar_type=='unknown')
  740. {
  741. unlink($savefile);
  742. }
  743. exec("mv $savefile ". $savefile. '.'. $avatar_type);
  744. return $dir. '/'. $random_name. '.'. $avatar_type;
  745. }
  746. /**
  747. * 检测图片类型
  748. * @param [string] $imgName [文件路径]
  749. * @return [string] [文件类型]
  750. */
  751. public function checkImgType($imgName){
  752. $file = fopen($imgName, "rb");
  753. $bin = fread($file, 2);
  754. $strInfo = @unpack("C2chars", $bin);
  755. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  756. switch($typeCode)
  757. {
  758. case '255216':
  759. return 'jpg';
  760. break;
  761. case '7173':
  762. return 'gif';
  763. break;
  764. case '13780':
  765. return 'png';
  766. break;
  767. case '6677':
  768. return 'bmp';
  769. break;
  770. default:
  771. return 'unknown';
  772. break;
  773. }
  774. }
  775. /**
  776. * 模拟登录获取cookie
  777. * @return [type] [description]
  778. */
  779. public function login(){
  780. $snoopy = new Snoopy;
  781. $submit = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
  782. $post["username"] = $this->_account;
  783. $post["pwd"] = md5($this->_password);
  784. $post["f"] = "json";
  785. $post["imgcode"] = "";
  786. $snoopy->referer = "https://mp.weixin.qq.com/";
  787. $snoopy->submit($submit,$post);
  788. $cookie = '';
  789. $this->log($snoopy->results);
  790. $result = json_decode($snoopy->results,true);
  791. if (!isset($result['base_resp']) || $result['base_resp']['ret'] != 0) {
  792. return false;
  793. }
  794. foreach ($snoopy->headers as $key => $value) {
  795. $value = trim($value);
  796. if(preg_match('/^set-cookie:[\s]+([^=]+)=([^;]+)/i', $value,$match))
  797. $cookie .=$match[1].'='.$match[2].'; ';
  798. }
  799. preg_match("/token=(\d+)/i",$result['redirect_url'],$matches);
  800. if($matches){
  801. $this->_token = $matches[1];
  802. $this->log('token:'.$this->_token);
  803. }
  804. $cookies='{"cookie":"'.$cookie.'","token":"'.$this->_token.'"}';
  805. $this->saveCookie($this->_cookiename,$cookies);
  806. return $cookie;
  807. }
  808. /**
  809. * 把cookie写入缓存
  810. * @param string $filename 缓存文件名
  811. * @param string $content 文件内容
  812. * @return bool
  813. */
  814. public function saveCookie($filename,$content){
  815. return file_put_contents($filename,$content);
  816. }
  817. /**
  818. * 读取cookie缓存内容
  819. * @param string $filename 缓存文件名
  820. * @return string cookie
  821. */
  822. public function getCookie($filename){
  823. if (file_exists($filename)) {
  824. $mtime = filemtime($filename);
  825. if ($mtime<time()-$this->_cookieexpired)
  826. $data = '';
  827. else
  828. $data = file_get_contents($filename);
  829. } else
  830. $data = '';
  831. if($data){
  832. $login=json_decode($data,true);
  833. $send_snoopy = new Snoopy;
  834. $send_snoopy->rawheaders['Cookie']= $login['cookie'];
  835. $send_snoopy->maxredirs = 0;
  836. $url = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=".$login['token'];
  837. $send_snoopy->fetch($url);
  838. $header = $send_snoopy->headers;
  839. $this->log('header:'.print_r($send_snoopy->headers,true));
  840. if( strstr($header[3], 'EXPIRED')){
  841. return $this->login();
  842. }else{
  843. $this->_token =$login['token'];
  844. $this->log('token:'.$this->_token);
  845. return $login['cookie'];
  846. }
  847. }else{
  848. return $this->login();
  849. }
  850. }
  851. /**
  852. * 验证cookie的有效性
  853. * @return bool
  854. */
  855. public function checkValid()
  856. {
  857. if (!$this->cookie || !$this->_token) return false;
  858. $send_snoopy = new Snoopy;
  859. $post = array('ajax'=>1,'token'=>$this->_token);
  860. $submit = "https://mp.weixin.qq.com/cgi-bin/getregions?id=1017&t=ajax-getregions&lang=zh_CN";
  861. $send_snoopy->rawheaders['Cookie']= $this->cookie;
  862. $send_snoopy->submit($submit,$post);
  863. $result = $send_snoopy->results;
  864. if(json_decode($result,1)){
  865. return true;
  866. }else{
  867. return false;
  868. }
  869. }
  870. private function log($log){
  871. if ($this->debug && function_exists($this->_logcallback)) {
  872. if (is_array($log)) $log = print_r($log,true);
  873. return call_user_func($this->_logcallback,$log);
  874. }
  875. }
  876. }