You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
payment/app/Service/AppService.php

74 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Service;
use App\Exception\BusinessException;
use App\Helper\Platform\Signer;
use App\Helper\Redis;
use App\Helper\RedisKey;
use App\Helper\StringHelper;
use App\Model\App;
use App\Model\Merchant;
class AppService extends AbstractService
{
public function createApp(Merchant $merchant, string $appName)
{
$app = new App();
$app->merchant_id = $merchant->id;
$app->app_id = $this->generateAppId();
$app->app_key = StringHelper::getRandomString(32);
$app->app_name = $appName;
$app->status = App::STATUS_ACTIVE;
$app->save();
return $app;
}
private function generateAppId()
{
$now = time();
$key = RedisKey::getGenerateAppIdKey($now);
$expireAt = strtotime(date('Y-m-d 23:59:59', $now)) + 1;
$incrId = Redis::incr($key);
$incrId = '' . $incrId;
Redis::expireAt($key, $expireAt);
$padLength = 8 - strlen($incrId);
$incrId = str_pad($incrId, $padLength, '0', STR_PAD_LEFT);
return date('Ymd', $now) . $incrId;
}
private function checkApp($appId): App
{
if (is_null($appId)) {
throw new BusinessException('[app_id]错误');
}
$app = App::query()->where('app_id', $appId)->first();
if (is_null($app)) {
throw new BusinessException('APP错误');
}
if ($app->status != 1) {
throw new BusinessException('应用暂未启用');
}
return $app;
}
public function checkSign($params): App
{
$appId = $params['app_id'] ?? null;
$app = $this->checkApp($appId);
if (!Signer::verify($params, $app->app_key)) {
throw new BusinessException('验签错误');
}
if ($params['timestamp'] < time() - 6000) {
throw new BusinessException('请求已过期');
}
return $app;
}
}