public AccessTokenModel xcx_Get_Token2() { AjaxResult result = new AjaxResult(); AccessTokenModel AccessTokenModel = new AccessTokenModel(); try { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?appid={0}&secret={1}&grant_type=client_credential", "..............", "....................."); string jsonData = Common.Common.HttpGet(url); JavaScriptSerializer js = new JavaScriptSerializer(); //例項化一個能夠序列化資料的類 AccessTokenModel accesstokenmodel = js.Deserialize<AccessTokenModel>(jsonData); //將json資料轉化為物件型別並賦值給list if (!string.IsNullOrEmpty(accesstokenmodel.access_token)) { AccessTokenModel = accesstokenmodel; } else { AccessTokenModel = new AccessTokenModel(); } } catch (Exception ex) { AccessTokenModel = new AccessTokenModel(); } return AccessTokenModel; } [HttpPost] public JsonResult getPhone(string code) { AjaxResult res = new AjaxResult(); res.state = false; try { string AccessToken = xcx_Get_Token2().access_token;//獲取access_token string _url = string.Format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}", AccessToken); //json引數 string jsonParam = Newtonsoft.Json.JsonConvert.SerializeObject(new { code = code }); var request = (HttpWebRequest)WebRequest.Create(_url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8";//ContentType byte[] byteData = Encoding.UTF8.GetBytes(jsonParam); int length = byteData.Length; request.ContentLength = length; Stream writer = request.GetRequestStream(); writer.Write(byteData, 0, length); writer.Close(); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); //例項化一個能夠序列化資料的類 PhoneModel PhoneInfo = js.Deserialize<PhoneModel>(responseString); res.state = true; res.data = PhoneInfo.phone_info.phoneNumber; } catch (Exception ex) { res.state = false; res.message = ex.Message; } return Json(res, JsonRequestBehavior.AllowGet); }
public class AjaxResult { /// <summary> /// 狀態碼 /// </summary> public object state = false; /// <summary> /// 返回訊息內容 /// </summary> public string message { get; set; } /// <summary> /// 返回資料 /// </summary> public object data { get; set; } public object obj { get; set; } }
public class PhoneModel { public int errcode { get; set; } public string errmsg { get; set; } public Phone_Info phone_info { get; set; } } public class Phone_Info { public string phoneNumber { get; set; } public string purePhoneNumber { get; set; } public int countryCode { get; set; } public Watermarks watermark { get; set; } } public class Watermarks { public int timestamp { get; set; } public string appid { get; set; } }