forked from dodgepudding/wechat-php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qywechat.class.php
2241 lines (2121 loc) · 69 KB
/
qywechat.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
/**
* 微信公众平台企业号PHP-SDK, 官方API类库
* @author binsee <[email protected]>
* @link https://github.com/binsee/wechat-php-sdk
* @version 1.0
* usage:
* $options = array(
* 'token'=>'tokenaccesskey', //填写应用接口的Token
* 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
* 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
* 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
* 'agentid'=>'1', //应用的id
* 'debug'=>false, //调试开关
* 'logcallback'=>'logg', //调试输出方法,需要有一个string类型的参数
* );
*
*/
class Wechat
{
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 EVENT_SUBSCRIBE = 'subscribe'; //订阅
const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消订阅
const EVENT_LOCATION = 'LOCATION'; //上报地理位置
const EVENT_ENTER_AGENT = 'enter_agent'; //用户进入应用
const EVENT_MENU_VIEW = 'VIEW'; //菜单 - 点击菜单跳转链接
const EVENT_MENU_CLICK = 'CLICK'; //菜单 - 点击菜单拉取消息
const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜单 - 扫码推事件(客户端跳URL)
const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜单 - 扫码推事件(客户端不跳URL)
const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜单 - 弹出系统拍照发图
const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜单 - 弹出拍照或者相册发图
const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜单 - 弹出微信相册发图器
const EVENT_MENU_LOCATION = 'location_select'; //菜单 - 弹出地理位置选择器
const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //发送结果 - 高级群发完成
const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//发送结果 - 模板消息发送结果
const API_URL_PREFIX = 'https://qyapi.weixin.qq.com/cgi-bin';
const USER_CREATE_URL = '/user/create?';
const USER_UPDATE_URL = '/user/update?';
const USER_DELETE_URL = '/user/delete?';
const USER_BATCHDELETE_URL = '/user/batchdelete?';
const USER_GET_URL = '/user/get?';
const USER_LIST_URL = '/user/simplelist?';
const USER_LIST_INFO_URL = '/user/list?';
const USER_GETINFO_URL = '/user/getuserinfo?';
const USER_INVITE_URL = '/invite/send?';
const DEPARTMENT_CREATE_URL = '/department/create?';
const DEPARTMENT_UPDATE_URL = '/department/update?';
const DEPARTMENT_DELETE_URL = '/department/delete?';
const DEPARTMENT_MOVE_URL = '/department/move?';
const DEPARTMENT_LIST_URL = '/department/list?';
const TAG_CREATE_URL = '/tag/create?';
const TAG_UPDATE_URL = '/tag/update?';
const TAG_DELETE_URL = '/tag/delete?';
const TAG_GET_URL = '/tag/get?';
const TAG_ADDUSER_URL = '/tag/addtagusers?';
const TAG_DELUSER_URL = '/tag/deltagusers?';
const TAG_LIST_URL = '/tag/list?';
const MEDIA_UPLOAD_URL = '/media/upload?';
const MEDIA_GET_URL = '/media/get?';
const AUTHSUCC_URL = '/user/authsucc?';
const MASS_SEND_URL = '/message/send?';
const MENU_CREATE_URL = '/menu/create?';
const MENU_GET_URL = '/menu/get?';
const MENU_DELETE_URL = '/menu/delete?';
const TOKEN_GET_URL = '/gettoken?';
const TICKET_GET_URL = '/get_jsapi_ticket?';
const CALLBACKSERVER_GET_URL = '/getcallbackip?';
const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
const OAUTH_AUTHORIZE_URL = '/authorize?';
private $token;
private $encodingAesKey;
private $appid; //也就是企业号的CorpID
private $appsecret;
private $access_token;
private $agentid; //应用id AgentID
private $postxml;
private $agentidxml; //接收的应用id AgentID
private $_msg;
private $_receive;
private $_sendmsg; //主动发送消息的内容
private $_text_filter = true;
public $debug = false;
public $errCode = 40001;
public $errMsg = "no access";
public $logcallback;
public function __construct($options)
{
$this->token = isset($options['token'])?$options['token']:'';
$this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
$this->appid = isset($options['appid'])?$options['appid']:'';
$this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
$this->agentid = isset($options['agentid'])?$options['agentid']:'';
$this->debug = isset($options['debug'])?$options['debug']:false;
$this->logcallback = isset($options['logcallback'])?$options['logcallback']:false;
}
protected 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);
}
}
/**
* 数据XML编码
* @param mixed $data 数据
* @return string
*/
public 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;
}
public static function xmlSafeStr($str)
{
return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
}
/**
* XML编码
* @param mixed $data 数据
* @param string $root 根节点名
* @param string $item 数字索引的子节点名
* @param string $attr 根节点属性
* @param string $id 数字索引子节点key转换的属性名
* @param string $encoding 数据编码
* @return string
*/
public 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 = "<{$root}{$attr}>";
$xml .= self::data_to_xml($data, $item, $id);
$xml .= "</{$root}>";
return $xml;
}
/**
* 微信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_string ( $value ) && 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
}
/**
* 过滤文字回复\r\n换行符
* @param string $text
* @return string|mixed
*/
private function _auto_text_filter($text) {
if (!$this->_text_filter) return $text;
return str_replace("\r\n", "\n", $text);
}
/**
* GET 请求
* @param string $url
*/
private function http_get($url){
$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_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
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
* @param boolean $post_file 是否文件上传
* @return string content
*/
private function http_post($url,$param,$post_file=false){
$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_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
if (is_string($param) || $post_file) {
$strPOST = $param;
} else {
$aPOST = array();
foreach($param as $key=>$val){
$aPOST[] = $key."=".urlencode($val);
}
$strPOST = join("&", $aPOST);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($oCurl, CURLOPT_POST,true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(intval($aStatus["http_code"])==200){
return $sContent;
}else{
return false;
}
}
/**
* For weixin server validation
*/
private function checkSignature($str)
{
$signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:'';
$timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
$nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
$tmpArr = array($str,$this->token, $timestamp, $nonce);//比普通公众平台多了一个加密的密文
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$shaStr = sha1($tmpStr);
if( $shaStr == $signature ){
return true;
}else{
return false;
}
}
/**
* 微信验证,包括post来的xml解密
* @param bool $return 是否返回
*/
public function valid($return=false)
{
$encryptStr="";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$postStr = file_get_contents("php://input");
$array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->log($postStr);
if (isset($array['Encrypt'])) {
$encryptStr = $array['Encrypt'];
$this->agentidxml = isset($array['AgentID']) ? $array['AgentID']: '';
}
} else {
$encryptStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
}
if ($encryptStr) {
$ret=$this->checkSignature($encryptStr);
}
if (!isset($ret) || !$ret) {
if (!$return) {
die('no access');
} else {
return false;
}
}
$pc = new Prpcrypt($this->encodingAesKey);
$array = $pc->decrypt($encryptStr,$this->appid);
if (!isset($array[0]) || ($array[0] != 0)) {
if (!$return) {
die('解密失败!');
} else {
return false;
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$this->postxml = $array[1];
//$this->log($array[1]);
return ($this->postxml!="");
} else {
$echoStr = $array[1];
if ($return) {
return $echoStr;
} else {
die($echoStr);
}
}
return false;
}
/**
* 获取微信服务器发来的信息
*/
public function getRev()
{
if ($this->_receive) return $this;
$postStr = $this->postxml;
$this->log($postStr);
if (!empty($postStr)) {
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
if (!isset($this->_receive['AgentID'])) {
$this->_receive['AgentID']=$this->agentidxml; //当前接收消息的应用id
}
}
return $this;
}
/**
* 获取微信服务器发来的信息
*/
public function getRevData()
{
return $this->_receive;
}
/**
* 获取微信服务器发来的原始加密信息
*/
public function getRevPostXml()
{
return $this->postxml;
}
/**
* 获取消息发送者
*/
public function getRevFrom() {
if (isset($this->_receive['FromUserName']))
return $this->_receive['FromUserName'];
else
return false;
}
/**
* 获取消息接受者
*/
public function getRevTo() {
if (isset($this->_receive['ToUserName']))
return $this->_receive['ToUserName'];
else
return false;
}
/**
* 获取接收消息的应用id
*/
public function getRevAgentID() {
if (isset($this->_receive['AgentID']))
return $this->_receive['AgentID'];
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 array(
'mediaid'=>$this->_receive['MediaId'],
'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
);
else
return false;
}
/**
* 获取接收地理位置
*/
public function getRevGeo(){
if (isset($this->_receive['Location_X'])){
return array(
'x'=>$this->_receive['Location_X'],
'y'=>$this->_receive['Location_Y'],
'scale'=>(string)$this->_receive['Scale'],
'label'=>(string)$this->_receive['Label']
);
} else
return false;
}
/**
* 获取上报地理位置事件
*/
public function getRevEventGeo(){
if (isset($this->_receive['Latitude'])){
return array(
'x'=>$this->_receive['Latitude'],
'y'=>$this->_receive['Longitude'],
'precision'=>$this->_receive['Precision'],
);
} else
return false;
}
/**
* 获取接收事件推送
*/
public function getRevEvent(){
if (isset($this->_receive['Event'])){
$array['event'] = $this->_receive['Event'];
}
if (isset($this->_receive['EventKey']) && !empty($this->_receive['EventKey'])){
$array['key'] = $this->_receive['EventKey'];
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 获取自定义菜单的扫码推事件信息
*
* 事件类型为以下两种时则调用此方法有效
* Event 事件类型,scancode_push
* Event 事件类型,scancode_waitmsg
*
* @return: array | false
* array (
* 'ScanType'=>'qrcode',
* 'ScanResult'=>'123123'
* )
*/
public function getRevScanInfo(){
if (isset($this->_receive['ScanCodeInfo'])){
if (!is_array($this->_receive['SendPicsInfo'])) {
$array=(array)$this->_receive['ScanCodeInfo'];
$this->_receive['ScanCodeInfo']=$array;
}else {
$array=$this->_receive['ScanCodeInfo'];
}
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 获取自定义菜单的图片发送事件信息
*
* 事件类型为以下三种时则调用此方法有效
* Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
* Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
* Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
*
* @return: array | false
* array (
* 'Count' => '2',
* 'PicList' =>array (
* 'item' =>array (
* 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
* 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
* ),
* ),
* )
*
*/
public function getRevSendPicsInfo(){
if (isset($this->_receive['SendPicsInfo'])){
if (!is_array($this->_receive['SendPicsInfo'])) {
$array=(array)$this->_receive['SendPicsInfo'];
if (isset($array['PicList'])){
$array['PicList']=(array)$array['PicList'];
$item=$array['PicList']['item'];
$array['PicList']['item']=array();
foreach ( $item as $key => $value ){
$array['PicList']['item'][$key]=(array)$value;
}
}
$this->_receive['SendPicsInfo']=$array;
} else {
$array=$this->_receive['SendPicsInfo'];
}
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 获取自定义菜单的地理位置选择器事件推送
*
* 事件类型为以下时则可以调用此方法有效
* Event 事件类型,location_select 弹出系统拍照发图的事件推送
*
* @return: array | false
* array (
* 'Location_X' => '33.731655000061',
* 'Location_Y' => '113.29955200008047',
* 'Scale' => '16',
* 'Label' => '某某市某某区某某路',
* 'Poiname' => '',
* )
*
*/
public function getRevSendGeoInfo(){
if (isset($this->_receive['SendLocationInfo'])){
if (!is_array($this->_receive['SendLocationInfo'])) {
$array=(array)$this->_receive['SendLocationInfo'];
if (empty($array['Poiname'])) {
$array['Poiname']="";
}
if (empty($array['Label'])) {
$array['Label']="";
}
$this->_receive['SendLocationInfo']=$array;
} else {
$array=$this->_receive['SendLocationInfo'];
}
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 获取接收语音推送
*/
public function getRevVoice(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'format'=>$this->_receive['Format'],
);
} else
return false;
}
/**
* 获取接收视频推送
*/
public function getRevVideo(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'thumbmediaid'=>$this->_receive['ThumbMediaId']
);
} else
return false;
}
/**
* 设置回复消息
* Example: $obj->text('hello')->reply();
* @param string $text
*/
public function text($text='')
{
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_TEXT,
'Content'=>$this->_auto_text_filter($text),
'CreateTime'=>time(),
);
$this->Message($msg);
return $this;
}
/**
* 设置回复消息
* Example: $obj->image('media_id')->reply();
* @param string $mediaid
*/
public function image($mediaid='')
{
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_IMAGE,
'Image'=>array('MediaId'=>$mediaid),
'CreateTime'=>time(),
);
$this->Message($msg);
return $this;
}
/**
* 设置回复消息
* Example: $obj->voice('media_id')->reply();
* @param string $mediaid
*/
public function voice($mediaid='')
{
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_IMAGE,
'Voice'=>array('MediaId'=>$mediaid),
'CreateTime'=>time(),
);
$this->Message($msg);
return $this;
}
/**
* 设置回复消息
* Example: $obj->video('media_id','title','description')->reply();
* @param string $mediaid
*/
public function video($mediaid='',$title='',$description='')
{
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_IMAGE,
'Video'=>array(
'MediaId'=>$mediaid,
'Title'=>$title,
'Description'=>$description
),
'CreateTime'=>time(),
);
$this->Message($msg);
return $this;
}
/**
* 设置回复图文
* @param array $newsData
* 数组结构:
* 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())
{
$count = count($newsData);
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_NEWS,
'CreateTime'=>time(),
'ArticleCount'=>$count,
'Articles'=>$newsData,
);
$this->Message($msg);
return $this;
}
/**
* 设置发送消息
* @param array $msg 消息数组
* @param bool $append 是否在原消息数组追加
*/
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;
}
}
/**
*
* 回复微信服务器, 此函数支持链式操作
* Example: $this->text('msg tips')->reply();
* @param string $msg 要发送的信息, 默认取$this->_msg
* @param bool $return 是否返回信息而不抛出到浏览器 默认:否
*/
public function reply($msg=array(),$return = false)
{
if (empty($msg))
$msg = $this->_msg;
$xmldata= $this->xml_encode($msg);
$this->log($xmldata);
$pc = new Prpcrypt($this->encodingAesKey);
$array = $pc->encrypt($xmldata, $this->appid);
$ret = $array[0];
if ($ret != 0) {
$this->log('encrypt err!');
return false;
}
$timestamp = time();
$nonce = rand(77,999)*rand(605,888)*rand(11,99);
$encrypt = $array[1];
$tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
sort($tmpArr, SORT_STRING);
$signature = implode($tmpArr);
$signature = sha1($signature);
$smsg = $this->generate($encrypt, $signature, $timestamp, $nonce);
$this->log($smsg);
if ($return)
return $smsg;
elseif ($smsg){
echo $smsg;
return true;
}else
return false;
}
private function generate($encrypt, $signature, $timestamp, $nonce)
{
//格式化加密信息
$format = "<xml>
<Encrypt><![CDATA[%s]]></Encrypt>
<MsgSignature><![CDATA[%s]]></MsgSignature>
<TimeStamp>%s</TimeStamp>
<Nonce><![CDATA[%s]]></Nonce>
</xml>";
return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
}
/**
* 设置缓存,按需重载
* @param string $cachename
* @param mixed $value
* @param int $expired
* @return boolean
*/
protected function setCache($cachename,$value,$expired){
//TODO: set cache implementation
return false;
}
/**
* 获取缓存,按需重载
* @param string $cachename
* @return mixed
*/
protected function getCache($cachename){
//TODO: get cache implementation
return false;
}
/**
* 清除缓存,按需重载
* @param string $cachename
* @return boolean
*/
protected function removeCache($cachename){
//TODO: remove cache implementation
return false;
}
/**
* 通用auth验证方法
* @param string $appid
* @param string $appsecret
* @param string $token 手动指定access_token,非必要情况不建议用
*/
public function checkAuth($appid='',$appsecret='',$token=''){
if (!$appid || !$appsecret) {
$appid = $this->appid;
$appsecret = $this->appsecret;
}
if ($token) { //手动指定token,优先使用
$this->access_token=$token;
return $this->access_token;
}
$authname = 'qywechat_access_token'.$appid;
if ($rs = $this->getCache($authname)) {
$this->access_token = $rs;
return $rs;
}
$result = $this->http_get(self::API_URL_PREFIX.self::TOKEN_GET_URL.'corpid='.$appid.'&corpsecret='.$appsecret);
if ($result)
{
$json = json_decode($result,true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->access_token = $json['access_token'];
$expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
$this->setCache($authname,$this->access_token,$expire);
return $this->access_token;
}
return false;
}
/**
* 删除验证数据
* @param string $appid
*/
public function resetAuth($appid=''){
if (!$appid) $appid = $this->appid;
$this->access_token = '';
$authname = 'qywechat_access_token'.$appid;
$this->removeCache($authname);
return true;
}
/**
* 删除JSAPI授权TICKET
* @param string $appid 用于多个appid时使用
*/
public function resetJsTicket($appid=''){
if (!$appid) $appid = $this->appid;
$this->jsapi_ticket = '';
$authname = 'qywechat_jsapi_ticket'.$appid;
$this->removeCache($authname);
return true;
}
/**
* 获取JSAPI授权TICKET
* @param string $appid 用于多个appid时使用,可空
* @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
*/
public function getJsTicket($appid='',$jsapi_ticket=''){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!$appid) $appid = $this->appid;
if ($jsapi_ticket) { //手动指定token,优先使用
$this->jsapi_ticket = $jsapi_ticket;
return $this->jsapi_ticket;
}
$authname = 'qywechat_jsapi_ticket'.$appid;
if ($rs = $this->getCache($authname)) {
$this->jsapi_ticket = $rs;
return $rs;
}
$result = $this->http_get(self::API_URL_PREFIX.self::TICKET_GET_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->jsapi_ticket = $json['ticket'];
$expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
$this->setCache($authname, $this->jsapi_ticket, $expire);
return $this->jsapi_ticket;
}
return false;
}
/**
* 获取JsApi使用签名
* @param string $url 网页的URL,自动处理#及其后面部分
* @param string $timestamp 当前时间戳 (为空则自动生成)
* @param string $noncestr 随机串 (为空则自动生成)
* @param string $appid 用于多个appid时使用,可空
* @return array|bool 返回签名字串
*/
public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
if (!$timestamp)
$timestamp = time();
if (!$noncestr)
$noncestr = $this->generateNonceStr();
$ret = strpos($url,'#');
if ($ret)
$url = substr($url,0,$ret);
$url = trim($url);
if (empty($url))
return false;
$arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
$sign = $this->getSignature($arrdata);
if (!$sign)
return false;
$signPackage = array(
"appid" => $this->appid,
"noncestr" => $noncestr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $sign
);
return $signPackage;
}
/**
* 获取签名