C# 微信公众号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;namespace Web
{
    public partial class Test : System.Web.UI.Page
    {
        //用户id
        public string openid = "";

        //公众号信息部分
        public string appid = ConfigurationManager.AppSettings["AppId"];
        public string appsecret = ConfigurationManager.AppSettings["AppSecret"];

        public string redirect_uri = HttpUtility.UrlEncode("需返回的URL");

        #region 显示页面
        public string accesstoken;
        public string nickname;
        public string sex;
        public string headimgurl;
        public string province;
        public string country;
        public string language;
        public string city;

        public string privilege = "";

        public string errorMsg = "";
        public string errorUrl = "";
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            // 微信官方文档
            // https://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
            // /* *微信认证获取openid部分: *临时认证code */
            string code = Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                //判断session不存在
                if (Session["openid"] == null)
                {
                    //认证第一步:重定向跳转至认证网址
                    // 1.snsapi_base 不弹出授权页面,直接跳转,只能获取用户openid
                    string urlbase = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123#wechat_redirect", appid, redirect_uri);
                    // 2.snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
                    string usrinfo = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect", appid, redirect_uri);

                    Response.Redirect(urlbase);
                }
                //判断session存在
                else
                {
                    //跳转到前端页面.aspx
                    Response.Redirect(Request.Url.ToString());
                }
                return;
            }
            //第三步 获得openid
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appsecret, code);
            string result = HttpHelper.GetResponse(url);
            Log.Instance.SaveLog(result);
            JObject outputObj = JObject.Parse(result);
            if (outputObj["errmsg"] != null)
            {
                errorMsg = outputObj["errmsg"].ToString();
                errorUrl = url;
                return;
            }
            accesstoken = outputObj["access_token"].ToString();
            openid = outputObj["openid"].ToString();

            GetUserInfo(openid);//通过基础接口获取数据, 不弹出授权页面
            GetUserInfo(accesstoken, openid);//通过授权页面获取信息, 会弹出确认页面,需要第一步传入userinfo
        }

        /// <summary>
        /// 通过基础接口获取用户信息
        /// </summary>
        public void GetUserInfo( string openid )
        {
            //第一步 获取基础支持access_token
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);
            string result = HttpHelper.GetResponse(url);
            Log.Instance.SaveLog(result);
            JObject outputObj = JObject.Parse(result);
            if (outputObj["errmsg"] != null)
            {
                errorMsg = outputObj["errmsg"].ToString();
                errorUrl = url;
                return;
            }
            string token = outputObj["access_token"].ToString();

            //第二步 获取用户基本信息
            url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}", token, openid);
            result = HttpHelper.GetResponse(url);
            Log.Instance.SaveLog(result);
            outputObj = JObject.Parse(result);
            if (outputObj["errmsg"] != null)
            {
                errorMsg = outputObj["errmsg"].ToString();
                errorUrl = url;
                return;
            }

            //以下是第四步获得的信息: 
            nickname = outputObj["nickname"].ToString(); //昵称
            sex = outputObj["sex"].ToString()=="1"?"":""; //性别什么的
            headimgurl = outputObj["headimgurl"].ToString(); //头像url
            province = outputObj["province"].ToString();
            country = outputObj["country"].ToString(); ;
            language = outputObj["language"].ToString(); ;
            city = outputObj["city"].ToString(); ;
            //将获得的用户信息填入到session中
            Session["openid"] = outputObj["openid"];            
        }

        /// <summary>
        /// 通过网页授权方式获取用户信息
        /// </summary>
        public void GetUserInfo(string token, string openid)
        {
            //微信认证部分:第四步 获得更多信息
            string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accesstoken, openid);
            string result = HttpHelper.GetResponse(url);
            Log.Instance.SaveLog(result);
            JObject outputObj = JObject.Parse(result);//将json转为数组

            if (outputObj["errmsg"] != null)
            {
                errorMsg = outputObj["errmsg"].ToString();
                errorUrl = url;
                return;
            }

            //以下是第四步获得的信息: 
            nickname = outputObj["nickname"].ToString(); //昵称
            sex = outputObj["sex"].ToString(); //性别什么的
            headimgurl = outputObj["headimgurl"].ToString(); //头像url
            province = outputObj["province"].ToString(); ;
            country = outputObj["country"].ToString(); ;
            language = outputObj["language"].ToString(); ;
            city = outputObj["city"].ToString(); ;
            //将获得的用户信息填入到session中
            Session["openid"] = outputObj["openid"];
            //转向回入口
            //OpenAccess();
        }

    }

}

 

C# 微信公众号

上一篇:微信开发node


下一篇:8 HTTP 的请求方法