-
Notifications
You must be signed in to change notification settings - Fork 38
/
wechat-sdk.php
3266 lines (2747 loc) · 101 KB
/
wechat-sdk.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
/**
* WeChat PHP SDK
*
* Helper class to handle WeChat authentication, official account manipulation and ecommerce
* Requires Curl
*
* Inspired from the work of 小陈叔叔 <cjango@163.com> - https://coding.net/u/cjango/p/wechat_sdk/git
*
* @category SDK
* @package WeChat
* @author Alexandre Froger
* @copyright 2017 froger.me
* @license MIT License
* @version 2.0
* @see http://froger.me
*/
class Wechat_SDK {
/* Get access_token URL */
const AUTH_URL = 'https://api.weixin.qq.com/cgi-bin/token';
/* Menu URLs */
const MENU_CREATE_URL = 'https://api.weixin.qq.com/cgi-bin/menu/create';
const MENU_GET_URL = 'https://api.weixin.qq.com/cgi-bin/menu/get';
const MENU_DELETE_URL = 'https://api.weixin.qq.com/cgi-bin/menu/delete';
const MENU_CREATE_CONDITIONAL_URL = 'https://api.weixin.qq.com/cgi-bin/menu/addconditional';
const MENU_DELETE_CONDITIONAL_URL = 'https://api.weixin.qq.com/cgi-bin/menu/delconditional';
/* User and user group URLs */
const USER_GET_URL = 'https://api.weixin.qq.com/cgi-bin/user/get';
const USER_INFO_URL = 'https://api.weixin.qq.com/cgi-bin/user/info';
const USER_INFO_BATCH_URL = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget';
const TAG_ID_USER_URL = 'https://api.weixin.qq.com/cgi-bin/tags/getidlist';
const TAG_BATCH_UNTAG_URL = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging';
const TAG_BATCH_TAG_URL = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging';
const TAGGED_USERS_GET_URL = 'https://api.weixin.qq.com/cgi-bin/user/tag/get';
const TAG_DELETE_URL = 'https://api.weixin.qq.com/cgi-bin/tags/delete';
const TAG_UPDATE_URL = 'https://api.weixin.qq.com/cgi-bin/tags/update';
const TAG_GET_URL = 'https://api.weixin.qq.com/cgi-bin/tags/get';
const TAG_CREATE_URL = 'https://api.weixin.qq.com/cgi-bin/tags/create';
/* Send customer service message URL */
const CUSTOM_SEND_URL = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
/* Parametric QR code URLs */
const QRCODE_URL = 'https://api.weixin.qq.com/cgi-bin/qrcode/create';
const QRCODE_SHOW_URL = 'https://mp.weixin.qq.com/cgi-bin/showqrcode';
/* Web browser authentication QR code URL */
const QR_AUTHORIZATION_URL = 'https://open.weixin.qq.com/connect/qrconnect';
/* OAuth2.0 URLs */
const OAUTH_AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
const OAUTH_USER_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
const OAUTH_REFRESH_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
/* Get user info URL */
const GET_USER_INFO_URL = 'https://api.weixin.qq.com/sns/userinfo';
/* Message template URL */
const TEMPLATE_SEND_URL = 'https://api.weixin.qq.com/cgi-bin/message/template/send';
/* JS-SDK jsapi_ticket URL */
const JSAPI_TICKET_URL = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
/* Unified order */
const UNIFIED_ORDER_URL = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
const UNIFIED_ORDER_INTERFACE_VERSION = '1.0';
/* Order status inquiry URL */
const ORDER_QUERY_URL = 'https://api.mch.weixin.qq.com/pay/orderquery';
/* Close order URL */
const CLOSE_ORDER_URL = 'https://api.mch.weixin.qq.com/pay/closeorder';
/* Cancel payment URL */
const REVERSE_TRANSACTION_URL = 'https://api.mch.weixin.qq.com/secapi/pay/reverse';
/* Refund URL */
const PAY_REFUND_ORDER_URL = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
/* Refund inquiry URL */
const REFUND_QUERY_URL = 'https://api.mch.weixin.qq.com/pay/refundquery';
/* Download bill URL */
const DOWNLOAD_BILL_URL = 'https://api.mch.weixin.qq.com/pay/downloadbill';
/* URL shortener tool URL */
const GET_SHORT_URL = 'https://api.mch.weixin.qq.com/tools/shorturl';
/* Send red envelope URL */
const SEND_RED_PACK_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
/* Send shared red envelope URL */
const SEND_GROUP_RED_PACK_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack';
/* Red envelope inquiry URL */
const GET_RED_PACK_INFO_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo';
/* Assets management URLs */
const MEDIA_UPLOAD_URL = 'https://api.weixin.qq.com/cgi-bin/media/upload'; // add temporary Asset
const MEDIA_GET_URL = 'https://api.weixin.qq.com/cgi-bin/media/get'; // get temporary Asset
const MEDIA_NEWS_URL = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews'; // add temporary Rich Media Message Assets
const MATERIAL_NEWS_URL = 'https://api.weixin.qq.com/cgi-bin/material/add_news'; // add permanent Rich Media Message Assets
const MATERIAL_NEWS_IMAGE_URL = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg'; // add permanent Rich Media Message Image asset - images in news
const MATERIAL_FILE_URL = 'https://api.weixin.qq.com/cgi-bin/material/add_material'; // add permanent Asset
const MATERIAL_GET_URL = 'https://api.weixin.qq.com/cgi-bin/material/get_material'; // get permanent Asset
const MATERIAL_DEL_URL = 'https://api.weixin.qq.com/cgi-bin/material/del_material'; // remove permanent Asset
const MATERIAL_UPDATE_URL = 'https://api.weixin.qq.com/cgi-bin/material/update_news'; // update permanent Rich Media Message Asset
const MATERIAL_COUNT_URL = 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount'; // Get permanent Assets Count
const MATERIAL_LIST_URL = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material'; // Get permanent Assets List
/* Mass Broadcast URL */
const MASS_BY_TAG = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall';
const MASS_BY_USER = 'https://api.weixin.qq.com/cgi-bin/message/mass/send';
const MASS_DELETE = 'https://api.weixin.qq.com/cgi-bin/message/mass/delete';
const MASS_PREVIEW = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview';
const MASS_GET = 'https://api.weixin.qq.com/cgi-bin/message/mass/get';
/* Customer Service API */
const CS_SEND_MESSAGE = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
private $token;
private $appid;
private $secret;
private $access_token;
private $access_token_expire;
private $user_token;
private $debug = false;
private $data = array();
private $send = array();
private $error;
private $errorCode;
private $ticket;
private $result = false;
private $encode;
private $AESKey;
private $mch_appid;
private $mch_id;
private $payKey;
private $pemCert;
private $pemKey;
private $pemPath;
private $proxy;
private $proxyPort;
private $proxyHost;
public function __construct($options = array()) {
$this->token = isset($options['token']) ? $options['token'] : '';
$this->appid = isset($options['appid']) ? $options['appid'] : '';
$this->secret = isset($options['secret']) ? $options['secret'] : '';
$this->access_token = isset($options['access_token']) ? $options['access_token'] : '';
$this->access_token_expire = isset($options['access_token_expire']) ? $options['access_token_expire'] : '';
$this->debug = isset($options['debug']) ? $options['debug'] : false;
$this->encode = isset($options['encode']) && !empty($options['encode']) ? true : false;
$this->AESKey = isset($options['aeskey']) ? $options['aeskey'] : '';
$this->mch_appid = isset($options['mch_appid']) && !empty($options['mch_appid']) ? $options['mch_appid'] : $this->appid;
$this->mch_id = isset($options['mch_id']) ? $options['mch_id'] : '';
$this->payKey = isset($options['payKey']) ? $options['payKey'] : '';
$this->pem = isset($options['pem']) ? $options['pem'] : '';
$this->pemPath = isset($options['pemPath']) ? $options['pemPath'] : '';
$this->proxy = isset($options['proxy']) ? $options['proxy'] : false;
$this->proxyHost = isset($options['proxyHost']) ? $options['proxyHost'] : '';
$this->proxyPort = isset($options['proxyPort']) ? $options['proxyPort'] : '';
if ($this->encode && strlen($this->AESKey) != 43) {
$this->setError('AESKey Length Error');
return false;
}
}
public function __get($key) {
return $this->$key;
}
public function __set($key, $value) {
$this->$key = $value;
}
/**
* Check if accessing the app using the WeChat browser
* @param string $version Minimum required version - format: 3 numbers separated by "." - default empty string
* @return bool
*/
public static function isMobileBrowser($version = '') {
$is_wechat_mobile = (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false);
if ($is_wechat_mobile && !empty($version)) {
$version_parts = explode('.', $version_browser);
if (count($version_parts) < 3) {
$this->setError('Invalid WeChat version format');
$is_wechat_mobile = false;
} else {
foreach (explode(' ', $_SERVER['HTTP_USER_AGENT']) as $key => $value) {
if (strpos($value, 'MicroMessenger') !== false) {
$version_browser = end(explode('/', $value));
$version_browser_parts = explode('.', $version_browser);
$condition = (((int) $version_browser_parts[0]) >= ((int) $version_parts[0]));
if ($condition) {
$condition = ((int) $version_browser_parts[1]) >= ((int) $version_parts[1]);
}
if ($condition) {
$condition = ((int) $version_browser_parts[2]) >= ((int) $version_parts[2]);
}
if (!$condition) {
$this->setError('Current WeChat version ('. $version_browser .') < required version (' . $version . ')');
$is_wechat_mobile = false;
} else {
$is_wechat_mobile = true;
}
}
}
}
}
return $is_wechat_mobile;
}
/**
* Check if the website is bound to the WeChat official account
* @author, chen shushu <cjango@163.com>
*/
public function checkBind() {
$echoStr = filter_input(INPUT_GET, 'echostr', FILTER_UNSAFE_RAW);
if ($echoStr) {
if ($this->checkSignature()) {
exit($echoStr);
} else {
exit('Access Denied!');
}
}
return true;
}
/**
* Check official account's signature
* @author, chen shushu <cjango@163.com>
*/
public function checkSignature() {
if ($this->debug) {
return true;
}
$signature = filter_input(INPUT_GET, 'signature', FILTER_UNSAFE_RAW);
$timestamp = filter_input(INPUT_GET, 'timestamp', FILTER_UNSAFE_RAW);
$nonce = filter_input(INPUT_GET, 'nonce', FILTER_UNSAFE_RAW);
if (empty($signature) || empty($timestamp) || empty($nonce)) {
return false;
}
$token = $this->token;
if (!$token) {
return false;
}
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
return (sha1($tmpStr) === $signature);
}
/**
* Get official account's access_token
* @param boolean $force Force retrieving the access token from the API if true, get the property otherwise.
* @return string|boolean
* @author, chen shushu <cjango@163.com>
*/
public function getAccessToken($force = false) {
$access_token = $this->access_token;
if (!empty($access_token) && !$force) {
return $this->access_token;
} else {
if ($this->requestAccessToken()) {
return $this->access_token;
} else {
return false;
}
}
}
/**
* Set official account's access_token
* @param string $access_token A valid official account's access_token
* @author, chen shushu <cjango@163.com>
*/
public function setAccessToken($access_token) {
$this->access_token = $access_token;
}
/**
* Get official account's access_token expiry time (timestamp)
* @return integer|boolean
* @author, chen shushu <cjango@163.com>
*/
public function getAccessTokenExpiry() {
return ($this->access_token_expire) ? $this->access_token_expire : false;
}
/**
* Set official account's access_token expiry time
* @param integer The official account's access_token expiry time (timestamp)
* @author, chen shushu <cjango@163.com>
*/
public function setAccessTokenExpiry($access_token_expire) {
$this->access_token_expire = $access_token_expire;
}
/**
* Retrieve the official account's access_token from the WeChat remote interface
* @author, chen shushu <cjango@163.com>
*/
private function requestAccessToken() {
$params = array(
'grant_type' => 'client_credential',
'appid' => $this->appid,
'secret' => $this->secret,
);
$jsonStr = $this->http(self::AUTH_URL, $params);
if ($jsonStr) {
$this->parseJson($jsonStr);
if (false === $this->getError()) {
$jsonArr = $this->result;
$this->access_token = $jsonArr['access_token'];
$this->access_token_expire = time() + $jsonArr['expires_in'];
return $this->access_token;
} else {
return false;
}
} else {
return false;
}
}
/**
* Get the official account's custom menu
* @return array | boolean
* @author, chen shushu <cjango@163.com>
*/
public function menus() {
$params = array(
'access_token' => $this->getAccessToken(),
);
$jsonStr = $this->http(self::MENU_GET_URL, $params);
$res = $this->parseJson($jsonStr);
return ($res) ? $this->result : false;
}
/**
* Create the official account's custom menu
* @param array $menus An array representing the custom menu
* @param bool $conditional Whether the menu structure is conditional or general
* @see http://open.wechat.com/cgi-bin/newreadtemplate?t=overseas_open/docs/oa/custom-menus/create
* @see http://open.wechat.com/cgi-bin/newreadtemplate?t=overseas_open/docs/oa/custom-menus/personalized#custom-menus_personalized
* @return boolean
* @author, chen shushu <cjango@163.com>
*/
public function menu_create($menus = array(), $conditional = false) {
if (empty($menus)) {
$this->setError('Menu array representation required');
return false;
}
$params = $this->json_encode($menus);
if ($conditional) {
$url = self::MENU_CREATE_CONDITIONAL_URL . '?access_token=' . $this->getAccessToken();
} else {
$url = self::MENU_CREATE_URL . '?access_token=' . $this->getAccessToken();
}
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Delete the official account's custom menus
* @param int $menu_id the id of the menu to delete - delete all menus by default ; default null
* @see http://open.wechat.com/cgi-bin/newreadtemplate?t=overseas_open/docs/oa/custom-menus/delete
* @see http://open.wechat.com/cgi-bin/newreadtemplate?t=overseas_open/docs/oa/custom-menus/personalized#custom-menus_personalized
* @return boolean
* @author, chen shushu <cjango@163.com>
*/
public function menu_delete($menu_id = NULL) {
$params = array();
if ($menu_id !== NULL) {
$params['menuid'] = ((string)$menu_id);
$url = self::MENU_DELETE_CONDITIONAL_URL . '?access_token=' . $this->getAccessToken();
} else {
$url = self::MENU_DELETE_URL . '?access_token=' . $this->getAccessToken();
}
$params = json_encode($params);
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Get official account's followers tags
* @return array|boolean
*/
public function tags() {
$url = self::TAG_GET_URL . '?access_token='.$this->getAccessToken();
$jsonStr = $this->http($url);
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return $this->result['tags'];
} else {
return false;
}
}
/**
* Add a followers tag to the official account
* @param string $name Followers' tag name
* @return boolean
*/
public function tag_add($name = '') {
if (empty($name)) {
$this->setError('Followers tag name required');
return false;
}
$params = array(
'tag' => array(
'name' => $name,
)
);
$params = $this->json_encode($params);
$url = self::TAG_CREATE_URL . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return $this->result['tag'];
} else {
return false;
}
}
/**
* Update an official account's followers tag
* @param integer $tag_id Followers tag ID
* @param string $name New followers tag name
* @return boolean
*/
public function tag_update($tag_id = '', $name = '') {
if (empty($name) || empty($tag_id)) {
$this->setError('Followers tag ID and new Followers tag name required');
return false;
}
$params = array(
'tag' => array(
'id' => $tag_id,
'name' => $name,
)
);
$params = $this->json_encode($params);
$url = self::TAG_UPDATE_URL . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Delete an official account's followers tag
* @param integer $tag_id Followers tag ID
* @return boolean
*/
public function tag_delete($tag_id) {
$params = array(
'tag' => array(
'id' => $tag_id,
),
);
$params = $this->json_encode($params);
$url = self::TAG_DELETE_URL . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Get a list of openIDs of the official account's followers
* Max 10,000 openIDs can be loaded ; use the index 'next_openid' and call this method again to get more users
* If success, the returned array has the following indexes:
* - 'data' contains the users
* - 'total' is the number of total users in the account (not present if $tag_id is used)
* - 'count' is the number of users loaded
* - 'next_openid' the openID from which to load the batch of users
* @param string $next_openid The openID from which to load the batch of users - default empty string
* @param int $tag_id The tag ID to filter the users list by - default null
* @return array|boolean
*/
public function users($next_openid = '', $tag_id = null) {
$params = array();
if (!empty($next_openid)) {
$params['next_openid'] = $next_openid;
}
if (null !== $tag_id && is_numeric($tag_id)) {
$url = self::TAGGED_USERS_GET_URL . '?access_token=' . $this->getAccessToken();
} else {
$url = self::USER_GET_URL;
$params['access_token'] = $this->getAccessToken();
}
$jsonStr = $this->http($url, $params);
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
$data = $this->result['data']['openid'];
unset($this->result['data']);
$this->result['data'] = $data;
return $this->result;
} else {
return false;
}
}
/**
* Get the information of a follower of the official account
* @param string $openid the follower's openID
* @return array|boolean
*/
public function follower($openid = '') {
$jsonArr = $this->user($openid);
if ($jsonArr['subscribe'] == 1) {
unset($jsonArr['subscribe']);
return $jsonArr;
} else {
if (empty($this->errorCode)) {
$this->setError('No Follower found');
}
return false;
}
}
/**
* Get the information of a WeChat user
* @param string $openid the WeChat user openID
* @return array|boolean
*/
public function user($openid = '') {
if (empty($openid)) {
$this->setError('User openID required');
return false;
}
$params = array(
'access_token' => $this->getAccessToken(),
'lang' => 'zh_CN',
'openid' => $openid,
);
$jsonStr = $this->http(self::USER_INFO_URL, $params);
$res = $this->parseJson($jsonStr);
return ($res) ? $this->result : false;
}
/**
* Get the information of a list of WeChat users
* @param array $users_info the list of WeChat user info - array count max to 100. Each item is an array with keys 'openid' (required) and 'lang' (optional)
* @return array|boolean
*/
public function user_batch($users_info = array()) {
if (empty($users_info)) {
$this->setError('User openIDs required');
return false;
}
$params = array(
'user_list' => $users_info,
);
$url = self::USER_INFO_BATCH_URL . '?access_token=' . $this->getAccessToken();
$params = $this->json_encode($params);
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return $this->result['user_info_list'];
} else {
return false;
}
}
/**
* Get tags assigned to a follower
* @param string $openid Follower's openID
* @return array|boolean
*/
public function user_tags($openid = '') {
if (empty($openid)) {
$this->setError('Follower openID required');
return false;
}
$params = array(
'openid' => $openid,
);
$params = $this->json_encode($params);
$url = self::TAG_ID_USER_URL . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return $this->result['tagid_list'];
} else {
return false;
}
}
/**
* Batch assign a follower's tag to followers
* @param array $openids Follower's openIDs
* @param integer $tag_id Follower's tag ID
* @return boolean
*/
public function users_batch_assign_tag($openids = array(), $tag_id = '') {
if (empty($openids) || !is_numeric($tag_id)) {
$this->setError('Follower openIDs and numeric tag ID required');
return false;
}
$params = array(
'openid_list' => $openids,
'tagid' => $tag_id,
);
$params = $this->json_encode($params);
$url = self::TAG_BATCH_TAG_URL . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Batch unassign a follower's tag from followers
* @param array $openids Follower's openIDs
* @param integer $tag_id Follower's tag ID
* @return boolean
*/
public function users_batch_unassign_tag($openids = array(), $tag_id = '') {
if (empty($openids) || !is_numeric($tag_id)) {
$this->setError('Follower openIDs and numeric tag ID required');
return false;
}
$params = array(
'openid_list' => $openids,
'tagid' => $tag_id,
);
$params = $this->json_encode($params);
$url = self::TAG_BATCH_UNTAG_URL . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Get data pushed by WeChat to the server
* @return array An array of data with keys all converted to lowercase
*/
public function request() {
$postStr = file_get_contents("php://input");
if (!empty($postStr)) {
$data = $this->_extractXml($postStr);
if ($this->encode && isset($data['encrypt'])) {
$data = $this->AESdecode($data['encrypt']);
}
if (!empty($data)) {
foreach ($data as $key => $value) {
if ($value instanceof SimpleXMLElement) {
$data[$key] = $this->json_encode($this->_extractXml($value), false);
}
}
}
return $this->data = $data;
} else {
return false;
}
}
/**
* Parse an XML string and converts it to an array with keys in lowercase
* @param string $xml
* @return array
*/
private function _extractXml($xml) {
$data = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
return array_change_key_case($data, CASE_LOWER);
}
/**
* Reply to a WeChat message (auto-reply).
* Uses the Customer Service API.
* A call to "exit" is necessary after calling this method (of after error handling).
* @param string $to Receiver's OpenID
* @param string $from Developer's ID
* @param string $type Message type - "text", "music", "news", "voice", "video", "mpnews", "msgmenu" - default "text"
* @param array $content Response information - all values in the array must be of type string
* @return string|bool
*/
public function response($type = 'text', $content = '') {
$this->data = array(
'touser' => $this->data['fromusername'],
'msgtype' => $type,
);
if (!method_exists($this, $type)) {
$this->setError('Invalid WeChat response message type "' . $type . '"');
return false;
}
$this->$type($content);
$response = 'success';
ob_start();
$serverProtocol = filter_input(INPUT_SERVER, 'SERVER_PROTOCOL', FILTER_UNSAFE_RAW);
echo 'success';
header($serverProtocol . ' 200 OK');
header('Content-type: plain/text');
header('Content-Encoding: none');
header('Connection: close');
header('Content-Length: ' . ob_get_length());
ob_end_flush();
ob_flush();
flush();
$params = $this->json_encode($this->data);
$url = self::CS_SEND_MESSAGE . '?access_token=' . $this->getAccessToken();
$jsonStr = $this->http($url, $params, 'POST');
$res = $this->parseJson($jsonStr);
if (false === $this->getError()) {
return true;
} else {
return false;
}
}
/**
* Sign a mesage with SHA1
* @param string $encrypt_msg Message to sign
* @param string $nonce Random characters string
* @return string
*/
public function getSHA1($encrypt_msg, $nonce) {
$array = array($encrypt_msg, $this->token, time(), $nonce);
sort($array, SORT_STRING);
$str = implode($array);
return sha1($str);
}
/**
* Set Text response content
* @param string $content Text content
*/
private function text($content) {
$this->data['text'] = array('content' => $content);
}
/**
* Set Music response content
* @param array $content Music content
*/
private function music($music) {
$content = array();
$content['title'] = $music['title'];
$content['description'] = $music['description'];
$content['musicurl'] = $music['musicurl'];
$content['hqmusicurl'] = $music['hqmusicurl'];
$content['thumb_media_id'] = $music['thumb_media_id'];
$this->data['music'] = $content;
}
/**
* Set image response content
* @param array $image image content
*/
private function image($image) {
$content = array();
$content['media_id'] = $image['media_id'];
$this->data['image'] = $content;
}
/**
* Set Rich Media response content
* @param array $news Rich Media content
*/
private function news($news) {
$articles = array();
foreach ($news as $key => $value) {
$articles[$key] = array();
$articles[$key]['title'] = $value['title'];
$articles[$key]['description'] = $value['description'];
$articles[$key]['picurl'] = $value['picurl'];
$articles[$key]['url'] = $value['url'];
if ($key >= 1) {
break;
} // Maximum 1 news
}
$this->data['news'] = array('articles' => $articles);
}
/**
* Set voice response content
* @param array $voice voice content
*/
private function voice($voice) {
$content = array();
$content['media_id'] = $voice['media_id'];
$this->data['voice'] = $content;
}
/**
* Set video response content
* @param string $video video content
*/
private function video($video) {
$content = array();
$content['media_id'] = $video['media_id'];
$content['thumb_media_id'] = $video['thumb_media_id'];
$content['title'] = $video['title'];
$content['description'] = $video['description'];
$this->data['video'] = $content;
}
/**
* Set mpnews response content
* @param array $mpnews mpnews content
*/
private function mpnews($mpnews) {
$content = array();
$content['media_id'] = $mpnews['media_id'];
$this->data['mpnews'] = $content;
}
/**
* Set menu response content
* @param array $menu menu content
*/
private function msgmenu($menu) {
$content = array();
$content['head_content'] = $menu['head_content'];
$content['tail_content'] = $menu['tail_content'];
$content['list'] = array();
foreach ($menu['list'] as $key => $value) {
$item = array();
if ( is_array( $value ) ) {
if ( isset( $value['id'] ) ) {
$item['id'] = $value['id'];
} else {
$item['id'] = (string) $key;
}
$item['content'] = $value['content'];
} else {
$item['id'] = (string) $key;
$item['content'] = $value;
}
$content['list'][] = $item;
}
$this->data['msgmenu'] = $content;
}
/**
* Convert an aray to XML string