YonyouBipClient.php
11.7 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
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
<?php
namespace app\admin\library;
use GuzzleHttp\Client;
use think\Exception;
use think\Log;
/**
* 用友BIP API客户端
* 用于与用友BIP云平台进行数据交互
*/
class YonyouBipClient
{
/**
* API基础URL
* @var string
*/
private $baseUrl;
/**
* 应用Key
* @var string
*/
private $appKey;
/**
* 应用Secret
* @var string
*/
private $appSecret;
/**
* 租户ID
* @var string
*/
private $tenantId;
/**
* 访问令牌
* @var string
*/
private $accessToken;
/**
* HTTP客户端
* @var Client
*/
private $httpClient;
/**
* 构造函数
* @param array $config 配置信息
*/
public function __construct($config = [])
{
// 从配置中获取参数,如果没有则使用默认值或从数据库读取
$this->baseUrl = $config['base_url'] ?? config('yonyou_bip.base_url', 'https://api.yonyoucloud.com');
$this->appKey = $config['app_key'] ?? config('yonyou_bip.app_key', '');
$this->appSecret = $config['app_secret'] ?? config('yonyou_bip.app_secret', '');
$this->tenantId = $config['tenant_id'] ?? config('yonyou_bip.tenant_id', '');
$this->httpClient = new Client([
'timeout' => 30,
'verify' => false, // 根据实际情况设置SSL验证
]);
}
/**
* 获取访问令牌
* 使用OAuth2.0客户端凭证模式获取访问令牌
* @return string
* @throws Exception
*/
public function getAccessToken()
{
// 如果已有有效Token,直接返回(实际应用中可以添加Token过期检查)
if ($this->accessToken) {
return $this->accessToken;
}
// 验证必需参数
if (empty($this->appKey) || empty($this->appSecret)) {
throw new Exception('AppKey或AppSecret未配置,请在配置文件中设置');
}
try {
// 用友BIP OAuth2.0 Token获取端点
$url = rtrim($this->baseUrl, '/') . '/oauth/token';
$response = $this->httpClient->post($url, [
'form_params' => [
'grant_type' => 'client_credentials',
'client_id' => $this->appKey,
'client_secret' => $this->appSecret,
],
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]);
$result = json_decode($response->getBody()->getContents(), true);
// 根据用友BIP实际返回格式处理
// 可能的返回格式:
// 1. {"access_token": "xxx", "token_type": "Bearer", "expires_in": 7200}
// 2. {"code": 200, "data": {"access_token": "xxx", ...}}
if (isset($result['access_token'])) {
$this->accessToken = $result['access_token'];
Log::info('用友BIP Token获取成功');
return $this->accessToken;
} elseif (isset($result['data']['access_token'])) {
// 如果返回格式是嵌套的
$this->accessToken = $result['data']['access_token'];
Log::info('用友BIP Token获取成功');
return $this->accessToken;
} else {
$errorMsg = isset($result['message']) ? $result['message'] : json_encode($result);
Log::error('用友BIP获取Token失败: ' . $errorMsg);
throw new Exception('获取访问令牌失败: ' . $errorMsg);
}
} catch (\GuzzleHttp\Exception\RequestException $e) {
$errorMsg = '网络请求失败';
if ($e->hasResponse()) {
$response = $e->getResponse();
$errorMsg = $response->getBody()->getContents();
}
Log::error('用友BIP获取Token网络错误: ' . $e->getMessage() . ' | ' . $errorMsg);
throw new Exception('获取访问令牌失败: ' . $errorMsg);
} catch (\Exception $e) {
Log::error('用友BIP获取Token失败: ' . $e->getMessage());
throw new Exception('获取访问令牌失败: ' . $e->getMessage());
}
}
/**
* 发送API请求
* @param string $method HTTP方法
* @param string $endpoint API端点
* @param array $data 请求数据
* @return array
* @throws Exception
*/
public function request($method, $endpoint, $data = [])
{
// 获取访问令牌
$token = $this->getAccessToken();
// 构建完整URL
$url = rtrim($this->baseUrl, '/') . '/' . ltrim($endpoint, '/');
// 构建请求头
$headers = [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
];
// 添加租户ID(如果用友BIP需要)
if (!empty($this->tenantId)) {
$headers['tenant-id'] = $this->tenantId;
}
$options = [
'headers' => $headers,
];
// GET请求使用query参数,其他请求使用JSON body
if (strtoupper($method) === 'GET') {
$options['query'] = $data;
} else {
$options['json'] = $data;
}
try {
$response = $this->httpClient->request($method, $url, $options);
$statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
$result = json_decode($body, true);
// 记录请求日志
Log::info('用友BIP API请求', [
'method' => $method,
'url' => $url,
'status' => $statusCode,
]);
// 判断请求是否成功
if ($statusCode >= 200 && $statusCode < 300) {
// 根据用友BIP实际返回格式处理
// 可能的格式:
// 1. {"code": 200, "message": "成功", "data": {...}}
// 2. 直接返回数据
if (isset($result['code'])) {
if ($result['code'] == 200 || $result['code'] == 0) {
return $result;
} else {
$errorMsg = isset($result['message']) ? $result['message'] : json_encode($result);
throw new Exception('API返回错误: ' . $errorMsg);
}
} else {
return $result;
}
} else {
$errorMsg = isset($result['message']) ? $result['message'] : $body;
throw new Exception('API请求失败 (HTTP ' . $statusCode . '): ' . $errorMsg);
}
} catch (\GuzzleHttp\Exception\RequestException $e) {
$errorMsg = '网络请求失败';
if ($e->hasResponse()) {
$response = $e->getResponse();
$errorMsg = $response->getBody()->getContents();
}
Log::error('用友BIP API请求网络错误', [
'method' => $method,
'url' => $url,
'error' => $e->getMessage(),
'response' => $errorMsg,
]);
throw new Exception('API请求失败: ' . $errorMsg);
} catch (\Exception $e) {
Log::error('用友BIP API请求失败', [
'method' => $method,
'url' => $url,
'error' => $e->getMessage(),
]);
throw new Exception('API请求失败: ' . $e->getMessage());
}
}
/**
* 创建销售订单
* @param array $orderData 订单数据
* @return array
* @throws Exception
*/
public function createSalesOrder($orderData)
{
// 用友BIP销售订单创建接口
// 根据实际API文档调整端点路径
return $this->request('POST', '/api/sales/order/create', $orderData);
}
/**
* 更新销售订单
* @param string $orderId 订单ID
* @param array $orderData 订单数据
* @return array
* @throws Exception
*/
public function updateSalesOrder($orderId, $orderData)
{
return $this->request('PUT', '/api/sales/order/update/' . $orderId, $orderData);
}
/**
* 创建销售订单发货单
* @param array $deliveryData 发货数据
* @return array
* @throws Exception
*/
public function createSalesDelivery($deliveryData)
{
// 用友BIP销售订单发货接口
// 根据实际API文档调整端点路径
return $this->request('POST', '/api/sales/delivery/create', $deliveryData);
}
/**
* 查询销售订单
* @param array $params 查询参数
* @return array
* @throws Exception
*/
public function getSalesOrder($params = [])
{
return $this->request('GET', '/api/sales/order/list', $params);
}
/**
* 查询销售订单详情
* @param string $orderId 订单ID
* @return array
* @throws Exception
*/
public function getSalesOrderDetail($orderId)
{
return $this->request('GET', '/api/sales/order/detail/' . $orderId);
}
/**
* 获取销售组织列表
* @param array $params 查询参数
* @return array
* @throws Exception
*/
public function getSalesOrganizations($params = [])
{
// 根据实际API文档调整端点路径
return $this->request('GET', '/api/base/sales/organization/list', $params);
}
/**
* 获取交易类型列表
* @param array $params 查询参数
* @return array
* @throws Exception
*/
public function getTransactionTypes($params = [])
{
// 根据实际API文档调整端点路径
return $this->request('GET', '/api/base/transaction/type/list', $params);
}
/**
* 获取销售部门列表
* @param array $params 查询参数
* @return array
* @throws Exception
*/
public function getSalesDepartments($params = [])
{
// 根据实际API文档调整端点路径
return $this->request('GET', '/api/base/sales/department/list', $params);
}
/**
* 获取销售业务员列表
* @param array $params 查询参数
* @return array
* @throws Exception
*/
public function getSalesPersons($params = [])
{
// 根据实际API文档调整端点路径
return $this->request('GET', '/api/base/sales/person/list', $params);
}
/**
* 获取客户列表(从用友BIP)
* @param array $params 查询参数
* @return array
* @throws Exception
*/
public function getCustomers($params = [])
{
// 根据实际API文档调整端点路径
return $this->request('GET', '/api/base/customer/list', $params);
}
/**
* 同步基础数据(批量获取并缓存)
* @param string $type 数据类型:organization-销售组织, transaction_type-交易类型, department-销售部门, person-销售业务员, customer-客户
* @return array
* @throws Exception
*/
public function syncBaseData($type)
{
$endpoints = [
'organization' => '/api/base/sales/organization/list',
'transaction_type' => '/api/base/transaction/type/list',
'department' => '/api/base/sales/department/list',
'person' => '/api/base/sales/person/list',
'customer' => '/api/base/customer/list',
];
if (!isset($endpoints[$type])) {
throw new Exception('不支持的数据类型: ' . $type);
}
return $this->request('GET', $endpoints[$type], []);
}
}