解決微信公眾號OAuth出現40029(invalid code,不合法的oauth_code)的錯誤


解決方案四(推薦★★★★★)

利用同步鎖,判斷code的使用情況,這是最粗獷也是最徹底的方法,以 C# 使用 Senparc.Weixin SDK 為例,直接上代碼:

定義靜態變量:

    static Dictionary<string, OAuthAccessTokenResult> OAuthCodeCollection = new Dictionary<string, OAuthAccessTokenResult>(); static object OAuthCodeCollectionLock = new object(); 

回調方法內:

    string openId; OAuthAccessTokenResult result = null; try { //通過,用code換取access_token var isSecondRequest = false; lock (OAuthCodeCollectionLock) { isSecondRequest = OAuthCodeCollection.ContainsKey(code); } if (!isSecondRequest) { //第一次請求 LogUtility.Weixin.DebugFormat("第一次微信OAuth到達,code:{0}", code); lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = null; } } else { //第二次請求 LogUtility.Weixin.DebugFormat("第二次微信OAuth到達,code:{0}", code); lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } try { try { result = result ?? OAuthApi.GetAccessToken(SiteConfig.YourAppId, SiteConfig.YourAppSecret, code); } catch (Exception ex) { return Content("OAuth AccessToken錯誤:" + ex.Message); } if (result != null) { lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = result; } } } catch (ErrorJsonResultException ex) { if (ex.JsonResult.errcode == ReturnCode.不合法的oauth_code) { //code已經被使用過 lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } } openId = result != null ? result.openid : null; } catch (Exception ex) { return Content("授權過程發生錯誤:" + ex.Message); } //使用result繼續操作

說明:
1、上述靜態Dicitonary的儲存方式適用於單台服務器,如果是分布式的系統,這里的Dictionary請使用公共緩存(如Redis),並使用分布鎖,否則如果兩次請求命中了兩台不同的服務器仍然會失效。
2、請注意做好緩存清理工作

解決方案總結

以上解決方案沒有絕對的好壞之分,要看具體的環境,因為都不會涉及到影響效率和安全性的問題,可以視情況組合使用。推薦指數更多傾向於通用性。

參考資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM