前端需要注意:(如位元組小程式)
## 注意事項
- 請謹慎使用,僅可在登入時使用!!!若使用者舉報較多或被發現在不必要場景下使用,位元組跳動有權永久回收該小程式的該介面許可權。
- 使用(使用者點選 button)前需先呼叫[tt.login](https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/api/open-interface/log-in/tt-login/)介面。如果在回撥中呼叫 `tt.login` 會重新整理登入態,導致登入後[換取](https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/server/log-in/code-2-session)的 session_key 與手機號碼加密時使用的 session_key 不同,從而導致解密失敗。
- 基礎庫 1.14.0 開始支援
#region 獲取session_key string code=“前端獲取傳入後端”; string encryptedData=“前端傳入後端(加密字串)”; string iv="前端傳入後端(偏移變數)"; string appid = “你的AppID”; string secret =“你的AppSecret”; string url = string.Format("https://developer.toutiao.com/api/apps/jscode2session?appid={0}&secret={1}&code={2}", appid, secret, code); var request = WebRequest.Create(url) as HttpWebRequest; var response = request.GetResponse(); var respStream = response.GetResponseStream(); var res_ = string.Empty; using (var reader = new StreamReader(respStream, Encoding.UTF8)) { res_ = reader.ReadToEnd(); } string session_key = ""; if (res_.Contains("session_key")) { JsonData jd = JsonMapper.ToObject(res_); session_key = (string)jd["session_key"]; } else { ht.Add("code", "0"); ht.Add("message", "session_key未獲取"); return ht; } #endregion string mobile = getPhoneNumber(encryptedData,iv,session_key); if (mobile.Length == 0) { ht.Add("code", "0"); ht.Add("message", "手機號獲取失敗"); return ht; } else{ //獲取成功 } //方法 #region 解密獲取手機號 private string getPhoneNumber(string encryptedData, string IV, string Session_key) { try { byte[] encryData = Convert.FromBase64String(encryptedData); RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Key = Convert.FromBase64String(Session_key); rijndaelCipher.IV = Convert.FromBase64String(IV); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length); string result = Encoding.Default.GetString(plainText); dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic; return model.phoneNumber; } catch (Exception ex) { return ""; } } #endregion
最新評論