parent
4d2e73552e
commit
eb3143ee84
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SmsVerification extends Model
|
||||
{
|
||||
public const SCENE_PARTICIPANT_LOGIN = 'participant_login';
|
||||
|
||||
public const PROVIDER_DISABLED = 'disabled';
|
||||
|
||||
public const PROVIDER_TENCENTCLOUD = 'tencentcloud';
|
||||
|
||||
public const STATUS_PENDING = 'pending';
|
||||
public const STATUS_SENT = 'sent';
|
||||
public const STATUS_FAILED = 'failed';
|
||||
public const STATUS_USED = 'used';
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
protected $fillable = [
|
||||
'scene',
|
||||
'mobile',
|
||||
'code',
|
||||
'provider',
|
||||
'status',
|
||||
'template_id',
|
||||
'sign_name',
|
||||
'request_payload_json',
|
||||
'response_json',
|
||||
'provider_request_id',
|
||||
'provider_code',
|
||||
'provider_message',
|
||||
'sent_at',
|
||||
'failed_at',
|
||||
'used_at',
|
||||
'expires_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'request_payload_json' => 'array',
|
||||
'response_json' => 'array',
|
||||
'sent_at' => 'datetime',
|
||||
'failed_at' => 'datetime',
|
||||
'used_at' => 'datetime',
|
||||
'expires_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
@ -1,81 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 与 wx.sstbc.com app/Http/functions.php 中 ymSms() 相同通道与签名规则。
|
||||
*/
|
||||
class BtomSmsService
|
||||
{
|
||||
public function sendContent(string $mobile, string $content): bool
|
||||
{
|
||||
$appId = (string) config('sms.app_id');
|
||||
$secret = (string) config('sms.secret');
|
||||
$url = (string) config('sms.gateway');
|
||||
|
||||
if ($appId === '' || $secret === '') {
|
||||
Log::warning('SMS skipped: SMS_APPID or SMS_SECRETKEY empty');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$timestamp = date('YmdHis');
|
||||
$params = [
|
||||
'appId' => $appId,
|
||||
'timestamp' => $timestamp,
|
||||
'mobiles' => $mobile,
|
||||
'content' => $content,
|
||||
];
|
||||
$params['sign'] = md5($appId.$secret.$timestamp);
|
||||
|
||||
Log::info('sms.gateway request', [
|
||||
'url' => $url,
|
||||
'mobile_mask' => strlen($mobile) >= 11
|
||||
? substr($mobile, 0, 3).'****'.substr($mobile, -4)
|
||||
: '***',
|
||||
'app_id_len' => strlen($appId),
|
||||
'timestamp' => $timestamp,
|
||||
]);
|
||||
|
||||
try {
|
||||
$response = Http::timeout((int) config('sms.timeout', 5))
|
||||
->withHeaders(['Content-Type' => 'application/json'])
|
||||
->get($url, $params);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('SMS request failed', ['exception' => $e->getMessage()]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$status = $response->status();
|
||||
$bodySnippet = substr($response->body(), 0, 500);
|
||||
Log::info('sms.gateway response', [
|
||||
'http_status' => $status,
|
||||
'body_preview' => $bodySnippet,
|
||||
]);
|
||||
|
||||
$return = $response->json();
|
||||
if (! is_array($return)) {
|
||||
Log::error('SMS invalid JSON', ['body' => $response->body()]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (($return['code'] ?? '') !== 'SUCCESS') {
|
||||
Log::warning('SMS gateway error', array_merge($return, ['http_status' => $status]));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Log::info('sms.gateway success', [
|
||||
'mobile_mask' => strlen($mobile) >= 11
|
||||
? substr($mobile, 0, 3).'****'.substr($mobile, -4)
|
||||
: '***',
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Models\SmsVerification;
|
||||
|
||||
class DisabledSmsSender implements SmsSender
|
||||
{
|
||||
public function sendVerification(SmsVerification $record): SmsSendResult
|
||||
{
|
||||
return SmsSendResult::success(
|
||||
SmsVerification::PROVIDER_DISABLED,
|
||||
null,
|
||||
'DISABLED_OK',
|
||||
'SMS_ENABLED=false; provider call skipped.',
|
||||
['disabled' => true]
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
class SmsSendResult
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed>|null $response
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly bool $success,
|
||||
public readonly string $provider,
|
||||
public readonly ?string $requestId = null,
|
||||
public readonly ?string $providerCode = null,
|
||||
public readonly ?string $providerMessage = null,
|
||||
public readonly ?array $response = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|null $response
|
||||
*/
|
||||
public static function success(
|
||||
string $provider,
|
||||
?string $requestId = null,
|
||||
?string $providerCode = null,
|
||||
?string $providerMessage = null,
|
||||
?array $response = null,
|
||||
): self {
|
||||
return new self(true, $provider, $requestId, $providerCode, $providerMessage, $response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|null $response
|
||||
*/
|
||||
public static function failure(
|
||||
string $provider,
|
||||
?string $requestId = null,
|
||||
?string $providerCode = null,
|
||||
?string $providerMessage = null,
|
||||
?array $response = null,
|
||||
): self {
|
||||
return new self(false, $provider, $requestId, $providerCode, $providerMessage, $response);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Models\SmsVerification;
|
||||
|
||||
interface SmsSender
|
||||
{
|
||||
public function sendVerification(SmsVerification $record): SmsSendResult;
|
||||
}
|
||||
@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Models\SmsVerification;
|
||||
use App\Support\SmsConfig;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class TencentCloudSmsSender implements SmsSender
|
||||
{
|
||||
private const ACTION = 'SendSms';
|
||||
private const VERSION = '2021-01-11';
|
||||
private const SERVICE = 'sms';
|
||||
private const ALGORITHM = 'TC3-HMAC-SHA256';
|
||||
|
||||
public function sendVerification(SmsVerification $record): SmsSendResult
|
||||
{
|
||||
try {
|
||||
SmsConfig::assertReadyForRealSending();
|
||||
} catch (\Throwable $e) {
|
||||
return SmsSendResult::failure(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
null,
|
||||
'CONFIG_INCOMPLETE',
|
||||
$e->getMessage(),
|
||||
['error' => 'config_incomplete']
|
||||
);
|
||||
}
|
||||
|
||||
$endpoint = (string) config('sms.tencentcloud.endpoint');
|
||||
$region = (string) config('sms.tencentcloud.region');
|
||||
$secretId = (string) config('sms.tencentcloud.secret_id');
|
||||
$secretKey = (string) config('sms.tencentcloud.secret_key');
|
||||
$timeout = (int) config('sms.timeout', 5);
|
||||
|
||||
$payload = [
|
||||
'PhoneNumberSet' => ['+86'.$record->mobile],
|
||||
'SmsSdkAppId' => (string) config('sms.tencentcloud.sdk_app_id'),
|
||||
'SignName' => (string) config('sms.tencentcloud.sign_name'),
|
||||
'TemplateId' => (string) config('sms.tencentcloud.template_id'),
|
||||
'TemplateParamSet' => [
|
||||
(string) $record->code,
|
||||
(string) data_get($record->request_payload_json, 'ttl_minutes', '5'),
|
||||
],
|
||||
];
|
||||
|
||||
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if ($body === false) {
|
||||
return SmsSendResult::failure(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
null,
|
||||
'PAYLOAD_ENCODE_FAILED',
|
||||
'Tencent Cloud SMS payload encode failed.',
|
||||
['error' => 'payload_encode_failed']
|
||||
);
|
||||
}
|
||||
|
||||
$timestamp = time();
|
||||
$headers = $this->buildHeaders($endpoint, $region, $secretId, $secretKey, $timestamp, $body);
|
||||
|
||||
try {
|
||||
$response = Http::timeout($timeout)
|
||||
->withHeaders($headers)
|
||||
->withBody($body, 'application/json; charset=utf-8')
|
||||
->post('https://'.$endpoint);
|
||||
} catch (\Throwable $e) {
|
||||
return SmsSendResult::failure(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
null,
|
||||
'NETWORK_ERROR',
|
||||
$e->getMessage(),
|
||||
['error' => 'network_error']
|
||||
);
|
||||
}
|
||||
|
||||
$json = $response->json();
|
||||
if (! is_array($json)) {
|
||||
return SmsSendResult::failure(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
null,
|
||||
'INVALID_RESPONSE',
|
||||
'Tencent Cloud SMS returned a non-json response.',
|
||||
['http_status' => $response->status()]
|
||||
);
|
||||
}
|
||||
|
||||
$tencentResponse = data_get($json, 'Response', []);
|
||||
$requestId = data_get($tencentResponse, 'RequestId');
|
||||
|
||||
if (data_get($tencentResponse, 'Error.Code')) {
|
||||
return SmsSendResult::failure(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
is_string($requestId) ? $requestId : null,
|
||||
(string) data_get($tencentResponse, 'Error.Code'),
|
||||
(string) data_get($tencentResponse, 'Error.Message'),
|
||||
$this->responseSummary($json)
|
||||
);
|
||||
}
|
||||
|
||||
$status = data_get($tencentResponse, 'SendStatusSet.0', []);
|
||||
$providerCode = (string) data_get($status, 'Code', '');
|
||||
$providerMessage = (string) data_get($status, 'Message', '');
|
||||
|
||||
if ($response->successful() && $providerCode === 'Ok') {
|
||||
return SmsSendResult::success(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
is_string($requestId) ? $requestId : null,
|
||||
$providerCode,
|
||||
$providerMessage,
|
||||
$this->responseSummary($json)
|
||||
);
|
||||
}
|
||||
|
||||
return SmsSendResult::failure(
|
||||
SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
is_string($requestId) ? $requestId : null,
|
||||
$providerCode !== '' ? $providerCode : 'HTTP_'.$response->status(),
|
||||
$providerMessage !== '' ? $providerMessage : 'Tencent Cloud SMS send failed.',
|
||||
$this->responseSummary($json)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function buildHeaders(
|
||||
string $host,
|
||||
string $region,
|
||||
string $secretId,
|
||||
string $secretKey,
|
||||
int $timestamp,
|
||||
string $payload,
|
||||
): array {
|
||||
$date = gmdate('Y-m-d', $timestamp);
|
||||
$canonicalHeaders = "content-type:application/json; charset=utf-8\nhost:{$host}\n";
|
||||
$signedHeaders = 'content-type;host';
|
||||
$canonicalRequest = implode("\n", [
|
||||
'POST',
|
||||
'/',
|
||||
'',
|
||||
$canonicalHeaders,
|
||||
$signedHeaders,
|
||||
hash('sha256', $payload),
|
||||
]);
|
||||
|
||||
$credentialScope = $date.'/'.self::SERVICE.'/tc3_request';
|
||||
$stringToSign = implode("\n", [
|
||||
self::ALGORITHM,
|
||||
(string) $timestamp,
|
||||
$credentialScope,
|
||||
hash('sha256', $canonicalRequest),
|
||||
]);
|
||||
|
||||
$secretDate = hash_hmac('sha256', $date, 'TC3'.$secretKey, true);
|
||||
$secretService = hash_hmac('sha256', self::SERVICE, $secretDate, true);
|
||||
$secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true);
|
||||
$signature = hash_hmac('sha256', $stringToSign, $secretSigning);
|
||||
|
||||
$authorization = self::ALGORITHM
|
||||
.' Credential='.$secretId.'/'.$credentialScope
|
||||
.', SignedHeaders='.$signedHeaders
|
||||
.', Signature='.$signature;
|
||||
|
||||
return [
|
||||
'Authorization' => $authorization,
|
||||
'Content-Type' => 'application/json; charset=utf-8',
|
||||
'Host' => $host,
|
||||
'X-TC-Action' => self::ACTION,
|
||||
'X-TC-Region' => $region,
|
||||
'X-TC-Timestamp' => (string) $timestamp,
|
||||
'X-TC-Version' => self::VERSION,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $response
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function responseSummary(array $response): array
|
||||
{
|
||||
return [
|
||||
'request_id' => data_get($response, 'Response.RequestId'),
|
||||
'error' => data_get($response, 'Response.Error'),
|
||||
'send_status_set' => data_get($response, 'Response.SendStatusSet'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class SmsConfig
|
||||
{
|
||||
/**
|
||||
* Tencent Cloud SendSms uses Cloud API 3.0 authentication. SmsSdkAppId is
|
||||
* a business parameter, not an API credential.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function realSendingRequiredEnv(): array
|
||||
{
|
||||
return [
|
||||
'sms.tencentcloud.endpoint' => 'TENCENT_SMS_ENDPOINT',
|
||||
'sms.tencentcloud.region' => 'TENCENT_SMS_REGION',
|
||||
'sms.tencentcloud.secret_id' => 'TENCENTCLOUD_SECRET_ID',
|
||||
'sms.tencentcloud.secret_key' => 'TENCENTCLOUD_SECRET_KEY',
|
||||
'sms.tencentcloud.sdk_app_id' => 'TENCENT_SMS_SDK_APP_ID',
|
||||
'sms.tencentcloud.sign_name' => 'TENCENT_SMS_SIGN_NAME',
|
||||
'sms.tencentcloud.template_id' => 'TENCENT_SMS_TEMPLATE_ID',
|
||||
];
|
||||
}
|
||||
|
||||
public static function assertReadyForRealSending(): void
|
||||
{
|
||||
if (! (bool) config('sms.enabled')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((string) config('sms.driver') !== 'tencentcloud') {
|
||||
throw new RuntimeException('SMS_ENABLED=true requires SMS_DRIVER=tencentcloud.');
|
||||
}
|
||||
|
||||
$missing = [];
|
||||
foreach (self::realSendingRequiredEnv() as $configKey => $envName) {
|
||||
$value = config($configKey);
|
||||
if ($value === null || trim((string) $value) === '') {
|
||||
$missing[] = $envName;
|
||||
}
|
||||
}
|
||||
|
||||
if ((int) config('sms.tencentcloud.template_param_count') !== 2) {
|
||||
$missing[] = 'TENCENT_SMS_TEMPLATE_PARAM_COUNT must be 2';
|
||||
}
|
||||
|
||||
if ($missing !== []) {
|
||||
throw new RuntimeException(
|
||||
'SMS_ENABLED=true but Tencent Cloud SMS configuration is incomplete. '
|
||||
.'SendSms uses Cloud API 3.0 and requires CAM credentials. Missing or invalid: '
|
||||
.implode(', ', $missing)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('sms_verifications', function (Blueprint $table) {
|
||||
$table->string('scene', 64)->default('participant_login')->after('id');
|
||||
$table->string('provider', 32)->default('disabled')->after('code');
|
||||
$table->string('status', 16)->default('pending')->after('provider');
|
||||
$table->string('template_id', 64)->nullable()->after('status');
|
||||
$table->string('sign_name', 64)->nullable()->after('template_id');
|
||||
$table->json('request_payload_json')->nullable()->after('sign_name');
|
||||
$table->json('response_json')->nullable()->after('request_payload_json');
|
||||
$table->string('provider_request_id', 128)->nullable()->after('response_json');
|
||||
$table->string('provider_code', 128)->nullable()->after('provider_request_id');
|
||||
$table->string('provider_message', 500)->nullable()->after('provider_code');
|
||||
$table->timestamp('sent_at')->nullable()->after('expires_at');
|
||||
$table->timestamp('failed_at')->nullable()->after('sent_at');
|
||||
$table->timestamp('used_at')->nullable()->after('failed_at');
|
||||
|
||||
$table->index(['scene', 'mobile', 'created_at'], 'sms_verifications_scene_mobile_created_idx');
|
||||
$table->index(['scene', 'mobile', 'status', 'expires_at'], 'sms_verifications_scene_mobile_status_expires_idx');
|
||||
$table->index(['provider', 'provider_code', 'created_at'], 'sms_verifications_provider_code_created_idx');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('sms_verifications', function (Blueprint $table) {
|
||||
$table->dropIndex('sms_verifications_scene_mobile_created_idx');
|
||||
$table->dropIndex('sms_verifications_scene_mobile_status_expires_idx');
|
||||
$table->dropIndex('sms_verifications_provider_code_created_idx');
|
||||
|
||||
$table->dropColumn([
|
||||
'scene',
|
||||
'provider',
|
||||
'status',
|
||||
'template_id',
|
||||
'sign_name',
|
||||
'request_payload_json',
|
||||
'response_json',
|
||||
'provider_request_id',
|
||||
'provider_code',
|
||||
'provider_message',
|
||||
'sent_at',
|
||||
'failed_at',
|
||||
'used_at',
|
||||
]);
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,380 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Competition;
|
||||
use App\Models\SmsVerification;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Http\Client\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AuthSmsControllerTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config([
|
||||
'app.url' => 'http://localhost',
|
||||
'cache.default' => 'array',
|
||||
'database.default' => 'sqlite',
|
||||
'database.connections.sqlite' => [
|
||||
'driver' => 'sqlite',
|
||||
'database' => ':memory:',
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => false,
|
||||
],
|
||||
'sms.driver' => 'tencentcloud',
|
||||
'sms.enabled' => false,
|
||||
'sms.resend_interval_seconds' => 60,
|
||||
'sms.code_ttl_seconds' => 300,
|
||||
'sms.tencentcloud.endpoint' => 'sms.tencentcloudapi.com',
|
||||
'sms.tencentcloud.region' => 'ap-guangzhou',
|
||||
'sms.tencentcloud.secret_id' => null,
|
||||
'sms.tencentcloud.secret_key' => null,
|
||||
'sms.tencentcloud.sdk_app_id' => null,
|
||||
'sms.tencentcloud.sign_name' => '元禾控股',
|
||||
'sms.tencentcloud.template_id' => '2175650',
|
||||
'sms.tencentcloud.template_param_count' => 2,
|
||||
]);
|
||||
|
||||
DB::purge();
|
||||
DB::reconnect();
|
||||
Cache::flush();
|
||||
|
||||
$this->createSchema();
|
||||
}
|
||||
|
||||
public function test_disabled_sender_creates_record_and_login_consumes_it(): void
|
||||
{
|
||||
$this->competition('main-event');
|
||||
|
||||
$send = $this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138000',
|
||||
])->assertOk();
|
||||
|
||||
$code = (string) $send->json('debug_code');
|
||||
$this->assertMatchesRegularExpression('/^\d{6}$/', $code);
|
||||
|
||||
$record = SmsVerification::query()->firstOrFail();
|
||||
$this->assertSame(SmsVerification::STATUS_SENT, $record->status);
|
||||
$this->assertSame(SmsVerification::PROVIDER_DISABLED, $record->provider);
|
||||
$this->assertSame('DISABLED_OK', $record->provider_code);
|
||||
$this->assertSame('138****8000', $record->request_payload_json['phone_number']);
|
||||
$this->assertArrayNotHasKey('code', $record->request_payload_json);
|
||||
|
||||
$this->postJson('/api/auth/sms/login', [
|
||||
'mobile' => '13800138000',
|
||||
'code' => $code,
|
||||
'competition_slug' => 'main-event',
|
||||
])->assertOk()
|
||||
->assertJsonPath('token_type', 'Bearer');
|
||||
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'id' => $record->id,
|
||||
'status' => SmsVerification::STATUS_USED,
|
||||
]);
|
||||
$this->assertDatabaseHas('applications', [
|
||||
'competition_id' => Competition::query()->where('slug', 'main-event')->value('id'),
|
||||
'status' => 'draft',
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/login', [
|
||||
'mobile' => '13800138000',
|
||||
'code' => $code,
|
||||
'competition_slug' => 'main-event',
|
||||
])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_enabled_sender_fails_fast_when_cloud_credentials_are_missing(): void
|
||||
{
|
||||
config(['sms.enabled' => true]);
|
||||
Http::fake();
|
||||
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138001',
|
||||
])->assertStatus(503)
|
||||
->assertJsonPath('message', '短信服务配置未完成');
|
||||
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'mobile' => '13800138001',
|
||||
'provider' => SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
'status' => SmsVerification::STATUS_FAILED,
|
||||
'provider_code' => 'CONFIG_INCOMPLETE',
|
||||
]);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_disabled_sender_does_not_expose_debug_code_in_production(): void
|
||||
{
|
||||
$this->app->detectEnvironment(fn () => 'production');
|
||||
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138006',
|
||||
])->assertOk()
|
||||
->assertJsonMissingPath('debug_code');
|
||||
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'mobile' => '13800138006',
|
||||
'provider' => SmsVerification::PROVIDER_DISABLED,
|
||||
'status' => SmsVerification::STATUS_SENT,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_enabled_sender_posts_tencent_cloud_template_parameters_and_marks_sent(): void
|
||||
{
|
||||
$this->enableTencentCloudConfig();
|
||||
Http::fake([
|
||||
'https://sms.tencentcloudapi.com' => Http::response([
|
||||
'Response' => [
|
||||
'SendStatusSet' => [[
|
||||
'SerialNo' => 'serial-1',
|
||||
'PhoneNumber' => '+8613800138002',
|
||||
'Fee' => 1,
|
||||
'SessionContext' => '',
|
||||
'Code' => 'Ok',
|
||||
'Message' => 'send success',
|
||||
'IsoCode' => 'CN',
|
||||
]],
|
||||
'RequestId' => 'request-1',
|
||||
],
|
||||
], 200),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138002',
|
||||
])->assertOk()
|
||||
->assertJsonMissingPath('debug_code');
|
||||
|
||||
Http::assertSent(function (Request $request): bool {
|
||||
$payload = json_decode($request->body(), true);
|
||||
|
||||
return $request->hasHeader('X-TC-Action', 'SendSms')
|
||||
&& $request->hasHeader('X-TC-Version', '2021-01-11')
|
||||
&& str_contains((string) $request->header('Authorization')[0], 'TC3-HMAC-SHA256 Credential=test-secret-id/')
|
||||
&& $payload['PhoneNumberSet'] === ['+8613800138002']
|
||||
&& $payload['SmsSdkAppId'] === '1400000000'
|
||||
&& $payload['SignName'] === '元禾控股'
|
||||
&& $payload['TemplateId'] === '2175650'
|
||||
&& count($payload['TemplateParamSet']) === 2
|
||||
&& preg_match('/^\d{6}$/', (string) $payload['TemplateParamSet'][0]) === 1
|
||||
&& $payload['TemplateParamSet'][1] === '5';
|
||||
});
|
||||
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'mobile' => '13800138002',
|
||||
'provider' => SmsVerification::PROVIDER_TENCENTCLOUD,
|
||||
'status' => SmsVerification::STATUS_SENT,
|
||||
'provider_request_id' => 'request-1',
|
||||
'provider_code' => 'Ok',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_failed_new_send_keeps_previous_sent_code_usable(): void
|
||||
{
|
||||
$competition = $this->competition('main-event');
|
||||
$old = SmsVerification::query()->create([
|
||||
'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN,
|
||||
'mobile' => '13800138003',
|
||||
'code' => '111111',
|
||||
'provider' => SmsVerification::PROVIDER_DISABLED,
|
||||
'status' => SmsVerification::STATUS_SENT,
|
||||
'expires_at' => now()->addMinutes(5),
|
||||
]);
|
||||
|
||||
$this->enableTencentCloudConfig();
|
||||
Http::fake([
|
||||
'https://sms.tencentcloudapi.com' => Http::response([
|
||||
'Response' => [
|
||||
'SendStatusSet' => [[
|
||||
'Code' => 'FailedOperation.TemplateIncorrect',
|
||||
'Message' => 'template incorrect',
|
||||
]],
|
||||
'RequestId' => 'request-failed',
|
||||
],
|
||||
], 200),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138003',
|
||||
])->assertStatus(503)
|
||||
->assertJsonPath('message', '发送失败');
|
||||
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'id' => $old->id,
|
||||
'status' => SmsVerification::STATUS_SENT,
|
||||
]);
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'mobile' => '13800138003',
|
||||
'status' => SmsVerification::STATUS_FAILED,
|
||||
'provider_request_id' => 'request-failed',
|
||||
'provider_code' => 'FailedOperation.TemplateIncorrect',
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/login', [
|
||||
'mobile' => '13800138003',
|
||||
'code' => '111111',
|
||||
'competition_slug' => $competition->slug,
|
||||
])->assertOk();
|
||||
}
|
||||
|
||||
public function test_successful_new_send_expires_previous_sent_code(): void
|
||||
{
|
||||
$this->competition('main-event');
|
||||
$old = SmsVerification::query()->create([
|
||||
'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN,
|
||||
'mobile' => '13800138007',
|
||||
'code' => '333333',
|
||||
'provider' => SmsVerification::PROVIDER_DISABLED,
|
||||
'status' => SmsVerification::STATUS_SENT,
|
||||
'expires_at' => now()->addMinutes(5),
|
||||
]);
|
||||
|
||||
$this->enableTencentCloudConfig();
|
||||
Http::fake([
|
||||
'https://sms.tencentcloudapi.com' => Http::response([
|
||||
'Response' => [
|
||||
'SendStatusSet' => [[
|
||||
'Code' => 'Ok',
|
||||
'Message' => 'send success',
|
||||
]],
|
||||
'RequestId' => 'request-new',
|
||||
],
|
||||
], 200),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138007',
|
||||
])->assertOk();
|
||||
|
||||
$this->assertDatabaseHas('sms_verifications', [
|
||||
'id' => $old->id,
|
||||
'status' => SmsVerification::STATUS_EXPIRED,
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/login', [
|
||||
'mobile' => '13800138007',
|
||||
'code' => '333333',
|
||||
'competition_slug' => 'main-event',
|
||||
])->assertUnprocessable()
|
||||
->assertJsonValidationErrors('code');
|
||||
}
|
||||
|
||||
public function test_rate_limit_is_kept_after_successful_send(): void
|
||||
{
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138004',
|
||||
])->assertOk();
|
||||
|
||||
$this->postJson('/api/auth/sms/send', [
|
||||
'mobile' => '13800138004',
|
||||
])->assertUnprocessable()
|
||||
->assertJsonValidationErrors('mobile');
|
||||
}
|
||||
|
||||
public function test_expired_sent_code_cannot_login(): void
|
||||
{
|
||||
$this->competition('main-event');
|
||||
SmsVerification::query()->create([
|
||||
'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN,
|
||||
'mobile' => '13800138005',
|
||||
'code' => '222222',
|
||||
'provider' => SmsVerification::PROVIDER_DISABLED,
|
||||
'status' => SmsVerification::STATUS_SENT,
|
||||
'expires_at' => now()->subSecond(),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/sms/login', [
|
||||
'mobile' => '13800138005',
|
||||
'code' => '222222',
|
||||
'competition_slug' => 'main-event',
|
||||
])->assertUnprocessable()
|
||||
->assertJsonValidationErrors('code');
|
||||
}
|
||||
|
||||
private function enableTencentCloudConfig(): void
|
||||
{
|
||||
config([
|
||||
'sms.enabled' => true,
|
||||
'sms.tencentcloud.secret_id' => 'test-secret-id',
|
||||
'sms.tencentcloud.secret_key' => 'test-secret-key',
|
||||
'sms.tencentcloud.sdk_app_id' => '1400000000',
|
||||
]);
|
||||
}
|
||||
|
||||
private function competition(string $slug): Competition
|
||||
{
|
||||
return Competition::query()->create([
|
||||
'slug' => $slug,
|
||||
'name' => '测试赛事',
|
||||
'status' => 'published',
|
||||
'published' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createSchema(): void
|
||||
{
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('mobile')->unique();
|
||||
$table->string('name')->nullable();
|
||||
$table->string('email')->nullable();
|
||||
$table->string('password')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('competitions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('slug')->unique();
|
||||
$table->string('name');
|
||||
$table->string('status')->default('draft');
|
||||
$table->boolean('published')->default(false);
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('applications', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id');
|
||||
$table->foreignId('competition_id');
|
||||
$table->string('status')->default('draft');
|
||||
$table->timestamps();
|
||||
$table->unique(['user_id', 'competition_id']);
|
||||
});
|
||||
|
||||
Schema::create('sms_verifications', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('scene', 64)->default('participant_login');
|
||||
$table->string('mobile', 20)->index();
|
||||
$table->string('code', 10);
|
||||
$table->string('provider', 32)->default('disabled');
|
||||
$table->string('status', 16)->default('pending');
|
||||
$table->string('template_id', 64)->nullable();
|
||||
$table->string('sign_name', 64)->nullable();
|
||||
$table->json('request_payload_json')->nullable();
|
||||
$table->json('response_json')->nullable();
|
||||
$table->string('provider_request_id', 128)->nullable();
|
||||
$table->string('provider_code', 128)->nullable();
|
||||
$table->string('provider_message', 500)->nullable();
|
||||
$table->timestamp('expires_at');
|
||||
$table->timestamp('sent_at')->nullable();
|
||||
$table->timestamp('failed_at')->nullable();
|
||||
$table->timestamp('used_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('personal_access_tokens', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->morphs('tokenable');
|
||||
$table->string('name');
|
||||
$table->string('token', 64)->unique();
|
||||
$table->text('abilities')->nullable();
|
||||
$table->timestamp('last_used_at')->nullable();
|
||||
$table->timestamp('expires_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue