欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MVC微信网页授权获取用户OpenId

程序员文章站 2023-11-30 09:15:40
最近开发微信公众平台,做下记录,以前也开发过,这次开发又给忘了,搞了半天,还是做个笔记为好。  注意框架为mvc 开发微信公众平台。场景为,在模板页中获取用...

最近开发微信公众平台,做下记录,以前也开发过,这次开发又给忘了,搞了半天,还是做个笔记为好。 

注意框架为mvc 开发微信公众平台。场景为,在模板页中获取用户openid,想要进行验证的页面,集成模板页就可以了。 

在_layout.cshtml中加入如下代码 

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>@viewbag.title - my asp.net application</title>
  @styles.render("~/content/css")
  @scripts.render("~/bundles/modernizr")
  @{
    var code = httpcontext.current.request["code"];
    log.logmsg(code);
    string urlpath = httpcontext.current.request.url.absoluteuri.tostring();
    viewbag.at = adminutil.getopenid(urlpath, code);
  }
</head> 

类adminutil中加入getopenid方法 

#region 获取openid
    /// <summary>
    /// 获取openid
    /// </summary>
    public static string getopenid(string redirect_url, string code)
    {
      string appid = wxmodel.appid;
      string appsecret = wxmodel.appsecret;
      string openid = "";
      openid = wxapi.getopenid(appid, redirect_url, code, appsecret);
      return openid;
    }
    #endregion 

类wxapi中加入getopenid方法 

 #region 获取openid
    /// <summary>
    /// 获取openid
    /// </summary>
    public static string getopenid(string appid, string redirect_url, string code, string screct)
    {
      string strjson = "";
      if (string.isnullorempty(code))
      {
        redirect_url = httputility.urlencode(redirect_url);
        httpcontext.current.response.redirect(string.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect",
          appid, redirect_url, new random().next(1000, 200000).tostring()));
      }
      else
      {
        strjson = httprequestutil.requesturl(string.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
        appid, screct, code));
      }
      return tools.getjsonvalue(strjson, "openid");
    }
    #endregion
public static class wxmodel
  {
    public static string access_token;
    public static string appid;
    public static string appsecret;
  } 
 /// <summary>
  /// 工具类
  /// </summary>
  public class tools
  {
    #region 获取json字符串某节点的值
    /// <summary>
    /// 获取json字符串某节点的值
    /// </summary>
    public static string getjsonvalue(string jsonstr, string key)
    {
      string result = string.empty;
      if (!string.isnullorempty(jsonstr))
      {
        key = "\"" + key.trim('"') + "\"";
        int index = jsonstr.indexof(key) + key.length + 1;
        if (index > key.length + 1)
        {
          //先截逗号,若是最后一个,截“}”号,取最小值
          int end = jsonstr.indexof(',', index);
          if (end == -1)
          {
            end = jsonstr.indexof('}', index);
          }

          result = jsonstr.substring(index, end - index);
          result = result.trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
        }
      }
      return result;
    }
    #endregion

  }
public class httprequestutil
  {
    #region 请求url,不发送数据
    /// <summary>
    /// 请求url,不发送数据
    /// </summary>
    public static string requesturl(string url)
    {
      return requesturl(url, "post");
    }
    #endregion

    #region 请求url,不发送数据
    /// <summary>
    /// 请求url,不发送数据
    /// </summary>
    public static string requesturl(string url, string method)
    {
      // 设置参数
      httpwebrequest request = webrequest.create(url) as httpwebrequest;
      cookiecontainer cookiecontainer = new cookiecontainer();
      request.cookiecontainer = cookiecontainer;
      request.allowautoredirect = true;
      request.method = method;
      request.contenttype = "text/html";
      request.headers.add("charset", "utf-8");

      //发送请求并获取相应回应数据
      httpwebresponse response = request.getresponse() as httpwebresponse;
      //直到request.getresponse()程序才开始向目标网页发送post请求
      stream responsestream = response.getresponsestream();
      streamreader sr = new streamreader(responsestream, encoding.default);
      //返回结果网页(html)代码
      string content = sr.readtoend();
      return content;
    }
    #endregion
  } 

注意:需要在微信公众平台中设置授权回调域

MVC微信网页授权获取用户OpenId

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。