1. 在页面中引导用户进入微信授权页面:(将回调页面通过URL参数传递到微信的授权页,并跳转)

string wxAuthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                   "?appid=" + wxAppId + //微信公众号的AppId
                   "&redirect_uri=" + wxRedirectUri + //回调页面地址
                   "&response_type=code" +
                   "&scope=snsapi_userinfo" +
                   "&state=STATE" +
                   "&connect_redirect=1#wechat_redirect";

授权页面.png


2. 在微信中点击确认之后,会回调我们指定的页面,回调之后的页面的url会自动加上code参数


3. 在回调页面中抓取以下地址的网页内容,页面地址要拼接上code参数

string wxGetOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=" + wxAppId + //微信公众号的AppId
                        "&secret=" + wxAppSecret + //微信公众号的AppSecret
                        "&code={0}" + //回调页面上的code参数
                        "&grant_type=authorization_code";


4. 抓取的结果是一串JSON字符串,JSON字符串中包含了用户的OpenId(网上有文章说JSON中也包含unionId,这里亲测之后未发现有unionId)

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}


附件内容是可以调用的Helper类:

WeChatHelper.zip


代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using Whir.Framework;
/// <summary>
/// WeChatHelper 的摘要说明
/// </summary>
public class WeChatHelper
{
    public static string GetUserOpenId()
    {
        //判断通过微信访问
        if (HttpContext.Current.Request.UserAgent.Contains("MicroMessenger"))
        {
            string wxAppId = AppSettingUtil.GetString("AppId");
            string wxAppSecret = AppSettingUtil.GetString("AppSecret");
            string wxRedirectUri = AppSettingUtil.GetString("WxRedirectUri");
            string wxAuthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                               "?appid=" + wxAppId +
                               "&redirect_uri=" + wxRedirectUri +
                               "&response_type=code" +
                               "&scope=snsapi_userinfo" +
                               "&state=STATE" +
                               "&connect_redirect=1#wechat_redirect";
            
            string wxGetOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                                    "?appid=" + wxAppId +
                                    "&secret=" + wxAppSecret +
                                    "&code={0}" +
                                    "&grant_type=authorization_code"; 
            string wxCode = RequestUtil.Instance.GetQueryString("code");
            if (wxCode.IsEmpty())
            {
                //跳转到微信授权页面
                HttpContext.Current.Response.Redirect(wxAuthUrl);
            }
            else
            {
                wxGetOpenIdUrl = wxGetOpenIdUrl.FormatWith(wxCode);
                string wxResponse = GetPageResponse(wxGetOpenIdUrl);
                WxResponse response = new JavaScriptSerializer().Deserialize<WxResponse>(wxResponse);
                if (response != null)
                    return response.openid;
            }
        }
        return "";
    }
    /// <summary>
    /// 获取网页响应的内容
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string GetPageResponse(string url)
    {
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultCredentials;
        //网页编码格式
        Encoding encoding = Encoding.UTF8;
        //抓取的网页地址
        Byte[] data = wc.DownloadData(url);
        //最终获取网页源代码字符串
        string result = encoding.GetString(data);
        return result;
    }
}
/// <summary>
/// 微信返回openid时为JSON字符串,这里用实体反序列化,取其中的openid
/// </summary>
public class WxResponse
{
    public string access_token { get; set; }
    public string expires_in { get; set; }
    public string refresh_token { get; set; }
    public string openid { get; set; }
    public string scope { get; set; }
}