Telegram测试服务器登录报错PHONE_CODE_INVALID求助
Telegram测试服务器登录验证码无效问题排查与解决
问题说明
使用Windows桌面客户端及GramJS API登录Telegram测试服务器时,输入测试号码9996611502与验证码11111,收到提示“您输入的验证码无效”,调用自定义authTestUser函数触发如下错误:
Error in authTestUser: For +9996611502. RPCError: 400: PHONE_CODE_INVALID (caused by auth.SignIn)
原代码示例
async authTestUser(phoneNumber: string, code: number, user = "User One") { let stringSession = new StringSession(""); let telegramTestDC = { dcId: 3, ip: "149.154.175.117", // dcId: 2, // ip: "149.154.167.40", // dcId: 1, // ip: "149.154.175.10", port: 443, } stringSession.setDC( telegramTestDC.dcId, telegramTestDC.ip, telegramTestDC.port ); this.client = new TelegramClient(stringSession, apiId, apiHash, { testServers: true, connectionRetries: 5, requestRetries: 10, }); await this.client.start({ phoneNumber: phoneNumber, phoneCode: async () => { return code.toString() }, firstAndLastNames: async () => { return [`First name ${user}`, `Last name ${user}`] }, onError: (err: any) => { throw new Error(`Error in authTestUser: For ${phoneNumber}. ${err}`); }, }); this.clientSessionString = await this.client.session.save(); console.log(this.clientSessionString); return this.client; }
排查与解决步骤
1. 确认测试环境API凭证
确保使用的apiId和apiHash是Telegram测试环境专用的,不能直接复用生产环境的凭证。测试环境需单独申请对应凭证,否则会导致验证流程不兼容。
2. 移除手动DC配置
手动指定DC可能与服务器分配的DC不匹配,导致验证码请求和验证操作不在同一DC下,引发无效错误。建议移除手动设置DC的代码,让GramJS自动协商测试服务器的DC。
3. 简化验证码返回逻辑
测试号码的验证码11111是固定值,直接返回字符串格式即可,避免类型转换可能带来的隐性问题。
4. 修改后的代码示例
async authTestUser(phoneNumber: string, code: number, user = "User One") { let stringSession = new StringSession(""); // 移除手动DC配置,由客户端自动协商 this.client = new TelegramClient(stringSession, apiId, apiHash, { testServers: true, connectionRetries: 5, requestRetries: 10, }); await this.client.start({ phoneNumber: phoneNumber, phoneCode: async () => "11111", // 直接返回固定验证码字符串 firstAndLastNames: async () => [`First name ${user}`, `Last name ${user}`], onError: (err: any) => { throw new Error(`Error in authTestUser: For ${phoneNumber}. ${err}`); }, }); this.clientSessionString = await this.client.session.save(); console.log(this.clientSessionString); return this.client; }
5. 同步桌面客户端测试环境设置
Windows桌面客户端需开启测试服务器模式(路径:设置->高级->测试服务器),确保与API使用的是同一测试环境,避免跨环境导致验证码无效。
内容的提问来源于stack exchange,提问作者Stas
相关产品推荐
相关产品推荐

