{"record":{"id":"5e9e04a95a289861","repo":"JeffreySu/WeiXinMPSDK","slug":"commonapi-gettoken-0-1","errorCode":null,"errorMessage":"微信请求发生错误（CommonApi.GetToken）！错误代码：{0}，说明：{1}","messagePattern":"微信请求发生错误（CommonApi\\.GetToken）！错误代码：(.+?)，说明：(.+?)","errorType":"exception","errorClass":"ErrorJsonResultException","httpStatus":null,"severity":"error","filePath":"src/Senparc.Weixin.MP/Senparc.Weixin.MP/CommonAPIs/CommonApi.cs","lineNumber":114,"sourceCode":"\n        /// <summary>\n        /// 获取凭证接口\n        /// </summary>\n        /// <param name=\"grant_type\">获取access_token填写client_credential</param>\n        /// <param name=\"appid\">第三方用户唯一凭证</param>\n        /// <param name=\"secret\">第三方用户唯一凭证密钥，既appsecret</param>\n        /// <returns></returns>\n        public static AccessTokenResult GetToken(string appid, string secret, string grant_type = \"client_credential\")\n        {\n            //注意：此方法不能再使用ApiHandlerWapper.TryCommonApi()，否则会循环\n            var url = string.Format(Config.ApiMpHost + \"/cgi-bin/token?grant_type={0}&appid={1}&secret={2}\",\n                                    grant_type.AsUrlData(), appid.AsUrlData(), secret.AsUrlData());\n\n            AccessTokenResult result = Get.GetJson<AccessTokenResult>(CommonDI.CommonSP, url);//此处为最原始接口，不再使用重试获取的封装\n\n            if (Config.ThrownWhenJsonResultFaild && result.errcode != ReturnCode.请求成功)\n            {\n                throw new ErrorJsonResultException(\n                    string.Format(\"微信请求发生错误（CommonApi.GetToken）！错误代码：{0}，说明：{1}\",\n                        (int)result.errcode, result.errmsg), null, result);\n            }\n\n            return result;\n        }   \n        \n        /// <summary>\n        /// 获取稳定版接口调用凭据\n        /// </summary>\n        /// <param name=\"grant_type\">获取access_token填写client_credential</param>\n        /// <param name=\"appid\">账号唯一凭证，即 AppID，可在「微信公众平台 - 设置 - 开发设置」页中获得。（需要已经成为开发者，且帐号没有异常状态）</param>\n        /// <param name=\"secret\">帐号唯一凭证密钥，即 AppSecret，获取方式同 appid</param>\n        /// <param name=\"force_refresh\">默认使用 false。\n        /// 1. force_refresh = false 时为普通调用模式，access_token 有效期内重复调用该接口不会更新 access_token；\n        /// 2. 当force_refresh = true 时为强制刷新模式，会导致上次获取的 access_token 失效，并返回新的 access_token</param>\n        /// <returns></returns>\n        public static AccessTokenResult GetStableAccessToken(string appid, string secret, string grant_type = \"client_credential\",bool force_refresh=false)","sourceCodeStart":96,"sourceCodeEnd":132,"githubUrl":"https://github.com/JeffreySu/WeiXinMPSDK/blob/be573f6f94bdbf718dd5f6cdecb137fbc7ff651e/src/Senparc.Weixin.MP/Senparc.Weixin.MP/CommonAPIs/CommonApi.cs#L96-L132","documentation":"GetToken requests an access token from Weixin's OAuth endpoint; when Config.ThrownWhenJsonResultFaild is true and Weixin returns a non-success errcode, the library throws ErrorJsonResultException embedding the numeric error code and errmsg. It means Weixin itself rejected the token request.","triggerScenarios":"Calling CommonApi.GetToken(appid, secret) where Weixin returns errcode such as 40001 (invalid secret) or 40013 (invalid appid), with Config.ThrownWhenJsonResultFaild enabled.","commonSituations":"Wrong or rotated AppSecret, appid/secret from a different environment, IP not on the Weixin official-account whitelist, or token quota issues.","solutions":["Read result.errcode/errmsg in the exception (ErrorJsonResultException carries the JSON result) and look up the Weixin error code","Verify appid and AppSecret against the Weixin admin console","Add your server's outbound IP to the official account IP whitelist","Optionally set Config.ThrownWhenJsonResultFaild = false if you prefer handling errcode manually"],"exampleFix":"// before\nvar token = CommonApi.GetToken(appId, wrongSecret);\n// after\nvar token = CommonApi.GetToken(appId, secretFromConfig); // secret verified in Weixin admin console","handlingStrategy":"try-catch","validationCode":"if (string.IsNullOrWhiteSpace(appid) || string.IsNullOrWhiteSpace(secret))\n    throw new InvalidOperationException(\"appid/secret must be configured before GetToken\");","typeGuard":null,"tryCatchPattern":"try\n{\n    var token = CommonApi.GetToken(appid, secret);\n}\ncatch (ErrorJsonResultException ex)\n{\n    logger.LogError(\"GetToken failed: {Code} {Msg}\", (int)ex.JsonResult.errcode, ex.JsonResult.errmsg);\n}","preventionTips":["Keep appid/secret in validated configuration, not hardcoded","Maintain the server IP whitelist in the Weixin console","Cache access tokens instead of requesting per call","Check Config.ThrownWhenJsonResultFaild so you know which error mode you are in"],"tags":["weixin","api-error","access-token"],"backgroundTag":"api-error-response","analyzedSha":"be573f6f94bdbf718dd5f6cdecb137fbc7ff651e","analyzedAt":"2026-09-12T10:01:50.733Z","contentChangedAt":"2026-09-12T10:01:50.733Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}