-
Notifications
You must be signed in to change notification settings - Fork 156
/
Wechat.class.php
2384 lines (2235 loc) · 82.8 KB
/
Wechat.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// error_reporting(0);
/**
* 微信公共平台整合库
* @author Ligboy ([email protected])
* @license 本库的很多思路来自于网上的其他热心人士的贡献,大家任意使用,我本人放弃所有权利,如果您心情好,给我留个署名也行。
*
*/
interface WechatSessionToolInter {
/**
* @name 获取token
*
*/
function getToken();
/**
* @name 设置保存token
* @param string $token
*/
function setToken($token);
/**
* @name 获取Cookies
* @param string $session
*
*/
function getCookies($session);
/**
* @name 设置保存Cookies
* @param string $Cookies
* @param string $session
* @return
*/
function setCookies($Cookies, $session);
}
/**
* @author Ligboy
* @name 微信关联接口
*
*/
interface WechatAscToolInter {
/**
* @name 判断指定Openid是否关联
* @param string $Openid 指定Openid
* @return boolean 返回逻辑判断结果,已关联则返回用户信息数组
*/
function getAscStatusByOpenid($Openid);
/**
* @name 判断指定fakeid是否关联
* @param string $fakeid 指定fakeid
* @return boolean 返回逻辑判断结果,已关联则返回用户信息数组
*/
function getAscStatusByFakeid($fakeid);
/**
* @name 设置fakeid与Openid的关联
* @param string $openid Openid
* @param string $fakeid fakeid
* @param string $detailInfo $detailInfo
*/
function setAssociation($openid, $fakeid, $detailInfo);
}
interface WechatFollowToolInter {
/**
* @name 用户关注执行动作
* @param string $openid Openid
*/
function followAddAction($openid);
/**
* @name 取消关注执行动作
* @param string $openid Openid
*/
function followCancelAction($openid);
}
class Wechat {
/* 配置参数 */
/**
*
* @var array
* @example array('token'=>'微信接口密钥','account'=>'微信公共平台账号','password'=>'微信公共平台密码','webtoken'=>"微信公共平台网页url的token");
*/
private $wechatOptions=array('token'=>'rqerwer','account'=>'[email protected]','password'=>'wwwwww','session'=>"default"); //
public $webtoken = '';
public $debug = false; //调试开关
public $protocol = "https"; //使用协议类型 http or https
/* 静态常量 */
const MSGTYPE_TEXT = 'text';
const MSGTYPE_IMAGE = 'image';
const MSGTYPE_LOCATION = 'location';
const MSGTYPE_LINK = 'link';
const MSGTYPE_EVENT = 'event';
const MSGTYPE_MUSIC = 'music';
const MSGTYPE_NEWS = 'news';
const MSGTYPE_VOICE = 'voice';
const MSGTYPE_VIDEO = 'video';
const MSGTYPE_GOODS = 'goods';
const MSGTYPE_CARD = 'card';
public static $POSITIVE_MSGTYPE = array('text'=>1, 'image'=>2, 'voice'=>3, 'video'=>4, 'news'=>10,'goods'=>11, 'card'=>42); //主动消息类型代码数组
/* 私有参数 */
private $_msg;
private $_funcflag = false;
public $_receive;
private $_logcallback;
private $_getRevRunOnce = 0;
private $_cookies;
private $_wechatcallbackFuns = null;
private $_curlHttpObject = null;
private $_referer = "https://mp.weixin.qq.com/";
/**
* @var boolean 自动附带发送openid开关
*/
private $_autosendopenid = false;
/**
* @var boolean 被动响应关联动作开关
*/
private $_passiveAssociationSwitch = false;
/**
*
*/
/**
* @var boolean 被动响应关联动作开关
*/
private $_passiveAscGetDetailSwitch = false;
/**
* 初始化工作
* @param array $option array('token'=>'微信接口密钥','account'=>'微信公共平台账号','password'=>'微信公共平台密码');
*/
function __construct($option=array())
{
if (!empty($option))
{
$this->wechatOptions = array_merge($this->wechatOptions, $option);
}
}
/**
* @name 主动动作初始化
* @param string $session 登录会话
* @return Wechat
*/
function positiveInit($session=null)
{
$this->processSession($session);
if (!is_object($this->_wechatcallbackFuns)) {
if ($this->wechatOptions['wechattool']) {
$this->setWechatToolFun($this->wechatOptions['wechattool']);
}
$this->setWechatToolFun($this->wechatOptions['wechattool']);
}
$this->_cookies[$session] = $this->getCookies($session);
$this->webtoken = (string)$this->getToken();
return $this;
}
private function curlInit($type=null, $option=null) {
if (!isset($this->_curlHttpObject)) {
$this->_curlHttpObject = new CurlHttp();
}
if ("single"==$type) {
$this->_curlHttpObject->singleInit($option);
}
elseif ("roll"==$type){
$this->_curlHttpObject->rollInit($option);
}
return $this->_curlHttpObject;
}
/**
* 验证请求签名操作
* @return boolean
*/
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = $this->wechatOptions['token'];
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature )
{
return true;
}
else
{
return false;
}
}
/**
* 验证当前请求是否有效
* @param bool $return 是否返回
* @return bool|string
*/
public function valid($return=false)
{
$echoStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
if ($return)
{
if ($echoStr)
{
if ($this->checkSignature())
{
return $echoStr;
}
else
{
return false;
}
} else
return $this->checkSignature();
}
else
{
if ($echoStr)
{
if ($this->checkSignature())
{
die($echoStr);
}
else
{
die('no access');
}
}
else
{
if ($this->checkSignature())
{
return true;
}
else
{
die('no access');
}
}
}
}
/**
* 设置发送消息
* @param array|string $msg 消息数组
* @param bool $append 是否在原消息数组追加
* @return array|null
*/
public function Message($msg = '',$append = false){
if (is_null($msg)) {
$this->_msg =array();
}elseif (is_array($msg)) {
if ($append)
$this->_msg = array_merge($this->_msg,$msg);
else
$this->_msg = $msg;
return $this->_msg;
} else {
return $this->_msg;
}
return null;
}
public function setFuncFlag($flag) {
$this->_funcflag = $flag;
return $this;
}
private function log($log){
if ($this->debug && function_exists($this->_logcallback)) {
if (is_array($log)) $log = print_r($log,true);
return call_user_func($this->_logcallback,$log);
}
return null;
}
/**
* @name 获取微信服务器发来的信息
* @return mixed
*/
public function getRev()
{
$postStr = file_get_contents("php://input");
$this->log($postStr);
if (!empty($postStr))
{
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
}
if ($this->_getRevRunOnce==0) {
$event = $this->getRevEvent();
if (Wechat::MSGTYPE_EVENT==$this->getRevType())
{
if ($event['event']=="subscribe" && method_exists($this->_wechatcallbackFuns, "followAddAction")) {
$this->_wechatcallbackFuns->followAddAction($this->getRevFrom());
}
elseif ($event['event']=="unsubscribe" && method_exists($this->_wechatcallbackFuns, "followCancelAction")){
$this->_wechatcallbackFuns->followCancelAction($this->getRevFrom());
}
}
$this->doAssociationAction();
$this->_getRevRunOnce = 1;
}
return $this;
}
/**
* 获取消息发送者
* @return string or boolean
*/
public function getRevFrom()
{
if ($this->_receive)
{
return $this->_receive['FromUserName'];
}
else
{
return false;
}
}
/**
* 获取消息接受者
* @return string or boolean
*/
public function getRevTo()
{
if ($this->_receive)
{
return $this->_receive['ToUserName'];
}
else
{
return false;
}
}
/**
* 获取接收消息的类型
*/
public function getRevType()
{
if (isset($this->_receive['MsgType']))
{
return $this->_receive['MsgType'];
}
else
{
return false;
}
}
/**
* 获取消息ID
*/
public function getRevID() {
if (isset($this->_receive['MsgId']))
return $this->_receive['MsgId'];
else
return false;
}
/**
* 获取消息发送时间
*/
public function getRevCtime() {
if (isset($this->_receive['CreateTime']))
return $this->_receive['CreateTime'];
else
return false;
}
/**
* 获取接收消息内容正文
*/
public function getRevContent(){
if (isset($this->_receive['Content']))
return $this->_receive['Content'];
else
return false;
}
/**
* 获取接收消息图片
*/
public function getRevPic(){
if (isset($this->_receive['PicUrl']))
return $this->_receive['PicUrl'];
else
return false;
}
/**
* 获取接收消息链接
*/
public function getRevLink(){
if (isset($this->_receive['Url'])){
return array(
'url'=>$this->_receive['Url'],
'title'=>$this->_receive['Title'],
'description'=>$this->_receive['Description']
);
} else
return false;
}
/**
* 获取接收地理位置
* @return array('x'=>'','y'=>'','scale'=>'','label'=>'')
*/
public function getRevGeo(){
if (isset($this->_receive['Location_X'])){
return array(
'x'=>$this->_receive['Location_X'],
'y'=>$this->_receive['Location_Y'],
'scale'=>$this->_receive['Scale'],
'label'=>$this->_receive['Label']
);
} else
return false;
}
/**
* 获取接收事件推送
* @return array 成功返回事件数组,失败返回false
*/
public function getRevEvent(){
if (isset($this->_receive['Event'])){
return array(
'event'=>$this->_receive['Event'],
'key'=>$this->_receive['EventKey'],
);
} else
return false;
}
/**
* 获取接收语言推送
* @return array|bool
*/
public function getRevVoice(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'format'=>$this->_receive['Format'],
);
} else
return false;
}
private static function xmlSafeStr($str)
{
return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
}
/**
* 数据XML编码
* @param mixed $data 数据
* @return string
*/
private static function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml .= "<$key>";
$xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
list($key, ) = explode(' ', $key);
$xml .= "</$key>";
}
return $xml;
}
/**
* XML编码
* @param mixed $data 数据
* @param string $root 根节点名
* @param string $item 数字索引的子节点名
* @param string $attr 根节点属性
* @param string $id 数字索引子节点key转换的属性名
* @param string $encoding 数据编码
* @return string
*/
private function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
if(is_array($attr)){
$_attr = array();
foreach ($attr as $key => $value) {
$_attr[] = "{$key}=\"{$value}\"";
}
$attr = implode(' ', $_attr);
}
$attr = trim($attr);
$attr = empty($attr) ? '' : " {$attr}";
$xml =null;
$xml .= "<{$root}{$attr}>";
$xml .= self::data_to_xml($data, $item, $id);
$xml .= "</{$root}>";
return $xml;
}
/**
* 设置回复消息
* Examle: $obj->text('hello')->reply();
* @param string $text
* @return $this
*/
public function text($text='')
{
if ($this->_autosendopenid) {
if (is_object($this->_wechatcallbackFuns) && method_exists($this->_wechatcallbackFuns, "getAscStatusByOpenid")) {
if (!$this->_wechatcallbackFuns->getAscStatusByOpenid($this->getRevFrom())) {
$text .= "<a href=\"##".$this->getRevFrom()."\"> </a>";
}
}
else{
$text .= "<a href=\"##".$this->getRevFrom()."\"> </a>";
}
}
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_TEXT,
'Content'=>$text,
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 设置回复音乐
* @param string $title
* @param string $desc
* @param string $musicurl
* @param string $hgmusicurl
* @return $this
*/
public function music($title,$desc,$musicurl,$hgmusicurl='') {
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'CreateTime'=>time(),
'MsgType'=>self::MSGTYPE_MUSIC,
'Music'=>array(
'Title'=>$title,
'Description'=>$desc,
'MusicUrl'=>$musicurl,
'HQMusicUrl'=>$hgmusicurl
),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 设置回复图文
* @param array $newsData
* @return $this
* @example 数组结构:
* array(
* [0]=>array(
* 'Title'=>'msg title',
* 'Description'=>'summary text',
* 'PicUrl'=>'http://www.domain.com/1.jpg',
* 'Url'=>'http://www.domain.com/1.html'
* ),
* [1]=>....
* )
*/
public function news($newsData=array())
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$count = count($newsData);
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_NEWS,
'CreateTime'=>time(),
'ArticleCount'=>$count,
'Articles'=>$newsData,
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
*
* 向微信服务器回复消息
* Example: $this->text('msg tips')->reply();
* @param array|string $msg 要发送的信息, 默认取$this->_msg
* @param bool $return 是否返回信息而输出 默认:false
* @return string
*/
public function reply($msg=array(),$return = false)
{
if (empty($msg))
{
$msg = $this->_msg;
}
$xmldata= $this->xml_encode($msg);
$this->log($xmldata);
if ($return)
{
return $xmldata;
}
else
{
echo $xmldata;
}
//debug 调试记录回复信息
if ($this->debug){file_put_contents($this->debugpath."./reply.txt","\n---".date('Y-m-d H:i:s')."\n".$xmldata,FILE_APPEND);}
}
/**
* 登录微信公共平台,获取并保存cookie、webtoken到指定文件
* @param string $session
* @return mixed 成功则返回true,失败则返回失败代码
*/
public function login($session=null)
{
$this->processSession($session);
$url = $this->protocol."://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
$postfields["username"] = $this->wechatOptions['account'];
$postfields["pwd"] = md5($this->wechatOptions['password']);
$postfields["f"] = "json";
$postfieldss = "username=".urlencode($this->wechatOptions['account'])."&pwd=".urlencode(md5($this->wechatOptions['password']))."&f=json";
$this->curlInit("single");
$response = $this->_curlHttpObject->post($url, $postfields, $this->protocol."://mp.weixin.qq.com/cgi-bin/login", $this->_cookies[$session]);
$result = json_decode($response, true);
if ($result['ErrCode']=="65201"||$result['ErrCode']=="65202"||$result['ErrCode']=="0")
{
preg_match('/&token=([\d]+)/i', $result['ErrMsg'],$match);
$this->webtoken = $match[1];
$this->setToken($this->webtoken);
$this->setCookies($this->_curlHttpObject->getCookies(),$session);
return true;
}
else
{
// return false;
return $result['ErrCode'];
}
}
/**
* @name 执行关联动作
*/
private function doAssociationAction()
{
//var_dump($this->_passiveAssociationSwitch && Wechat::MSGTYPE_EVENT!=$this->getRevType() && is_object($this->_wechatcallbackFuns) && method_exists($this->_wechatcallbackFuns, "getAscStatusByOpenid") && method_exists($this->_wechatcallbackFuns, "setAssociation") && !$this->_wechatcallbackFuns->getAscStatusByOpenid($this->getRevFrom()));
if ($this->_passiveAssociationSwitch && Wechat::MSGTYPE_EVENT!=$this->getRevType() && is_object($this->_wechatcallbackFuns) && method_exists($this->_wechatcallbackFuns, "getAscStatusByOpenid") && method_exists($this->_wechatcallbackFuns, "setAssociation") && !$this->_wechatcallbackFuns->getAscStatusByOpenid($this->getRevFrom()))
{
//$messageList = $this->getMessage();
$messageList = $this->getMessage(0, 40, 0);
if ($messageList)
{
$count = 0;
$fakeid = "";
foreach ($messageList as $value)
{
if ($value['date_time']==$this->getRevCtime())
{
$count += 1;
$fakeid = $value['fakeid'];
}
}
if (1==$count && $fakeid!="")
{
$detailInfo = NULL;
if ($this->_passiveAscGetDetailSwitch)
{
$detailInfo = $this->getContactInfo($fakeid);
}
$this->_wechatcallbackFuns->setAssociation((string)$this->getRevFrom(), $fakeid, $detailInfo);
}
}
}
}
/**
* 验证登录是否在线
* @param string $session
* @return boolean
*/
public function checkValid($session=null)
{
$this->processSession($session);
$postfields = array();
$url = $this->protocol."://mp.weixin.qq.com/cgi-bin/getregions?id=1054&t=ajax-getregions&lang=zh_CN&token=".$this->webtoken;
//判断cookie是否为空,为空的话自动执行登录
if ($this->_cookies[$session]||($this->_cookies[$session] = $this->getCookies($session)))
{
$this->curlInit("single");
$response = $this->_curlHttpObject->get($url, $this->protocol."://mp.weixin.qq.com/cgi-bin/", $this->_cookies[$session]);
$result = json_decode($response,1);
if(isset($result['num']))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
/**
* keepLive心跳包保持,在线状态,推荐通过cron每15分钟调用一下
* @param string $session
* @return boolean
*/
public function keepLive($session=null)
{
$this->processSession($session);
/* if($session && strpos($session, ","))
{
$sessionList = explode(",", $session);
}*/
if (!$this->checkValid($session)) {
return (true===$this->login($session));
}
return 1;
}
/**
* 主动单条发消息
* @param $fakeid
* @param string $content 发送的内容
* @param string $type
* @param string $imgcode 验证码
* @param string $session 会话通道
* @return integer 返回发送结果:成功返回:1,登录问题返回:-1,;需要验证码:-6; 其他原因返回:0
*/
public function send($fakeid, $content, $type=Wechat::MSGTYPE_TEXT, $imgcode="fuck", $session=null)
{
$this->processSession($session);
return $this->_send($fakeid, $content, $type, $imgcode, $session);
}
/**
* 主动单条发送媒体消息
* @param $fakeid
* @param string $fid 发送的内容
* @param $type 发送消息类型
* @param string $imgcode 验证码
* @param string $session 会话通道
* @return integer 返回发送结果:成功返回:1,登录问题返回:-1,;需要验证码:-6; 其他原因返回:0
*/
public function sendMedia($fakeid, $fid, $type, $imgcode="fuck", $session=null)
{
$this->processSession($session);
return $this->_send($fakeid, $fid, $type, $imgcode, $session);
}
//TODO Working...... 待解决图文消息添加后获取fid问题。
/**
* 通过微信号直接发送图文
* @param $wechatno 微信号
* @param $newsArray 消息数组,格式:<p>array(
* array('title'=>'','digest'=>'','author'=>'','image'=>'','content'=>'','sourceurl'=>''),
* array('title'=>'','digest'=>'','author'=>'','image'=>'','content'=>'','sourceurl'=>''),
* )</p>
* @param string $session 会话通道
* @return bool
*/
public function sendPreNews($wechatno, $newsArray, $session=null)
{
$this->processSession($session);
$postfields = array();
$newsArray = array_values($newsArray);
if(count($newsArray) < 1)
{
return false;
}
$i = 0; //完备消息数量
foreach($newsArray as $value)
{
if(preg_match('/^[0-9]{8,9}$/', $value['image']))
{
$postfields['fileid'.$i] = $value['image'];
}
elseif($fid = $this->mediaUpload($value['image'], Wechat::MSGTYPE_IMAGE,$session))
{
$postfields['fileid'.$i] = $fid;
}
else
{
continue;
}
$postfields['title'.$i] = $value['title'];
$postfields['digest'.$i] = $value['desc']?$value['desc']:"";
$postfields['author'.$i] = $value['author']?$value['author']:"";
$postfields['content'.$i] = $value['content'];
$postfields['sourceurl'.$i] = $value['sourceurl']?$value['sourceurl']:"";
$i += 1;
}
if($i==0)
{
return false;
}
$postfields['count'] = $i;
$postfields['error'] = 'false';
$postfields['AppMsgId'] = "";
$postfields['token'] = $this->webtoken;
$postfields['ajax'] = 1;
$postfields['preusername'] = $wechatno;
$url = $this->protocol."://mp.weixin.qq.com/cgi-bin/operate_appmsg?sub=preview&t=ajax-appmsg-preview";
$this->curlInit("single");
$result = $this->_curlHttpObject->post($url, $postfields, $this->_referer, $this->getCookies($session));
$result_json_decode = json_decode($result, true);
if($result_json_decode && 'OK'==$result_json_decode['appMsgId'])
{
return $result_json_decode['appMsgId'];
}
else
{
return false;
}
}
/**
* 主动单条发消息
* @param $fakeid 消息接收人
* @param string $content 发送的内容或多媒体内容的fid
* @param null $type 消息类型 默认:Wechat::MSGTYPE_TEXT
* @param string $imgcode 验证码
* @param string $session 会话通道
* @return integer 返回发送结果:成功返回:1,登录问题返回:-1;需要验证码:-6;其他
*/
private function _send($fakeid, $content, $type=null, $imgcode="fuck", $session=null)
{
$this->processSession($session);
if($type==null)
{
$type = Wechat::MSGTYPE_TEXT;
}
//判断cookie是否为空,为空的话自动执行登录
if ($this->_cookies[$session]||true===$this->login($session))
{
$singleMessgae = array();
$singleMessgae['fakeid'] = $fakeid;
$singleMessgae['content'] = $content;
$singleMessgae['imgcode'] = $imgcode;
$singleMessgae['fid'] = $content;
$singleMessgae['type'] = $type;
$postfields = $this->buildPositiveMsgFields($singleMessgae);
$url = $this->protocol."://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response";
// $url = "http://api.fzuer.com/weixin/fzuer/index.php?m=Request&a=index";
$this->curlInit("single");
$response = $this->_curlHttpObject->post($url, $postfields, $this->protocol."://mp.weixin.qq.com/cgi-bin/singlemsgpage?", $this->_cookies[$session]);
$tmp = json_decode($response,true);
//判断发送结果的逻辑部分
if ('ok'==$tmp["msg"]) {
return 1;
}
elseif ($tmp['ret']=="-2000")
{
return -1;
}
else
{
return $tmp['ret'];
}
}
else //登录失败返回false
{
return 0;
}
}
/**
* 主动群发相同消息,目前暂支持文本方式
* @param array $fakeidGroup 接受微信fakeid集合数组
* @param string $content 群发消息内容
* @param null $type x
* @param string $session
* @return mixed 返回一个记录发送结果的数组列表
* 这里需要注意请求耗时问题,目前采用curl并发性请求.
*/
public function batSend($fakeidGroup,$content, $type=null, $session=null)
{
$this->processSession($session);
if(NULL==$type)
{
$type = Wechat::MSGTYPE_TEXT;
}
$queueSendArray = array();
foreach ($fakeidGroup as $key =>$value)
{
$queueSendArray[$key] = array(
'fakeid' => $value,
'content' => $content,
'type' => $type?$type:Wechat::MSGTYPE_TEXT,
'session' => $session
);
}
return $this->doQueueSend($queueSendArray);
}
/**
* 主动发送队列消息,目前暂支持文本方式
* @param array 发送队列数组<br />array(array('fakeid'=>'','content'=>"", 'type'=>''text' , 'session'=>'default'))
* @param integer $queueCount 并发数量,默认10
* @return mixed 返回一个记录发送结果的数组列表
* 这里需要注意请求耗时问题,目前采用curl并发性请求.
*/
public function queueSend($queueSendArray,$queueCount=10)
{
return $this->doQueueSend($queueSendArray,$queueCount);
}
/**
* 执行主动发送队列,默认并发队列数是10
* @param array $queueSendArray 发送队列数组 array(array('fakeid'='','content'))
* @param integer $queueCount 并发数量,默认10
* @return array 返回一个记录发送结果的数组列表
**/
private function doQueueSend($queueSendArray, $queueCount=10)
{
$requestArray = array();
foreach ($queueSendArray as $key =>$value)
{
$postfields = array();
$postfields = $this->buildPositiveMsgFields($value);
$url = $this->protocol."://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response";
$requestArray[$key] = array('url'=>$url,'method'=>'post','postfields'=>$postfields,'referer'=>$this->protocol."://mp.weixin.qq.com/cgi-bin/singlemsgpage?",'cookies'=>$this->_cookies[($value['session']?$value['session']:(empty($this->wechatOptions['session'])?"default":$this->wechatOptions['session']))]);
}
function callback($result, $key){
$tmp = json_decode($result,true);
//判断发送结果的逻辑部分
if ('ok'==$tmp["msg"]) {
return 1;
}
elseif ($tmp['ret']=="-2000")
{
return -1;
}
else
{
return $tmp['ret'];
}
};
$this->curlInit("roll");
$this->_curlHttpObject->setRollLimitCount($queueCount);
$response = $this->_curlHttpObject->setCallback("callback")->rollRequest($requestArray);
return $response;
}
/**
* 获取用户的信息
* @param string $fakeid 用户的fakeid
* @param string $session
* @return mixed 如果成功获取返回数据数组,登录问题返回false,其他未知问题返回true,
*/
public function getContactInfo($fakeid, $session=null)
{
$this->processSession($session);
$url = $this->protocol."://mp.weixin.qq.com/cgi-bin/getcontactinfo?t=ajax-getcontactinfo&lang=zh_CN&fakeid=".$fakeid;
$this->curlInit("single");
$postfields = array("token"=>$this->webtoken, "ajax"=>1);
$response = $this->_curlHttpObject->post($url, $postfields, $this->protocol."://mp.weixin.qq.com/", $this->_cookies[$session]);
$result = json_decode($response, 1);
if($result['FakeId']){
unset($result['Groups']);
return $result;
}
elseif ($result['ret'])
{
return false;
}