51 lines
2.4 KiB
PHP
51 lines
2.4 KiB
PHP
<?php
|
||
|
||
namespace App\Support\CourierBills;
|
||
|
||
use DateTimeInterface;
|
||
use Illuminate\Support\Facades\Crypt;
|
||
use Illuminate\Support\Facades\URL;
|
||
use Throwable;
|
||
/**
|
||
* 快递账单确认链接。factory_id 保留共享令牌结构,表示对账单 ID;
|
||
* 公司、对账单、账期和推送版本均被加密签名约束,不沿用联合上传链接的范围。
|
||
*/
|
||
final class CourierFreightLink
|
||
{
|
||
public const TTL_DAYS = 30;
|
||
public function pageUrl(int $companyId, int $factoryId, string $month, int $version): string
|
||
{
|
||
return $this->signedRoute('signed.courier-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
|
||
}
|
||
|
||
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null, array $query = []): string
|
||
{
|
||
$url = URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
|
||
return $query === [] ? $url : $url . '&' . http_build_query($query);
|
||
}
|
||
/** @return array{factory_id:int,month:string,version:int}|null */
|
||
public function resolveToken(string $token, int $companyId): ?array
|
||
{
|
||
try {
|
||
$padding = (4 - strlen($token) % 4) % 4;
|
||
$encrypted = base64_decode(strtr($token . str_repeat('=', $padding), '-_', '+/'), true);
|
||
if ($encrypted === false) {
|
||
return null;
|
||
}
|
||
$payload = json_decode(Crypt::decryptString($encrypted), true, flags: JSON_THROW_ON_ERROR);
|
||
} catch (Throwable) {
|
||
return null;
|
||
}
|
||
if (!is_array($payload) || (int) ($payload['company_id'] ?? 0) !== $companyId || (int) ($payload['factory_id'] ?? 0) <= 0 || preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1 || (int) ($payload['version'] ?? 0) <= 0) {
|
||
return null;
|
||
}
|
||
return ['factory_id' => (int) $payload['factory_id'], 'month' => (string) $payload['month'], 'version' => (int) $payload['version']];
|
||
}
|
||
|
||
private function token(int $companyId, int $factoryId, string $month, int $version): string
|
||
{
|
||
$payload = json_encode(['company_id' => $companyId, 'factory_id' => $factoryId, 'month' => $month, 'version' => $version], JSON_THROW_ON_ERROR);
|
||
return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '=');
|
||
}
|
||
}
|