erp-backend/Modules/Ecommerce/Services/TaobaoService.php
2026-04-01 17:07:04 +08:00

86 lines
2.4 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\Ecommerce\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class TaobaoService
{
protected $appKey;
protected $appSecret;
protected $accessToken;
protected $gateway = 'https://eco.taobao.com/router/rest';
public function __construct($appKey, $appSecret, $accessToken)
{
$this->appKey = $appKey;
$this->appSecret = $appSecret;
$this->accessToken = $accessToken;
}
/**
* 拉取订单列表taobao.trades.sold.get
*
* @param string $startTime 起始时间格式Y-m-d H:i:s
* @param string $endTime 结束时间
* @return array
* @throws \Exception
*/
public function fetchOrders($startTime, $endTime)
{
$params = [
'method' => 'taobao.trades.sold.get',
'app_key' => $this->appKey,
'session' => $this->accessToken,
'timestamp' => date('Y-m-d H:i:s'),
'format' => 'json',
'v' => '2.0',
'sign_method' => 'hmac-sha256',
'fields' => 'tid,status,payment,receiver_name,receiver_city,receiver_district,receiver_address,orders',
'start_created' => $startTime,
'end_created' => $endTime,
];
$params['sign'] = $this->generateSign($params);
try {
$client = new Client();
$response = $client->post($this->gateway, [
'form_params' => $params,
'timeout' => 30,
]);
$result = json_decode($response->getBody(), true);
// 检查淘宝API返回的错误
if (isset($result['error_response'])) {
throw new \Exception('淘宝API错误: ' . $result['error_response']['msg']);
}
return $result;
} catch (\Exception $e) {
Log::error('淘宝订单拉取失败', ['error' => $e->getMessage()]);
throw $e;
}
}
/**
* 生成签名
*
* @param array $params
* @return string
*/
protected function generateSign($params)
{
ksort($params);
$stringToSign = $this->appSecret;
foreach ($params as $key => $value) {
if ($key != 'sign' && $value !== '') {
$stringToSign .= $key . $value;
}
}
$stringToSign .= $this->appSecret;
return strtoupper(hash_hmac('sha256', $stringToSign, $this->appSecret));
}
}