forked from thenbsp/wechat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreate.php
More file actions
88 lines (72 loc) · 1.88 KB
/
Copy pathCreate.php
File metadata and controls
88 lines (72 loc) · 1.88 KB
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
<?php
namespace Thenbsp\Wechat\Menu;
use Thenbsp\Wechat\Bridge\Http;
use Thenbsp\Wechat\Wechat\AccessToken;
class Create
{
/**
* 接口地址
*/
const CREATE_URL = 'https://api.weixin.qq.com/cgi-bin/menu/create';
/**
* 一级菜单不能超过 3 个
*/
const MAX_COUNT = 3;
/**
* Thenbsp\Wechat\Wechat\AccessToken
*/
protected $accessToken;
/**
* 按钮集合
*/
protected $buttons = array();
/**
* 构造方法
*/
public function __construct(AccessToken $accessToken)
{
$this->accessToken = $accessToken;
}
/**
* 添加按钮
*/
public function add(ButtonInterface $button)
{
if( $button instanceof ButtonCollectionInterface ) {
if( !$button->getChild() ) {
throw new \InvalidArgumentException('一级菜单不能为空');
}
}
if( count($this->buttons) > (static::MAX_COUNT - 1) ) {
throw new \InvalidArgumentException(sprintf(
'一级菜单不能超过 %d 个', static::MAX_COUNT
));
}
$this->buttons[] = $button;
}
/**
* 发布菜单
*/
public function doCreate()
{
$response = Http::request('POST', static::CREATE_URL)
->withAccessToken($this->accessToken)
->withBody($this->getRequestBody())
->send();
if( $response['errcode'] != 0 ) {
throw new \Exception($response['errmsg'], $response['errcode']);
}
return true;
}
/**
* 获取数据
*/
public function getRequestBody()
{
$data = array();
foreach( $this->buttons AS $k=>$v ) {
$data['button'][$k] = $v->getData();
}
return $data;
}
}