YonyouBipClient.php 11.7 KB
<?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], []);
    }
}