code 參數(回調頁面 QueryString)。https://api.weixin.qq.com/sns/oauth2/access_token?appid=...&secret=...&code=...&grant_type=authorization_code。openid。public static string GetOpenId(string code) {
string url = $"{WxConfig.OAuthUrl}?appid={WxConfig.AppId}&secret={WxConfig.AppSecret}&code={code}&grant_type=authorization_code";
string json = HttpGet(url); // 封裝 HttpWebRequest
// 方式一:Newtonsoft.Json 反序列化
var obj = JsonConvert.DeserializeObject(json);
return obj?.openid;
// 方式二:簡易字符串截取(不推薦生產)
// int i = json.IndexOf("\"openid\":\"");
// return i > 0 ? json.Substring(i + 10, json.IndexOf('"', i + 10) - i - 10) : null;
}
public static string HttpGet(string url) {
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
using (var resp = (HttpWebResponse)req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new StreamReader(stream, Encoding.UTF8))
return reader.ReadToEnd();
}
class WxTokenResult {
public string access_token { get; set; }
public int expires_in { get; set; }
public string refresh_token { get; set; }
public string openid { get; set; }
public string scope { get; set; }
}
errcode)。