開發日誌:企業微信實現掃碼登錄(WEB)

一:獲取掃碼登陸所需的參數:appid,secret,agentid

登錄企業微信:https://work.weixin.qq.com/

掃碼登錄文檔:https://work.weixin.qq.com/api/doc/90000/90135/90988

1:獲取appid

點擊我的企業就可以看到企業ID信息,這就是appid

 

2:獲取secret和agentid

(1):點擊應用管理-》點擊創建應用

 

(2):應用創建完成之後我們就可以在應用中看到secret和agentid

2:配置企業微信授權登錄

二:開發企業微信二維碼登錄功能

(1):開發企業微信二維碼登錄頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>企業微信掃碼登錄</title>
    <script src="http://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js"></script>
</head>
<body class="body">
    <div id="wx_reg" style="text-align: center;margin-top: 10%;">

    </div>

	<script>
		var wwLogin = new WwLogin({
			"id": "wx_reg",  
			"appid": "wwee5d37c708b1ecfb",
			"agentid": "1000020",
			"redirect_uri": encodeURIComponent('http://www.xxx.com/login/qywxlogin.ashx?type=qywxLogin'),
			"state": "lmg",
			"href":"",
		});
	</script>
</body>
</html>

(2):開發企業微信二維碼登錄回調  qywxlogin.ashx

<%@ WebHandler Language="C#" Class="qywxlogin" Debug="true" %>

using System;
using System.IO;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

public class qywxlogin : IHttpHandler, IRequiresSessionState
{
    //企業微信
    public string appid = "";
    publi  string secret = "";
    public string PhyPath = "";
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", context.Session.SessionID));
        
        PhyPath = context.Server.MapPath("/");
        string type = context.Request["type"];
        switch(type) {
            case "qywxLogin": qywxLogin(context); break;
            default: context.Response.Write("非法訪問"); break;
        }
        context.Response.End();
    }
    public void qywxLogin(HttpContext c){
    
        string state = c.Request["state"];
        string code = c.Request["code"]; 
    
        string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+appid+"&corpsecret="+secret+"&debug=1";
        var token = HttpGet(url);
        if(!string.IsNullOrEmpty(token)) {
            JObject sk = JObject.Parse(token);
            if(sk["access_token"] != null) {
                string accessToken =sk["access_token"].ToString();
                url ="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken+"&code="+code+"&debug=1";
                var getuserinfo =HttpGet(url);
                JObject sk1 = JObject.Parse(getuserinfo);
                if(sk1["UserId"] != null) {
                    string UserId=sk1["UserId"].ToString(); //企業微信通訊錄裏的賬戶名稱
                    string sql ="select * from [Base_Users] where WeixinID='"+UserId+"'";
                    DataTable dtW = DataBase.ExecuteTable(sql);
                    if(dtW != null && dtW.Rows.Count > 0) {
                        //寫 session
                    }else{
               //綁定頁面 c.Response.Redirect(
"qywxbind.html?WeixinID="+UserId); } }else{ c.Response.Write(getuserinfo); } }else{ c.Response.Write(token); } }else{ c.Response.Write("驗證錯誤"); } } #region GET/POST public string HttpGet(string url) { StringBuilder builder = new StringBuilder(); builder.AppendLine("========================================================="); builder.AppendLine("url:" + url); string retString = string.Empty; try { string errMsg = string.Empty; HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); wbRequest.Method = "GET"; wbRequest.ContentType = "text/html;charset=UTF-8"; HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); using(Stream responseStream = wbResponse.GetResponseStream()) { using(StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"))) { retString = sReader.ReadToEnd(); } } builder.AppendLine(retString); } catch(Exception ex) { builder.AppendLine("errcode:" + ex.HResult); builder.AppendLine("errmsg:" + ex.Message); } LogWeChat(builder.ToString(), "Http"); return retString; } public string HttpPost(string url, string param = "", Dictionary<string, string> header = null,
     string contentType = "application/json") { StringBuilder builder = new StringBuilder(); builder.AppendLine("========================================================="); builder.AppendLine("url:" + url); builder.AppendLine("param:" + param); string data = ""; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = contentType; request.Accept = "*/*"; request.Timeout = 15000; request.AllowAutoRedirect = false; if(header != null && header.Count > 0) { foreach(var item in header) { request.Headers.Add(item.Key, item.Value); } } if(!string.IsNullOrWhiteSpace(param)) { byte[] byteData = UTF8Encoding.UTF8.GetBytes(param.ToString()); request.ContentLength = byteData.Length; using(Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); postStream.Close(); } } using(var response = request.GetResponse()) { StreamReader reader = new StreamReader(response.GetResponseStream()); data = reader.ReadToEnd(); } builder.AppendLine(data); } catch(Exception ex) { builder.AppendLine("errcode:" + ex.HResult); builder.AppendLine("errmsg:" + ex.Message); } LogWeChat(builder.ToString(), "Http"); return data; } #endregion #region Logging public void LogWeChat(string contents, string filename) { try { if(string.IsNullOrWhiteSpace(contents)) return; string msg = string.Format(@"{0}|{1}|" + filename + "|{2}" + Environment.NewLine, DateTime.Now, "", contents); string t = "logs"; string path = PhyPath + t; string logfile = path + "/wechat_" + filename + "_" + DateTime.Now.ToString("yyyyMMdd") + ".log"; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.AppendAllText(logfile, msg); } catch { } } #endregion public bool IsReusable { get { return false; } } }

(3):企業微信二維碼登錄(WEB)效果圖:

 

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章