59 lines
2.3 KiB
PHP
59 lines
2.3 KiB
PHP
<?php
|
||
|
||
namespace App\Support\DropshipFreight;
|
||
|
||
use DateTimeInterface;
|
||
use Illuminate\Support\Facades\Crypt;
|
||
use Illuminate\Support\Facades\URL;
|
||
use Throwable;
|
||
|
||
/**
|
||
* 代发运费确认页的免登录链接(同供应商对账的货款确认页):
|
||
* 公司、厂家、月份、推送版本放进加密令牌,URL 再做 Laravel 签名,厂家只能看本厂家本次推送的账期。
|
||
*/
|
||
final class DropshipShareLink
|
||
{
|
||
public const TTL_DAYS = 30;
|
||
|
||
public function pageUrl(int $companyId, int $factoryId, string $month, int $version): string
|
||
{
|
||
return $this->signedRoute('signed.dropship-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
|
||
}
|
||
|
||
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null): string
|
||
{
|
||
return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), [
|
||
'company_id' => $companyId, 'token' => $token,
|
||
]);
|
||
}
|
||
|
||
/** @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)), '+/', '-_'), '=');
|
||
}
|
||
}
|