微信小程序后台獲取用戶手機,openid(C#) --markdown


微信小程序后台獲取用戶手機,openid(C#)


  • 注意事項
    • 前端調用 wx.login 保存返回的code
    • 前端調用 wx.getUserInfo 保存返回的encryptedData 與 iv
    • 前端組合 code,encryptedData,iv傳入后台進行解密
    • 官網上寫的是對稱解密使用的算法為 AES-128-CBC,數據采用PKCS#7填充。但是設置的時候,千萬不要設置128位。會出現亂碼。
    • 出現Padding is invalid and cannot be removed。你的sessionKey有問題。千萬別百度網上亂起八糟的解決辦法。查詢第一個步驟。
st=>start: 前端傳入參數code,encryptedData,iv
op=>operation: 根據自己的配置調用獲取session_key與openid接口(注意請求時效)
op1=>operation: 返回的json字符串獲取sessionKey,openid
op2=>operation: 解密encryptedData
op3=>operation: 處理待解密字符串格式
op4=>operation: 創建方法進行解密
e=>end: 結束

st->op->op1->op2->op3->op4->e

    /// sessionKey 是用戶登陸code
    /// text 加密內容
    /// iv  加密配置
    public IActionResult DecryptWXString(string sessionKey, string text, string iv)
        {
            string openid = "";
            string url = @"https://api.weixin.qq.com/sns/jscode2session?appid=填寫自己的&secret=填寫自己的&js_code="+ sessionKey + "&grant_type=authorization_code";
            // 簡單的http 請求自己寫
            string str = HttpRequestHelp.RequestUrl.GetUrlAsync(url).Result;
            JObject json1 = (JObject)JsonConvert.DeserializeObject(str);
            if (json1["session_key"] == null || json1["openid"] == null)
            {
                ro.code = "3";
                ro.msg = "獲取session_key失敗!";
            }
            else
            {
                sessionKey = json1["session_key"].ToString();
                openid = json1["openid"].ToString();
            }
            if (!string.IsNullOrEmpty(sessionKey) && !string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(iv))
            {
                // 傳輸的數據有變化,必須處理,不然FromBase64String 報錯
                text = text.Replace("%", "").Replace(",", "").Replace(" ", "+");
                sessionKey = sessionKey.Replace("%", "").Replace(",", "").Replace(" ", "+");
                iv = iv.Replace("%", "").Replace(",", "").Replace(" ", "+");
                string result = "";
                using (Aes aesAlg = Aes.Create())
                {
                    try
                    {
                        aesAlg.Key = Convert.FromBase64String(sessionKey);
                        aesAlg.IV = Convert.FromBase64String(iv);
                        aesAlg.Mode = CipherMode.CBC;
                        aesAlg.Padding = PaddingMode.PKCS7;
                        //aesAlg.BlockSize = 128; //這里記得千萬不安裝官網的說明加上,不然解析出亂碼
                        ICryptoTransform decryptor = aesAlg.CreateDecryptor();

                        // Create the streams used for decryption.
                        using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(text)))
                        { 
                            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                            {
                                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                                {
                                    result = srDecrypt.ReadToEnd();
                                    JObject json3 = (JObject)JsonConvert.DeserializeObject(result);
                                    if (json3["purePhoneNumber"] != null)
                                    {
                                        ro.code = "0";
                                        ro.data = new
                                        {
                                            phone = json3["purePhoneNumber"].ToString(),
                                            openid = openid
                                        };
                                        return Json(ro);
                                    }
                                }
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        ro.code = "4";
                        ro.msg = "系統異常!";
                        if (aesAlg != null)
                            aesAlg.Clear();
                    }
                    finally
                    {
                        if (aesAlg != null)
                            aesAlg.Clear();
                    }

                }
            }
            return Json(ro);
        }


免責聲明!

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



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