Net 版本企业微信认证,直接拷贝就能使用

从企业号里面的应用进入第三方web的时候,如何获取你在这个企业号里面的账号信息

第一步,在应用的连接里面配置你的地址

把微信菜单地址改成这个 https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信WebAPPID&redirect_uri=你要进入的网站&response_type=code&scope=snsapi_base&state=st#wechat_redirect


然后在你的网站加配置

<add key="appid" value="xxxxxxxxxxx"/>
    <add key="secret" value="xxxxxxx"/>
    <add key="DomainUserPrefix" value="域名"/>

    <add key="NewRedirectUrl" value="与上面那个你要进入的网站一致,用来做错误重试"/>


然后在页面第一句代码调用这个

//微信认证

            WXBusiness.ValidateWxLogin();


然后调用这个获取登陆人的账号

WXBusinesss.GetUserCode();


具体看效果

 protected void Page_Load(object sender, EventArgs e)
        {
            string userAgent = HttpContext.Current.Request.UserAgent;
            if (userAgent.ToLower().Contains("micromessenger") == false)
            {
                Response.Write("请在微信浏览器中访问此页面。");
                Response.End();
            }
            //微信认证
            WXBusiness.ValidateWxLogin();
            //登陆用户
            string loginUser=WXBusiness.GetUserCode();
            
        }


下面就是WXBusiness类代码,拷贝过去直接使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Web;
using System.Configuration;

namespace BRC.Workflow.Portal.Lib.Utility
{
    public class WXBusiness
    {
        /// <summary>
        /// 登陆用户
        /// </summary>
        public static string LoginKey = "ADForWebApp";
        /// <summary>
        /// 异常
        /// </summary>
        public static string ErrorKey = "LoginError";
        /// <summary>
        /// 失败重试次数
        /// </summary>
        public static int ErrorCount = 3;


        public static string GetUserCode() {
            if (HttpContext.Current.Session[WXBusiness.LoginKey] == null)
            {
                HttpContext.Current.Response.Write("登录失效,请重新登录。");
                HttpContext.Current.Response.End();
            }
            return HttpContext.Current.Session[WXBusiness.LoginKey].ToString();
        }

        public static void ValidateWxLogin()
        {
            if (HttpContext.Current.Session[LoginKey] != null)
            {
                return;
            }
            string code = HttpContext.Current.Request.QueryString["code"];
            if (HttpContext.Current.Session[LoginKey] == null && string.IsNullOrEmpty(code))
            {
                FileLog.Log("Session用户:无数据");
                HttpContext.Current.Response.Write("用户未登陆。");
                HttpContext.Current.Response.End();
            }
            FileLog.Log("进入微信认证:" + code);

            bool result = GetWXUserCode(code);
            FileLog.Log("微信认证结果:" + result);
            if (result == false)
            {
                int errorCount=0;
                if (HttpContext.Current.Session[ErrorKey] == null)
                {
                    errorCount = 1;
                }
                else {
                    errorCount = Convert.ToInt32(HttpContext.Current.Session[ErrorKey])+1;
                }
                HttpContext.Current.Session[ErrorKey] = errorCount;
                if (errorCount > ErrorCount)
                {
                    HttpContext.Current.Response.Write("失败重试次数超过"+ErrorCount+"次,请联系管理员检查您的账号是否异常。");
                    HttpContext.Current.Response.End();
                }
                FileLog.Log("微信认证失败开始第" + errorCount + "次重试");
                string url = 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", ConfigurationManager.AppSettings["appid"], ConfigurationManager.AppSettings["NewRedirectUrl"], Guid.NewGuid().ToString());
                HttpContext.Current.Response.Redirect(url);
            }
        }
        public static bool GetWXUserCode(string code)
        {

            string adCode = "";
            //获取数据中的token
            string token = HttpContext.Current.Application["WXToken"] as string;
            FileLog.Log("服务器Token:" + token);
            while (true)
            {
                #region 获取token

                if (string.IsNullOrEmpty(token))
                {
                    token = GetWXTokenForAPI();
                    FileLog.Log("微信Token:" + token);
                    if (string.IsNullOrEmpty(token))
                    {
                        break;
                    }
                    HttpContext.Current.Application["WXToken"] = token;
                }
                #endregion
                //获取域账户
                string errorMsg = "";
                adCode = GetWXUserCodeForAPI(code, token, out errorMsg);
                FileLog.Log("微信AD:" + adCode);
                FileLog.Log("微信ADMesg:" + errorMsg);
                if (!string.IsNullOrEmpty(adCode))
                {
                    FileLog.Log("用户获取成功。");
                    break;
                }
                if (errorMsg.Contains("40029"))
                {
                    FileLog.Log("用户获取失败,准备重试。");
                    break;
                }
                if (errorMsg.Contains("40014"))
                {
                    token = "";
                    FileLog.Log("Token失效,准备重试。");
                    continue;
                }

                break;
            }
            FileLog.Log("用户Code:" + adCode);
            if (!string.IsNullOrEmpty(adCode))
            {
                FileLog.Log("用户存入Session。");
                HttpContext.Current.Session[LoginKey] = ConfigurationManager.AppSettings["DomainUserPrefix"] + "\\" + adCode;
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获取微信用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private static string GetWXUserCodeForAPI(string code, string token, out string msg)
        {
            string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", token, code);

            var client = new System.Net.WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            string data = client.DownloadString(url);
            msg = data;

            var tokenModel = JsonConvert.DeserializeObject<TokenModel>(data);

            return tokenModel.UserId;
        }
        /// <summary>
        /// 获取微信Token
        /// </summary>
        /// <returns></returns>
        private static string GetWXTokenForAPI()
        {
            var appid = ConfigurationManager.AppSettings["appid"];
            var secret = ConfigurationManager.AppSettings["secret"];
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", appid, secret);
            var client = new System.Net.WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            string data = client.DownloadString(url);

            var tokenModel = JsonConvert.DeserializeObject<TokenModel>(data);

            return tokenModel.access_token;
        }
        public class TokenModel
        {
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public int errcode { get; set; }
            public string errmsg { get; set; }
            public string UserId { get; set; }
        }
    }
}

再加一个日志文件类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace BRC.Workflow.Portal.Lib.Utility
{
    public class FileLog
    {
        public static void Log(string content)
        {
            //日志文件夹
            string logDir = HttpContext.Current.Server.MapPath("~/Logs");
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            string filePath = logDir + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            FileStream fs = new FileStream(filePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + content + "\r\n");
            sw.Flush();
            sw.Close();
            fs.Close();
        }
    }
}






阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭