224 lines
7.8 KiB
PHP
224 lines
7.8 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Services;
|
|
|
|
use Carbon\CarbonImmutable;
|
|
use GuzzleHttp\Cookie\CookieJar;
|
|
use Illuminate\Http\Client\PendingRequest;
|
|
use Illuminate\Support\Facades\Http;
|
|
use JsonException;
|
|
use RuntimeException;
|
|
|
|
/**
|
|
* 读取聚水潭胜算“平台资金账户余额 → 拼多多货款账户”月报表。
|
|
*
|
|
* 使用固定账号在服务器内部直接登录,不依赖个人浏览器会话。账号密码只从
|
|
* 私有 runtime/.env 读取;日志和异常信息不会包含密码。
|
|
*/
|
|
class JushuitanPlatformBalanceClient
|
|
{
|
|
/**
|
|
* @return list<array<string,mixed>>
|
|
*/
|
|
public function fetchMonth(string $period): array
|
|
{
|
|
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
|
throw new RuntimeException('聚水潭平台资金账户余额月份格式必须是 YYYY-MM。');
|
|
}
|
|
|
|
$account = trim((string) config('services.jushuitan.erp_account', ''));
|
|
$password = (string) config('services.jushuitan.erp_password', '');
|
|
if ($account === '' || $password === '') {
|
|
throw new RuntimeException('jushuitan_erp_credentials_missing');
|
|
}
|
|
|
|
$cookies = new CookieJar();
|
|
$login = Http::acceptJson()
|
|
->asJson()
|
|
->withOptions(['cookies' => $cookies])
|
|
->withHeaders([
|
|
'Origin' => 'https://www.erp321.com',
|
|
'Referer' => 'https://www.erp321.com/login.aspx',
|
|
])
|
|
->timeout($this->timeout())
|
|
->post((string) config(
|
|
'services.jushuitan.erp_login_url',
|
|
'https://api.erp321.com/erp/webapi/UserApi/WebLogin/Passport',
|
|
), [
|
|
'data' => [
|
|
'account' => $account,
|
|
'password' => $password,
|
|
'isApp' => false,
|
|
],
|
|
]);
|
|
if ($login->failed() || (int) $login->json('code') !== 0) {
|
|
throw new RuntimeException('jushuitan_erp_login_failed');
|
|
}
|
|
|
|
$balanceUrl = (string) config(
|
|
'services.jushuitan.pdd_balance_url',
|
|
'https://pf.erp321.com/app/FMS/alipayfee/balance/balanceitem.aspx?pk=PinDuoDuoPlatform&gk=PinduoduoImport',
|
|
);
|
|
$page = Http::accept('text/html')
|
|
->withOptions(['cookies' => $cookies])
|
|
->withHeaders([
|
|
'Referer' => 'https://www.erp321.com/epaas',
|
|
])
|
|
->timeout($this->timeout())
|
|
->get($balanceUrl);
|
|
if ($page->failed()) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_page_http_' . $page->status());
|
|
}
|
|
|
|
$html = $page->body();
|
|
if (! str_contains($html, '平台资金账户余额')) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_page_invalid');
|
|
}
|
|
[$viewState, $viewStateGenerator] = $this->formState($html);
|
|
$monthStart = CarbonImmutable::createFromFormat('!Y-m-d', $period . '-01');
|
|
if (! $monthStart instanceof CarbonImmutable) {
|
|
throw new RuntimeException('聚水潭平台资金账户余额月份无效。');
|
|
}
|
|
|
|
$conditions = [
|
|
'platform' => '',
|
|
'group' => '',
|
|
'shop_id' => '',
|
|
'begin_time' => $monthStart->format('Y-m-d'),
|
|
'end_time' => $monthStart->endOfMonth()->format('Y-m-d'),
|
|
'balance_begin' => '',
|
|
'balance_end' => '',
|
|
'status' => '',
|
|
'index' => 1,
|
|
'limit' => 100,
|
|
];
|
|
$first = $this->loadPage(
|
|
$cookies,
|
|
$balanceUrl,
|
|
$viewState,
|
|
$viewStateGenerator,
|
|
$conditions,
|
|
);
|
|
$rows = $first['rows'];
|
|
$pageCount = min($first['page_count'], 100);
|
|
for ($index = 2; $index <= $pageCount; $index++) {
|
|
$conditions['index'] = $index;
|
|
$next = $this->loadPage(
|
|
$cookies,
|
|
$balanceUrl,
|
|
$viewState,
|
|
$viewStateGenerator,
|
|
$conditions,
|
|
);
|
|
array_push($rows, ...$next['rows']);
|
|
}
|
|
|
|
return $rows;
|
|
}
|
|
|
|
/**
|
|
* @return array{0:string,1:string}
|
|
*/
|
|
private function formState(string $html): array
|
|
{
|
|
$previous = libxml_use_internal_errors(true);
|
|
try {
|
|
$document = new \DOMDocument();
|
|
$document->loadHTML($html, LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR);
|
|
$xpath = new \DOMXPath($document);
|
|
$viewState = trim((string) $xpath->evaluate(
|
|
'string(//input[@id="__VIEWSTATE"]/@value)',
|
|
));
|
|
$generator = trim((string) $xpath->evaluate(
|
|
'string(//input[@id="__VIEWSTATEGENERATOR"]/@value)',
|
|
));
|
|
} finally {
|
|
libxml_clear_errors();
|
|
libxml_use_internal_errors($previous);
|
|
}
|
|
|
|
if ($viewState === '' || $generator === '') {
|
|
throw new RuntimeException('jushuitan_pdd_balance_form_state_missing');
|
|
}
|
|
|
|
return [$viewState, $generator];
|
|
}
|
|
|
|
/**
|
|
* @param array<string,mixed> $conditions
|
|
* @return array{rows:list<array<string,mixed>>,page_count:int}
|
|
*/
|
|
private function loadPage(
|
|
CookieJar $cookies,
|
|
string $balanceUrl,
|
|
string $viewState,
|
|
string $viewStateGenerator,
|
|
array $conditions,
|
|
): array {
|
|
$callback = json_encode([
|
|
'Method' => 'LoadData',
|
|
'Args' => [json_encode($conditions, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)],
|
|
'CallControl' => '{page}',
|
|
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
|
$response = $this->http($cookies)
|
|
->asForm()
|
|
->withHeaders([
|
|
'Referer' => $balanceUrl,
|
|
])
|
|
->post(
|
|
$balanceUrl . '&ts___=' . now()->getTimestampMs() . '&am___=LoadData',
|
|
[
|
|
'__VIEWSTATE' => $viewState,
|
|
'__VIEWSTATEGENERATOR' => $viewStateGenerator,
|
|
'__CALLBACKID' => 'ACall1',
|
|
'__CALLBACKPARAM' => $callback,
|
|
],
|
|
);
|
|
if ($response->failed()) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_load_http_' . $response->status());
|
|
}
|
|
|
|
$body = $response->body();
|
|
$separator = strpos($body, '|');
|
|
$json = $separator === false ? $body : substr($body, $separator + 1);
|
|
try {
|
|
$payload = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
|
|
} catch (JsonException) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_load_invalid_json');
|
|
}
|
|
if (! is_array($payload) || ($payload['IsSuccess'] ?? false) !== true) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_load_failed');
|
|
}
|
|
|
|
$result = $payload['ReturnValue'] ?? [];
|
|
if (! is_array($result)) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_result_invalid');
|
|
}
|
|
try {
|
|
$rows = json_decode((string) ($result['datalist'] ?? '[]'), true, 512, JSON_THROW_ON_ERROR);
|
|
} catch (JsonException) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_rows_invalid');
|
|
}
|
|
if (! is_array($rows)) {
|
|
throw new RuntimeException('jushuitan_pdd_balance_rows_invalid');
|
|
}
|
|
|
|
return [
|
|
'rows' => array_values(array_filter($rows, 'is_array')),
|
|
'page_count' => max(1, (int) ($result['paging']['PageCount'] ?? 1)),
|
|
];
|
|
}
|
|
|
|
private function http(CookieJar $cookies): PendingRequest
|
|
{
|
|
return Http::acceptJson()
|
|
->withOptions(['cookies' => $cookies])
|
|
->timeout($this->timeout());
|
|
}
|
|
|
|
private function timeout(): int
|
|
{
|
|
return max(5, min(60, (int) config('services.jushuitan.timeout', 20)));
|
|
}
|
|
}
|