errorReporting = error_reporting(); $this->displayErrors = ini_get('display_errors'); $this->app = require dirname(__DIR__, 2) . '/bootstrap/app.php'; $this->kernel = $this->app->make(Kernel::class); $this->kernel->bootstrap(); $key = base64_encode(str_repeat('k', 32)); $this->crypto = new ApiCryptoService($key); config([ 'app.env' => 'testing', 'app.debug' => false, 'app.key' => 'base64:' . $key, 'api_crypto.enabled' => true, 'api_crypto.key' => $key, 'api_crypto.allow_plaintext' => false, 'api_crypto.timestamp_tolerance' => 300, 'api_crypto.max_payload_bytes' => 2097152, 'cache.default' => 'array', 'database.default' => 'sqlite', 'database.connections.sqlite.url' => null, 'database.connections.sqlite.database' => ':memory:', 'database.connections.sqlite.prefix' => 'bot_', 'logging.default' => 'null', 'logging.channels.dblog' => config('logging.channels.null'), 'app.tree_payment_merchant_id' => '', 'app.tree_pay_mch_id' => '', 'app.jd_pay_mch_id' => '', ]); } protected function tearDown(): void { DB::disconnect(); Facade::clearResolvedInstances(); $this->app->flush(); restore_error_handler(); restore_exception_handler(); error_reporting($this->errorReporting); ini_set('display_errors', $this->displayErrors); parent::tearDown(); } public function test_real_wallet_and_lottery_routes_keep_the_original_business_response(): void { $this->createWalletFixture(); Schema::create('pc_issues', function (Blueprint $table) { $table->id(); $table->integer('status'); $table->string('issue_no'); }); $response = $this->sendEncrypted('/api/wallet/withdrawChannel?lang=zh', 'GET', ['lang' => 'en'], true); $body = $this->unwrap($response); self::assertSame(0, $body['code']); self::assertSame(['code', 'timestamp', 'msg', 'data'], array_keys($body)); self::assertSame('Bank card', array_column($body['data'], 'label', 'value')['DF001']); $lottery = $this->unwrap($this->sendEncrypted('/api/newPc/yuanTou', 'GET', (object) [])); self::assertSame(0, $lottery['code'] ?? null, json_encode($lottery)); self::assertSame([], $lottery['data']); $response = $this->sendEncrypted('/api/wallet/payout?amount=900', 'POST', [ 'channel' => 'NOwithdraw', 'amount' => 100, 'card_no' => ' no_fixture ', 'safe_word' => 'fixture-password', ], true, ['card_no' => 'outer-account']); $body = $this->unwrap($response); self::assertSame(0, $body['code'] ?? null, json_encode($body)); $order = DB::table('payment_orders')->sole(); self::assertSame('NOwithdraw', $order->channel); self::assertSame('no_fixture', $order->card_no); self::assertSame(100, (int) $order->amount); DB::table('user_session')->where('token', self::TOKEN)->update(['expire_time' => time() - 1]); $expiredSession = $this->sendEncrypted('/api/wallet/withdrawChannel', 'GET', (object) [], true); self::assertSame(401, $expiredSession->getStatusCode()); self::assertSame(401, $this->unwrap($expiredSession)['code']); } public function test_authentication_and_maintenance_errors_remain_encrypted(): void { $this->createMaintenanceFixture(); $response = $this->sendEncrypted('/api/wallet/withdrawChannel', 'GET', (object) []); self::assertSame(401, $response->getStatusCode()); self::assertSame(401, $this->unwrap($response)['code']); DB::table('maintenance_settings')->where('scope_code', 'site')->update(['enabled' => 1, 'platforms' => '["H5"]']); $response = $this->sendEncrypted('/api/wallet/withdrawChannel?platform=PC', 'GET', ['platform' => 'H5']); self::assertSame(200, $response->getStatusCode()); self::assertSame(11001, $this->unwrap($response)['code']); } public function test_registered_real_name_is_used_for_binding_and_payout(): void { $this->createWalletFixture(); DB::table('users')->where('member_id', '42')->update(['real_name' => 'Registered Name']); $binding = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [ 'channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345', 'account' => 'Different Name', ], true)); self::assertSame('Registered Name', $binding['data']['real_name']); self::assertSame('Registered Name', DB::table('banks')->sole()->account); $payout = $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', [ 'channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345', 'amount' => 100, 'safe_word' => 'fixture-password', 'account' => 'Another Name', ], true)); self::assertSame(0, $payout['code'], $payout['msg']); self::assertSame('Registered Name', DB::table('payment_orders')->sole()->account); self::assertSame('Registered Name', UserService::paginate()['data']->first()->toArray()['real_name']); self::assertArrayNotHasKey('real_name', \App\Models\User::first()->toArray()); } public function test_only_the_first_successful_named_binding_can_set_a_missing_real_name(): void { $this->createWalletFixture(); $params = ['channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345']; $payout = $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', $params + [ 'amount' => 100, 'safe_word' => 'fixture-password', 'account' => 'Unbound Name', ], true)); self::assertSame('请先绑定收款账户并填写真实姓名', $payout['msg']); self::assertSame(0, DB::table('payment_orders')->count()); $invalid = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', $params + [ 'id' => 999, 'account' => 'Invalid Binding', ], true)); self::assertNotSame(0, $invalid['code']); self::assertNull(DB::table('users')->value('real_name')); DB::unprepared("CREATE TRIGGER reject_bank BEFORE INSERT ON bot_banks WHEN NEW.card_no = 'reject-fixture' BEGIN SELECT RAISE(ABORT, 'fixture failure'); END"); $failedSave = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [ 'card_no' => 'reject-fixture', 'account' => 'Failed Name', ] + $params, true)); self::assertNotSame(0, $failedSave['code']); self::assertNull(DB::table('users')->value('real_name')); $noName = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [ 'channel' => 'NOwithdraw', 'bank_name' => 'NO Wallet', 'card_no' => 'no_fixture', ], true)); self::assertSame(0, $noName['code']); self::assertNull($noName['data']['real_name']); $binding = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', $params + [ 'account' => " First Bound Name ", ], true)); self::assertSame('First Bound Name', $binding['data']['real_name']); $id = DB::table('banks')->where('channel', 'DF001')->value('id'); $update = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', $params + [ 'id' => $id, 'account' => 'Replacement Name', ], true)); self::assertSame('First Bound Name', $update['data']['real_name']); self::assertSame('First Bound Name', DB::table('banks')->where('id', $id)->value('account')); $deleted = $this->unwrap($this->sendEncrypted('/api/wallet/delBank', 'GET', ['id' => $id], true)); self::assertSame(0, $deleted['code']); $list = $this->unwrap($this->sendEncrypted('/api/wallet/bankList', 'GET', (object) [], true)); self::assertSame('First Bound Name', $list['data']['real_name']); self::assertSame('First Bound Name', $list['data']['list'][0]['account']); } public function test_protocol_errors_and_rollout_flags(): void { Route::get('api/wallet/probe', fn () => response()->json(['code' => 0])); foreach (['/api/wallet/probe', '/api/newPc', '/api/issue', '/api/pcissue'] as $path) { $response = $this->send($path); self::assertSame(400, $response->getStatusCode()); self::assertSame(4001, $this->unwrap($response)['code']); } $payload = $this->crypto->encrypt(['amount' => 100], 'request'); $envelope = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); $envelope['tag'][0] = $envelope['tag'][0] === 'A' ? 'B' : 'A'; $tampered = rtrim(strtr(base64_encode(json_encode($envelope)), '+/', '-_'), '='); $expired = $this->crypto->encrypt((object) [], 'request', (time() - 301) * 1000); $wrongDirection = $this->crypto->encrypt((object) [], 'response'); foreach (['', $tampered, $expired, $wrongDirection, $this->crypto->encrypt([], 'request')] as $invalid) { $response = $this->send('/api/wallet/probe?payload=' . $invalid, 'GET', ['HTTP_X_API_ENCRYPTED' => '1']); self::assertSame(400, $response->getStatusCode()); self::assertSame(4002, $this->unwrap($response)['code']); } Route::get('api/wallet/large-response', fn () => response()->json(['data' => str_repeat('x', 1024)])); config(['api_crypto.max_payload_bytes' => 1024]); $response = $this->sendEncrypted('/api/wallet/large-response', 'GET', (object) []); self::assertSame(500, $response->getStatusCode()); self::assertSame(5002, json_decode($response->getContent(), true)['code']); config(['api_crypto.allow_plaintext' => true]); self::assertSame('{"code":0}', $this->send('/api/wallet/probe')->getContent()); self::assertSame(0, $this->unwrap($this->sendEncrypted('/api/wallet/probe', 'GET', (object) []))['code']); config(['api_crypto.key' => 'invalid']); $response = $this->send('/api/wallet/probe'); self::assertSame(500, $response->getStatusCode()); self::assertSame(5001, json_decode($response->getContent(), true)['code']); config(['api_crypto.enabled' => false]); self::assertSame('{"code":0}', $this->send('/api/wallet/probe')->getContent()); } public function test_cors_preflight_and_head(): void { Route::get('api/wallet/probe', fn () => response()->json(['code' => 0])); $response = $this->send('/api/wallet/probe', 'OPTIONS', [ 'HTTP_ORIGIN' => 'https://frontend.example', 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST', 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'content-type,x-api-encrypted', ]); self::assertSame(204, $response->getStatusCode()); self::assertStringContainsString('x-api-encrypted', strtolower($response->headers->get('Access-Control-Allow-Headers'))); self::assertFalse($response->headers->has('X-Api-Encrypted')); $response = $this->sendEncrypted('/api/wallet/probe', 'HEAD', (object) []); self::assertSame(200, $response->getStatusCode()); self::assertSame('1', $response->headers->get('X-Api-Encrypted')); self::assertStringContainsString('X-Api-Encrypted', $response->headers->get('Access-Control-Expose-Headers')); self::assertSame('', $response->getContent()); } public function test_excluded_routes_keep_plaintext_input_and_response(): void { $this->createMaintenanceFixture(); (require dirname(__DIR__, 2) . '/database/migrations/2026_09_08_160000_add_payment_provider_status_and_channel_soft_deletes.php')->up(); $this->app->instance(TelegramWebHook::class, new class extends TelegramWebHook { public function __construct() {} public function handle(Request $request): JsonResponse { return response()->json(['update_id' => $request->input('update_id')]); } }); $telegram = $this->send('/api/onMessage', 'POST', ['CONTENT_TYPE' => 'application/json'], '{"update_id":123}'); self::assertSame('{"update_id":123}', $telegram->getContent()); self::assertFalse($telegram->headers->has('X-Api-Encrypted')); foreach (['notify', 'harvest'] as $callback) { $response = $this->send('/api/pay/' . $callback, 'POST', ['CONTENT_TYPE' => 'application/json'], '{"appId":"unmatched-fixture","merchantNum":"unmatched-fixture","userCode":"unmatched-fixture","mchId":"unmatched-fixture"}'); self::assertSame(200, $response->getStatusCode(), $callback . ': ' . $response->getContent()); self::assertSame('success', $response->getContent()); self::assertFalse($response->headers->has('X-Api-Encrypted')); } Schema::create('config', function (Blueprint $table) { $table->id(); $table->string('field'); $table->string('val'); }); DB::table('config')->insert([ ['field' => 'activity_rule', 'val' => 'Telegram rule fixture'], ['field' => 'benefits_service_customer', 'val' => 'customer fixture'], ]); $activity = $this->send('/api/ActivityReward/rule'); self::assertSame(200, $activity->getStatusCode()); self::assertSame('Telegram rule fixture', json_decode($activity->getContent(), true)['data']['rule']); self::assertFalse($activity->headers->has('X-Api-Encrypted')); $admin = $this->send('/admin/maintenance/options'); self::assertFalse($admin->headers->has('X-Api-Encrypted')); } private function send(string $url, string $method = 'GET', array $headers = [], ?string $body = null): Response { return $this->kernel->handle(Request::create($url, $method, [], [], [], $headers + [ 'HTTP_ORIGIN' => 'https://frontend.example', 'HTTP_ACCEPT' => 'application/json', ], $body)); } private function sendEncrypted(string $url, string $method, array|object $parameters, bool $authenticated = false, array $outerBody = []): Response { $payload = $this->crypto->encrypt($parameters, 'request'); $headers = ['HTTP_X_API_ENCRYPTED' => '1']; if ($authenticated) { $headers['HTTP_AUTHORIZATION'] = self::TOKEN; } if ($method === 'POST') { return $this->send($url, $method, $headers + ['CONTENT_TYPE' => 'application/json'], json_encode(['payload' => $payload] + $outerBody)); } return $this->send($url . (str_contains($url, '?') ? '&' : '?') . 'payload=' . $payload, $method, $headers); } private function unwrap(Response $response): array { self::assertSame('1', $response->headers->get('X-Api-Encrypted'), (string) $response->getContent()); self::assertStringContainsString('no-store', $response->headers->get('Cache-Control')); $envelope = json_decode($response->getContent(), true, 512, JSON_THROW_ON_ERROR); self::assertTrue($envelope['encrypted']); return $this->crypto->decrypt($envelope['payload'], 'response'); } private function createMaintenanceFixture(): void { (require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_120000_create_maintenance_settings.php')->up(); } private function createWalletFixture(): void { $this->createMaintenanceFixture(); Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('user_id'); $table->string('member_id'); $table->integer('from'); $table->integer('recharge_channel_group_id'); $table->string('payment_password'); $table->integer('level')->default(1); $table->string('agent_user_code')->nullable(); $table->timestamps(); }); (require dirname(__DIR__, 2) . '/database/migrations/2026_11_06_120000_add_real_name_to_users.php')->up(); Schema::create('level', function (Blueprint $table) { $table->id(); $table->integer('level'); $table->string('level_name'); $table->string('img'); $table->decimal('recharge'); }); Schema::create('user_session', function (Blueprint $table) { $table->id(); $table->string('user_id'); $table->string('token'); $table->bigInteger('expire_time'); $table->bigInteger('create_time'); $table->bigInteger('update_time'); }); Schema::create('recharge_channel_group', function (Blueprint $table) { $table->id(); $table->string('withdraw_type'); $table->softDeletes(); }); Schema::create('recharge_channel', function (Blueprint $table) { $table->id(); $table->integer('data_type'); $table->integer('status'); $table->integer('sort'); $table->string('name'); $table->string('type'); $table->decimal('rate'); $table->decimal('min'); $table->decimal('max'); $table->string('fixed')->nullable(); $table->string('logo')->nullable(); }); (require dirname(__DIR__, 2) . '/database/migrations/2026_09_08_160000_add_payment_provider_status_and_channel_soft_deletes.php')->up(); Schema::create('wallets', function (Blueprint $table) { $table->id(); $table->string('member_id'); $table->decimal('available_balance'); $table->decimal('frozen_balance')->default(0); $table->timestamps(); }); Schema::create('payment_orders', function (Blueprint $table) { $table->id(); $table->integer('type'); $table->integer('status'); foreach (['member_id', 'order_no', 'channel', 'bank_name', 'account', 'card_no', 'callback_url', 'remark'] as $field) { $table->string($field); } $table->decimal('amount'); $table->decimal('fee'); $table->timestamps(); }); Schema::create('backflow', function (Blueprint $table) { $table->id(); $table->string('member_id'); $table->string('date'); $table->integer('status')->default(0); $table->decimal('withdrawal_amount')->default(0); $table->timestamps(); }); Schema::create('balance_logs', function (Blueprint $table) { $table->id(); $table->integer('type')->default(1); $table->string('member_id'); $table->string('change_type'); $table->integer('related_id'); $table->string('remark'); $table->decimal('amount'); $table->decimal('before_balance'); $table->decimal('after_balance'); $table->timestamps(); }); Schema::create('banks', function (Blueprint $table) { $table->id(); foreach (['member_id', 'channel', 'bank_name', 'account', 'card_no', 'alias'] as $field) { $table->string($field); } $table->timestamps(); }); DB::table('users')->insert(['user_id' => '42', 'member_id' => '42', 'from' => 1, 'recharge_channel_group_id' => 1, 'payment_password' => password_hash('fixture-password', PASSWORD_DEFAULT)]); DB::table('user_session')->insert(['user_id' => '42', 'token' => self::TOKEN, 'expire_time' => time() + 3600, 'create_time' => time(), 'update_time' => time()]); DB::table('wallets')->insert(['member_id' => '42', 'available_balance' => 1000]); DB::table('recharge_channel_group')->insert(['id' => 1, 'withdraw_type' => 'DF001,NOwithdraw']); foreach (['DF001' => '银行卡', 'NOwithdraw' => 'NO快捷提现'] as $type => $name) { DB::table('recharge_channel')->insert(['data_type' => 2, 'status' => 1, 'sort' => 0, 'name' => $name, 'type' => $type, 'rate' => 0, 'min' => 10, 'max' => 5000]); } } }