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
PHTML

2 years ago
<?php
declare(strict_types=1);
namespace App\Service;
1 year ago
use App\Exception\BusinessException;
use App\Helper\Platform\Signer;
2 years ago
use App\Helper\Redis;
use App\Helper\RedisKey;
use App\Helper\StringHelper;
use App\Model\App;
use App\Model\Merchant;
class AppService extends AbstractService
{
1 year ago
public function createApp(Merchant $merchant, string $appName)
{
2 years ago
$app = new App();
$app->merchant_id = $merchant->id;
$app->app_id = $this->generateAppId();
$app->app_key = StringHelper::getRandomString(32);
1 year ago
$app->app_name = $appName;
2 years ago
$app->status = App::STATUS_ACTIVE;
$app->save();
return $app;
}
1 year ago
private function generateAppId()
{
2 years ago
$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;
}
1 year ago
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;
}
2 years ago
}