-
Notifications
You must be signed in to change notification settings - Fork 2
/
Wechat.php
2570 lines (2433 loc) · 85.2 KB
/
Wechat.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
namespace xfstudio\wechat;
use Yii;
use yii\base\Event;
use yii\base\Component;
use yii\web\HttpException;
use yii\base\InvalidParamException;
use yii\base\InvalidConfigException;
/**
* 微信公众号API类
* 相关文档请参考 http://mp.weixin.qq.com/wiki 微信公众平台开发者文档
*
* @package callmez\wechat\components
* @version 1.0.0alpha
*/
class Wechat extends Component
{
const EVENT_AFTER_ACCESS_TOKEN_UPDATE = 'afterAccessTokenUpdate';
const EVENT_AFTER_JS_API_TICKET_UPDATE = 'afterJsApiTicketUpdate';
/**
* 微信接口基本地址
*/
const WECHAT_BASE_URL = 'https://api.weixin.qq.com';
/**
* access token获取
*/
const WECHAT_ACCESS_TOKEN_URL = '/cgi-bin/token?';
/**
* js api ticket 获取
*/
const WECHAT_JS_API_TICKET_URL = '/cgi-bin/ticket/getticket?';
/**
* 创建菜单
*/
const WECHAT_MENU_CREATE_URL = '/cgi-bin/menu/create?';
/**
* 获取菜单
*/
const WECHAT_MENU_GET_URL = '/cgi-bin/menu/get?';
/**
* 删除菜单
*/
const WECHAT_MENU_DELETE_URL = '/cgi-bin/menu/delete';
/**
* 发送客服消息
*/
const WECHAT_CUSTOM_MESSAGE_SEND_URL = '/cgi-bin/message/custom/send?';
/**
* 发送模板消息
*/
const WECHAT_TEMPLATE_MESSAGE_SEND_URL = '/cgi-bin/message/template/send?';
/**
* 消息上传
*/
const WECHAT_ARTICLES_UPLOAD_URL = '/cgi-bin/media/uploadnews?';
/**
* 消息发送
*/
const WECHAT_ARTICLES_SEND_URL = '/cgi-bin/message/mass/sendall?';
/**
* 删除群发
*/
const WECHAT_ARTICLES_SEND_CANCEL_URL = '/cgi-bin/message/mass/delete?';
/**
* video消息的上传
*/
const WECHAT_MEDIA_VIDEO_UPLOAD_URL = '/cgi-bin/media/uploadvideo?';
/**
* 媒体文件上传
*/
const WECHAT_MEDIA_UPLOAD_URL = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?';
/**
* 媒体文件获取
*/
const WECHAT_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin/media/get?';
/**
* 分组创建
*/
const WECHAT_CREATE_GROUP_URL = '/cgi-bin/groups/create?';
/**
* 分组列表获取
*/
const WECHAT_GROUP_GET_URL = '/cgi-bin/groups/get?';
/**
* 修改分组名
*/
const WECHAT_UPDATE_GROUP_NAME_URL = '/cgi-bin/groups/update?';
/**
* 获取关注者所在分组ID
*/
const WECHAT_GET_GROUP_ID_URL = '/cgi-bin/groups/getid?';
/**
* 修改关注者所在分组
*/
const WECHAT_MEMBER_GROUP_UPDATE_URL = '/cgi-bin/groups/members/update?';
/**
* 修改关注者备注
*/
const WECHAT_MEMBER_REMARK_UPDATE_URL = '/cgi-bin/user/info/updateremark?';
/**
* 关注者基本信息
*/
const WECHAT_MEMBER_INFO_URL = '/cgi-bin/user/info?';
/**
* 关注者列表
*/
const WECHAT_MEMBER_GET_URL = '/cgi-bin/user/get?';
/**
* 获取客服聊天记录
*/
const WECHAT_CUSTOMER_SERVICE_RECORD_GET_URL = '/cgi-bin/customservice/getrecord?';
/**
* QR二维码创建
*/
const WECHAT_CREATE_QRCODE_URL = '/cgi-bin/qrcode/create?';
/**
* QR二维码展示
*/
const WECHAT_SHOW_QRCODE_URL = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?';
/**
* 短连接
*/
const WECHAT_SHORT_URL_URL = '/cgi-bin/shorturl?';
/**
* 网页授权获取用户信息
*/
const WECHAT_OAUTH2_AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
/**
* 获取网页授权后获取用户access_token地址
*/
const WECHAT_OAUTH2_ACCESS_TOKEN_URL = '/sns/oauth2/access_token?';
/**
* 网页授权后获取的access_token失效刷新地址
*/
const WECHAT_OAUTH2_ACCESS_TOKEN_REFRESH_URL = '/sns/oauth2/refresh_token?';
/**
* 检验授权凭证(access_token)是否有效地址
*/
const WECHAT_SNS_AUTH_URL = '/sns/auth?';
/**
* 拉取用户信息
*/
const WEHCAT_SNS_USER_INFO_URL = '/sns/userinfo?';
/**
* 标记客户的投诉处理状态
*/
const WECHAT_PAY_FEEDBACK_URL = '/payfeedback/update?';
/**
* 商品创建
*/
const WECHAT_SHOP_PRODUCT_CREATE_URL = '/merchant/create?';
/**
* 商品删除
*/
const WECHAT_SHOP_PRODUCT_DELETE_URL = '/merchant/del?';
/**
* 商品修改
*/
const WECHAT_SHOP_PRODUCT_UPDATE_URL = '/merchant/update?';
/**
* 获取商品
*/
const WECHAT_SHOP_PRODUCT_GET_URL = '/merchant/del?';
/**
* 获取指定状态的所有商品
*/
const WECHAT_SHOP_STATUS_PRODUCT_UPDATE_URL = '/merchant/getbystatus?';
/**
* 商品上下架
*/
const WECHAT_SHOP_STATUS_PRODUCT_GET_URL = '/merchant/modproductstatus?';
/**
* 商品增加库存
*/
const WECHAT_SHOP_PRODUCT_STOCK_ADD_URL = '/merchant/stock/add?';
/**
* 商品减少库存
*/
const WECHAT_SHOP_PRODUCT_STOCK_REDUCE_URL = '/merchant/stock/reduce?';
/**
* 增加分组
*/
const WECHAT_SHOP_GROUP_ADD_URL = '/merchant/group/add?';
/**
* 删除分组
*/
const WECHAT_SHOP_GROUP_DELETE_URL = '/merchant/group/del?';
/**
* 修改分组属性
*/
const WECHAT_SHOP_GROUP_UPDATE_URL = '/merchant/group/propertymod?';
/**
* 修改分组商品
*/
const WECHAT_SHOP_GROUP_PRODUCT_UPDATE_URL = '/merchant/group/productmod?';
/**
* 获取所有分组
*/
const WECHAT_SHOP_GROUP_LIST_URL = '/merchant/group/getall?';
/**
* 根据分组ID获取分组信息
*/
const WECHAT_SHOP_GROUP_ID_GET_URL = '/merchant/group/getbyid?';
/**
* 获取指定分类的所有子分类
*/
const WECHAT_SHOP_CATEGORY_SUB_GET_URL = '/merchant/category/getsub?';
/**
* 获取指定子分类的所有SKU
*/
const WECHAT_SHOP_CATEGORY_SKU_LIST_GET_URL = '/merchant/category/getsku?';
/**
* 获取指定分类的所有属性
*/
const WECHAT_SHOP_CATEGORY_PROPERTY_GET_URL = '/merchant/category/getproperty?';
/**
* 增加邮费模板
*/
const WECHAT_SHOP_DELIVERY_TEMPLATE_ADD_URL = '/merchant/express/add?';
/**
* 删除邮费模板
*/
const WECHAT_SHOP_DELIVERY_TEMPLATE_DELETE_URL = '/merchant/express/del?';
/**
* 修改邮费模板
*/
const WECHAT_SHOP_DELIVERY_TEMPLATE_UPDATE_URL = '/merchant/express/update?';
/**
* 获取指定ID的邮费模板
*/
const WECHAT_SHOP_DELIVERY_TEMPLATE_ID_GET_URL = '/merchant/express/getbyid?';
/**
* 获取所有邮费模板
*/
const WECHAT_SHOP_DELIVERY_TEMPLATE_LIST_GET_URL = '/merchant/express/getall?';
/**
* 增加货架
*/
const WECHAT_SHOP_SHELF_ADD_URL = '/merchant/shelf/add?';
/**
* 删除货架
*/
const WECHAT_SHOP_SHELF_DELETE_URL = '/merchant/shelf/del?';
/**
* 修改货架
*/
const WECHAT_SHOP_SHELF_UPDATE_URL = '/merchant/shelf/mod?';
/**
* 获取所有货架
*/
const WECHAT_SHOP_SHELF_LIST_URL = '/merchant/shelf/getall?';
/**
* 根据货架ID获取货架信息
*/
const WECHAT_SHOP_SHELF_ID_GET_URL = '/merchant/shelf/getbyid?';
/**
* 根据订单ID获取订单详情
*/
const WECHAT_SHOP_ORDER_GET_URL = '/merchant/order/getbyid?';
/**
* 根据订单状态/创建时间获取订单详情
*/
const WECHAT_SHOP_ORDER_FILTER_GET_URL = '/merchant/order/getbyfilter?';
/**
* 设置订单发货信息
*/
const WECHAT_SHOP_ORDER_DELIVERY_SET_URL = '/merchant/order/setdelivery?';
/**
* 关闭订单
*/
const WECHAT_SHOP_ORDER_CLOSE_URL = '/merchant/order/close?';
/**
* 上传图片(小店接口)
*/
const WECHAT_SHOP_IMAGE_UPLOAD_URL = '/merchant/common/upload_img?';
//==============卡券部分============================================
/**
* 获取微信卡券颜色列表
*/
const WECHAT_GET_CARD_COLORS_URL = '/card/getcolors?';
/**
* 创建卡券
*/
const WECHAT_CREATE_CARD_URL = '/card/create?';
/**
* 创建二维码
*/
const WECHAT_CARD_QRCODE_CREATE_URL = '/card/qrcode/create?';
/**
* 获取单个卡券详情
*/
const WECHAT_GET_CARD_URL = '/card/get?';
/**
* 核销卡券
*/
const WECHAT_CARD_CONSUME_URL = '/card/code/consume?';
/**
* 删除卡券
*/
const WECHAT_DELETE_CARD_URL = '/deleteCard?';
/**
* 得到批量卡券
*/
const WECHAT_GET_BATCH_CARD_URL = '/card/batchget?';
/**
* 得到卡券CODE
*/
const WECHAT_GET_CARD_CODE_URL = '/card/code/get?';
/**
* 更新卡券信息
*/
const WECHAT_UPDATE_CARD_URL = '/card/update?';
/**
* 更新库存
*/
const WECHAT_MODIFY_CARD_STOCK = '/card/modifystock?';
/**
* 卡券CODE解码
*/
const WECHAT_CARD_CODE_DECRYPT_URL = '/card/code/decrypt?';
/**
* 更新卡券CODE
*/
const WECHAT_CARD_CODE_UPDATE_URL = '/card/code/update?';
/**
* 设置卡券失效
*/
const WECHAT_SET_CARD_CODE_UNAVAILABLE_URL = '/card/code/unavailable?';
/**
* 激活/绑定会员卡
*/
const WECHAT_MEMBERCARD_ACTIVATE_URL = '/card/membercard/activate?';
/**
* 更新会员信息
*/
const WECHAT_MEMBERCARD_UPDATEUSER_URL = '/card/membercard/updateuser?';
/**
* 图片文件上传(不同于媒体图片该接口用于上传门店LOGO)
* T_T不知道微信的程序员怎么想要单独给logo开个图片上传
*/
const WECHAT_MEDIA_IMG_UPLOAD_URL = '/cgi-bin/media/uploadimg?';
/**
* 创建门店
*/
const WECHAT_ADD_POI_URL = '/cgi-bin/poi/addpoi?';
/**
* 查询单个门店
*/
const WECHAT_GET_POI_URL = '/cgi-bin/poi/getpoi?';
/**
* 查询门店列表
*/
const WECHAT_GET_POI_LIST_URL = '/cgi-bin/poi/getpoilist?';
/**
* 删除门店
*/
const WECHAT_DEL_POI_URL = '/cgi-bin/poi/delpoi?';
/**
* 更新门店信息
*/
const WECHAT_UPDATE_POI_URL = '/cgi-bin/poi/updatepoi?';
/**
* @var string 公众号appId
*/
public $appId;
/**
* @var string 公众号appSecret
*/
public $appSecret;
/**
* @var string 公众号支付请求中用于加密的密钥 Key,可验证商户唯一身份,PaySignKey 对应于支付场景中的 appKey 值。
*/
public $paySignKey;
/**
* @var sting 财付通商户身份标识。
*/
public $partnerId;
/**
* @var string 财付通商户权限密钥 Key
*/
public $partnerKey;
/**
* @var string 公众号接口验证token,可由您来设定. 并填写在微信公众平台->开发者中心
*/
public $token;
/**
* 数据缓存前缀
* @var string
*/
public $cachePrefix = 'wechat_cache';
/**
* 数据缓存时长
* @var int
*/
public $cacheTime = 3600;
/**
* @var array 最后请求的错误信息
*/
public $lastErrorInfo;
/**
* 操作ID(会化状态)定义
* 可用于显示客服聊天记录的操作详情
* @var array
*/
public $operCode = [
'1000' => '创建未接入会话',
'1001' => '接入会话',
'1002' => '主动发起会话',
'1004' => '关闭会话',
'1005' => '抢接会话',
'2001' => '公众号收到消息',
'2002' => '客服发送消息',
'2003' => '客服收到消息',
];
/**
* 回调错误代码
* 可用于检索用户返回错误详情
* @var array
*/
public $errorCode = [
'-1' => '系统繁忙',
'0' => '请求成功',
'40001' => '获取access_token时AppSecret错误,或者access_token无效',
'40002' => '不合法的凭证类型',
'40003' => '不合法的OpenID',
'40004' => '不合法的媒体文件类型',
'40005' => '不合法的文件类型',
'40006' => '不合法的文件大小',
'40007' => '不合法的媒体文件id',
'40008' => '不合法的消息类型',
'40009' => '不合法的图片文件大小',
'40010' => '不合法的语音文件大小',
'40011' => '不合法的视频文件大小',
'40012' => '不合法的缩略图文件大小',
'40013' => '不合法的APPID',
'40014' => '不合法的access_token',
'40015' => '不合法的菜单类型',
'40016' => '不合法的按钮个数',
'40017' => '不合法的按钮个数',
'40018' => '不合法的按钮名字长度',
'40019' => '不合法的按钮KEY长度',
'40020' => '不合法的按钮URL长度',
'40021' => '不合法的菜单版本号',
'40022' => '不合法的子菜单级数',
'40023' => '不合法的子菜单按钮个数',
'40024' => '不合法的子菜单按钮类型',
'40025' => '不合法的子菜单按钮名字长度',
'40026' => '不合法的子菜单按钮KEY长度',
'40027' => '不合法的子菜单按钮URL长度',
'40028' => '不合法的自定义菜单使用用户',
'40029' => '不合法的oauth_code',
'40030' => '不合法的refresh_token',
'40031' => '不合法的openid列表',
'40032' => '不合法的openid列表长度',
'40033' => '不合法的请求字符,不能包含\uxxxx格式的字符',
'40035' => '不合法的参数',
'40038' => '不合法的请求格式',
'40039' => '不合法的URL长度',
'40050' => '不合法的分组id',
'40051' => '分组名字不合法',
'41001' => '缺少access_token参数',
'41002' => '缺少appid参数',
'41003' => '缺少refresh_token参数',
'41004' => '缺少secret参数',
'41005' => '缺少多媒体文件数据',
'41006' => '缺少media_id参数',
'41007' => '缺少子菜单数据',
'41008' => '缺少oauth code',
'41009' => '缺少openid',
'42001' => 'access_token超时',
'42002' => 'refresh_token超时',
'42003' => 'oauth_code超时',
'43001' => '需要GET请求',
'43002' => '需要POST请求',
'43003' => '需要HTTPS请求',
'43004' => '需要接收者关注',
'43005' => '需要好友关系',
'44001' => '多媒体文件为空',
'44002' => 'POST的数据包为空',
'44003' => '图文消息内容为空',
'44004' => '文本消息内容为空',
'45001' => '多媒体文件大小超过限制',
'45002' => '消息内容超过限制',
'45003' => '标题字段超过限制',
'45004' => '描述字段超过限制',
'45005' => '链接字段超过限制',
'45006' => '图片链接字段超过限制',
'45007' => '语音播放时间超过限制',
'45008' => '图文消息超过限制',
'45009' => '接口调用超过限制',
'45010' => '创建菜单个数超过限制',
'45015' => '回复时间超过限制',
'45016' => '系统分组,不允许修改',
'45017' => '分组名字过长',
'45018' => '分组数量超过上限',
'46001' => '不存在媒体数据',
'46002' => '不存在的菜单版本',
'46003' => '不存在的菜单数据',
'46004' => '不存在的用户',
'47001' => '解析JSON/XML内容错误',
'48001' => 'api功能未授权',
'50001' => '用户未授权该api',
];
public function init()
{
if ($this->appId === null) {
throw new InvalidConfigException('The appId property must be set.');
} elseif ($this->appSecret === null) {
throw new InvalidConfigException('The appSecret property must be set.');
} elseif ($this->token === null) {
throw new InvalidConfigException('The token property must be set.');
}
}
/**
* 微信服务器请求签名检测
* @param string $signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
* @param string $timestamp 时间戳
* @param string $nonce 随机数
* @return bool
*/
public function checkSignature($signature = null, $timestamp = null, $nonce = null)
{
$request = Yii::$app->request;
$signature === null && $signature = $request->get('signature', '');
$timestamp === null && $timestamp = $request->get('timestamp', '');
$nonce === null && $nonce = $request->get('nonce', '');
$tmpArr = [$this->token, $timestamp, $nonce];
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
return sha1($tmpStr) == $signature;
}
/**
* 解析微信服务器请求的xml数据
* @param srting $xml 服务发送的xml数据
* @return array
*/
public function parseRequestData($xml = null)
{
$xml === null && $xml = Yii::$app->request->getRawBody();
return empty($xml) ? [] : (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
}
protected $_accessToken;
/**
* 设置AccessToken
* @param string @param array $data ['token' => 'token 字符串', 'expire' => 'token 超时时间']
*/
public function setAccessToken(array $data)
{
if (!isset($data['access_token'])) {
throw new InvalidParamException('The wechat access_token must be set.');
} elseif(!isset($data['expire'])) {
throw new InvalidParamException('Wechat access_token expire time must be set.');
}
$this->_accessToken = [
'token' => $data['access_token'],
'expire' => $data['expire']
];
}
/**
* 获取AccessToken
* 会自动判断超时时间然后重新获取新的token
* (会智能缓存accessToken)
* @param bool $force 是否强制获取
* @return string
* @throws \yii\base\Exception
*/
public function getAccessToken($force = false)
{
if ($this->_accessToken === null || $this->_accessToken['expire'] < YII_BEGIN_TIME || $force) {
$result = !$force && $this->_accessToken === null ? $this->getCache('access_token', false) : false;
if ($result === false) {
if (!($result = $this->requestAccessToken())) {
throw new HttpException(500, 'Fail to get access_token from wechat server.');
}
$this->trigger(self::EVENT_AFTER_ACCESS_TOKEN_UPDATE, new Event(['data' => $result]));
$this->setCache('access_token', $result, $result['expires_in']);
}
$this->setAccessToken($result);
}
return $this->_accessToken['token'];
}
/**
* 请求服务器access_token
* @param string $grantType
* @return array
*/
protected function requestAccessToken($grantType = 'client_credential')
{
$result = $this->httpGet(static::WECHAT_ACCESS_TOKEN_URL, [
'appid' => $this->appId,
'secret' => $this->appSecret,
'grant_type' => 'client_credential'
]);
if (isset($result['access_token'])) {
$result['expire'] = $result['expires_in'] + (int)YII_BEGIN_TIME;
return $result;
}
return false;
}
protected $_jsApiTicket;
/**
* 设置jsapi_ticket
* @param string @param array $data ['ticket' => 'ticket 字符串', 'expire' => 'ticket 超时时间']
*/
public function setJsApiTicket(array $data)
{
if (!isset($data['ticket'])) {
throw new InvalidParamException('The wechat js api ticket must be set.');
} elseif(!isset($data['expire'])) {
throw new InvalidParamException('Wechat jsapi_ticket expire time must be set.');
}
$this->_jsApiTicket = [
'ticket' => $data['ticket'],
'expire' => $data['expire']
];
}
/**
* 获取jsapi_ticket
* 会自动判断超时时间然后重新获取新的ticket
* (会智能缓存jsApiTicket)
* @param bool $force
* @return mixed
* @throws HttpException
*/
public function getJsApiTicket($force = false)
{
if ($this->_jsApiTicket === null || $this->_jsApiTicket['expire'] < YII_BEGIN_TIME || $force) {
$result = !$force && $this->_jsApiTicket === null ? $this->getCache('js_api_ticket', false) : false;
if ($result === false) {
if (!($result = $this->requestJsApiTicket())) {
throw new HttpException(500, 'Fail to get jsapi_ticket from wechat server.');
}
$this->trigger(self::EVENT_AFTER_JS_API_TICKET_UPDATE, new Event(['data' => $result]));
$this->setCache('js_api_ticket', $result, $result['expires_in']);
}
$this->setJsApiTicket($result);
}
return $this->_jsApiTicket['ticket'];
}
/**
* 请求服务器jsapi_ticket
* @param string $type
* @return array
*/
protected function requestJsApiTicket($type = 'jsapi')
{
$result = $this->httpGet(static::WECHAT_JS_API_TICKET_URL, [
'access_token' => $this->getAccessToken(),
'type' => $type
]);
if (isset($result['ticket'])) {
$result['expire'] = $result['expires_in'] + (int)YII_BEGIN_TIME;
return $result;
}
return false;
}
/**
* 生成js 必要的config
* 只需在视图文件输出JS代码:
* wx.config(<?= json_encode($wehcat->jsApiConfig()) ?>); // 默认全权限
* wx.config(<?= json_encode($wehcat->jsApiConfig([ // 只允许使用分享到朋友圈功能
* 'jsApiList' => [
* 'onMenuShareTimeline'
* ]
* ])) ?>);
* @param array $config
* @param bool $debug
* @return array
* @throws HttpException
*/
public function jsApiConfig(array $config = [], $debug = YII_DEBUG)
{
$data = [
'jsapi_ticket' => $this->getJsApiTicket(),
'noncestr' => Yii::$app->getSecurity()->generateRandomString(16),
'timestamp' => (int)YII_BEGIN_TIME,
'url' => explode('#', Yii::$app->getRequest()->getAbsoluteUrl())[0]
];
return array_merge([
'debug' => $debug,
'appId' => $this->appId,
'timestamp' => $data['timestamp'],
'nonceStr' => $data['noncestr'],
'signature' => sha1(urldecode(http_build_query($data))),
'jsApiList' => [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
]
], $config);
}
/**
* 创建菜单
* @param array $buttons 菜单结构字符串
* ~~~
* $this->createMenu([
* [
* 'type' => 'click',
* 'name' => '今日歌曲',
* 'key' => 'V1001_TODAY_MUSIC'
* ],
* [
* 'type' => 'view',
* 'name' => '搜索',
* 'url' => 'http://www.soso.com'
* ]
* ...
* ]);
* ~~~
* @return bool
*/
public function createMenu(array $buttons)
{
$result = $this->httpRaw(self::WECHAT_MENU_CREATE_URL . 'access_token=' . $this->getAccessToken(), [
'button' => $buttons
]);
return isset($result['errmsg']) && $result['errmsg'] == 'ok';
}
/**
* 获取菜单列表
* @return bool
*/
public function getMenuList()
{
$result = $this->httpRaw(self::WECHAT_MENU_GET_URL . 'access_token=' . $this->getAccessToken());
return isset($result['menu']['button']) ? $result['menu']['button'] : false;
}
/**
* 删除菜单
* @return bool
*/
public function deleteMenu()
{
$result = $this->httpGet(self::WECHAT_MENU_DELETE_URL . 'access_token=' . $this->getAccessToken());
return isset($result['errmsg']) && $result['errmsg'] == 'ok';
}
/**
* 发送模板消息给关注者
* 示例数据
* [
* "touser" => "接收消息的用户openid",
* "template_id" => "模板id",
* "url" => "http://weixin.qq.com/download",
* "topcolor" => "#FF0000",
* "data" => [
* "first" => [
* "value" => "恭喜你购买成功!",
* "color" => "#173177"
* ],
* "product" => [
* "value" => "巧克力",
* "color" => "#173177"
* ],
* "price" => [
* "value" => "39.8元",
* "color" => "#173177"
* ],
* "time" => [
* "value" => "2014年9月16日",
* "color" => "#173177"
* ],
* "remark" => [
* "value" => "欢迎再次购买!",
* "color" => "#173177"
* ]
* ]
*
* ]
* @param $toUser 关注者openID
* @param $templateId 模板ID(模板需在公众平台模板消息中挑选)
* @param array $data 模板需要的数据
* @return int|bool
*/
public function sendTemplateMessage($toUser, $templateId, array $data)
{
if (empty($data)) {
return false;
}
$requestParams = [
'touser' => $toUser,
'template_id' => $templateId,
'url' => null,
'topcolor' => '#FF0000',
'data' => $data
];
$result = $this->httpRaw(self::WECHAT_TEMPLATE_MESSAGE_SEND_URL . 'access_token=' . $this->getAccessToken(), $requestParams);
return isset($result['errmsg']) && $result['errmsg'] == 'ok' ? $result['msgid'] : false;
}
/**
* 发送文本客服信息
* @param $openId 关注者openID
* @param $content 文本消息内容
* @return bool
*/
public function sendText($openId, $content)
{
return $this->sendCustomMessage([
'touser' => $openId,
'msgtype' => 'text',
'text' => [
'content' => $content
]
]);
}
/**
* 发送图片客服消息
* @param string $openId 关注者openID
* @param string $mediaId 发送的图片的媒体ID
* @return bool
*/
public function sendImage($openId, $mediaId)
{
return $this->sendCustomMessage([
'touser' => $openId,
'msgtype' => 'image',
'voice' => [
'media_id' => $mediaId
]
]);
}
/**
* 发送声音客服消息
* @param string $openId 关注者openID
* @param string $mediaId 发送的语音的媒体ID
* @return bool
*/
public function sendVoice($openId, $mediaId)
{
return $this->sendCustomMessage([
'touser' => $openId,
'msgtype' => 'voice',
'voice' => [
'media_id' => $mediaId
]
]);
}
/**
* 发送视频客服信息
* @param string $openId 关注者openID
* @param string $mediaId 发送的视频的媒体ID
* @param string $thumbMediaId 缩略图的媒体ID
* @param string $title 视频消息的标题
* @param string $description 视频消息的描述
* @return bool
*/
public function sendVideo($openId, $mediaId, $thumbMediaId, $title = null, $description = null)
{
return $this->sendCustomMessage([
'touser' => $openId,
'msgtype' => 'video',
'video' => [
'media_id' => $mediaId,
'thumb_media_id' => $thumbMediaId,
'title' => $title,
'description' => $description
]
]);
}
/**
* 发送音乐客服消息
* @param $openId 关注者openID
* @param $thumbMediaId 缩略图的媒体ID
* @param $musicUrl 音乐链接
* @param $hqMusicUrl 高品质音乐链接,wifi环境优先使用该链接播放音乐
* @param null $title 音乐标题
* @param null $description 音乐描述
* @return bool
*/
public function sendMusic($openId, $thumbMediaId, $musicUrl, $hqMusicUrl, $title = null, $description = null)
{
return $this->sendCustomMessage([
'touser' => $openId,
'msgtype' => 'music',
'music' => [
'thumb_media_id' => $thumbMediaId,
'musicurl' => $musicUrl,
'hqMusicUrl' => $hqMusicUrl,
'title' => $title,
'description' => $description
]
]);
}
/**
* 发送图文客服消息
* @param $openId 关注者openID
* @param array $articles 图文信息内容部分
* ~~~
* $articles = [
* 'title' => 'Happy Day',
* 'description' => 'Is Really A Happy Day',
* 'url' => 'URL',
* 'picurl' => 'PIC_URL'
* ]
* ~~~
* @return bool
*/
public function sendNews($openId, array $articles)
{
return $this->sendCustomMessage([
'touser' => $openId,
'msgtype' => 'news',
'news' => [
'articles' => $articles
]
]);
}
/**
* 发送客服消息
* @param array $data
* @return bool
*/
protected function sendCustomMessage(array $data)
{
$result = $this->httpRaw(self::WECHAT_CUSTOM_MESSAGE_SEND_URL . 'access_token=' . $this->getAccessToken(), $data);
return isset($result['errmsg']) && $result['errmsg'] == 'ok';
}
/**
* 图文消息上传(高级群发接口)
* @param array $articles
* ~~~
* $articles = [
* [
* 'thumb_media_id' => 'qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p',
* 'author' => 'xxx',
* 'title' => 'Happy Day',
* 'content_source_url' => 'www.qq.com',
* 'content' => 'content',
* 'digest' => 'digest',
* 'show_cover_pic' => '1'
* ]
* ...
* ];
*
* ~~~
* @return array|bool
*/
public function uploadArticles(array $articles)
{