首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

.NET 微信網頁授權獲取 OpenID 的完整代碼實現

     編輯:程式設計綜合問答

流程

  1. 獲取 code 參數(回調頁面 QueryString)。
  2. 服務端拼接 URL:https://api.weixin.qq.com/sns/oauth2/access_token?appid=...&secret=...&code=...&grant_type=authorization_code。
  3. HTTP GET 請求,解析返回 JSON 取 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; }
}

注意

  • 需在微信公眾平台配置授權回調域名。
  • 生產環境務必用 JSON 庫解析,並處理錯誤碼(errcode)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved