首页 > 其他分享 >开发日志:企业微信实现扫码登录(WEB)

开发日志:企业微信实现扫码登录(WEB)

时间:2023-10-08 18:22:06浏览次数:87  
标签:WEB 扫码 string url 微信 builder AppendLine System using

一:获取扫码登陆所需的参数: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)效果图:

 

 


 

标签:WEB,扫码,string,url,微信,builder,AppendLine,System,using
From: https://www.cnblogs.com/luomingui/p/17749840.html

相关文章

  • Zabbix监控web网页登录
    1.web监控需求以zabbix-UI页面的登录监控,模拟登录,输入账号密码,实现首页的健康监控。1.模拟登录输入zabbix账号密码,登录后台,如果登录失败就报警2.基于响应状态码判断非200即报警2.配置步骤2.1抓取HTTP数据包既然是模拟登录,先抓包,查看zabbix登录的数据提交,通过浏览器开......
  • 微信审核趋严,小程序引流需要配一个小程序化App
    随着全球小程序技术的发展,加上这几年微信在国内大力发展小程序应用生态,微信小程序的生态达到了近几年来发展的巅峰:据对公开资料进行统计,2021年全网小程序数量已超700万,其中微信小程序开发者突破300万,小程序DAU已超4.5亿;日均使用次数同比增长32%,活跃小程序则增长41%,小程序生态已塑造......
  • 【webapp】 JSP 的常见语法元素
    1.注释: JSP支持三种类型的注释:HTML注释、JSP注释和Java注释。HTML注释:使用 <!--注释内容--> 来添加HTML注释。JSP注释:使用 <%--注释内容--%> 来添加JSP注释。Java注释:使用 // 或 /**/ 来添加Java注释。2.声明: 使用 <%!声明代码%> 来定义......
  • web DevOps / shell d3 / case
    s案例1:中断及退出案例2:基于case分支编写脚本案例3:编写一键部署软件脚本案例4:启动脚本案例5:使用Shell函数案例6:字符串处理案例7:字符串初值的处理1案例1:中断及退出1.1问题本案例要求编写两个Shell脚本,相关要求如下:从键盘循环取整数(0结束)并求和,输出最终结果1.2方......
  • 【webapp】JSP工作原理和过程
    JSP编译:当客户端请求访问一个JSP页面时,Web服务器首先检查是否已经编译过该JSP页面。如果没有编译过或者源文件已更改,服务器会将JSP文件编译成一个Servlet源文件。Servlet编译:编译后的Servlet源文件进一步被编译成Java字节码文件,这个过程由服务器的JSP引擎完......
  • .net6 webapi 项目注册为windows 服务后访问静态文件
    直接使用kestrel运行程序时,只需要http://localhost:port/file.html即可访问,但是将程序注册为windows服务后,http://localhost:port/file.html会报404的错误,此时要访问到这个文件,http://localhost:port/wwwroot/file.html才行,如果想要windows服务和web的url一致只需要加......
  • [网鼎杯 2020 朱雀组]phpweb
    原理反序列化命令执行call_user_func解题过程首先进入靶场莫名其妙报了个错,翻译一下是date()函数的问题--不管了,先看页面原代码看到这里有自动post请求,数据时func=date&p=Y-m-dh:i:sa,看格式像是传入一个函数和参数,那就试试使用func=system&p=ls却发现过滤了,尝试了很多......
  • Sovit2D在线组态设计 构建LNG加气站Web Scada控制系统
    前言天然气是最清洁的化石能源,天然气使用安全、应用广泛,在炊事、供热、发电、交通等领域扮演重要角色。LNG(液化天然气)作为一种市场化的全球能源,能够很好的解决天然气的可及性问题。建设背景在LNG行业迅速发展的同时,加气站的监管难度加大,加之许多地方管理工作相对薄弱滞后、控......
  • 微信小程序的附件上传与预览
    微信小程序的附件上传与预览文件与图片上传wx.chooseMessageFile({count:10,type:'file',success(res){//tempFilePath可以作为img标签的src属性显示图consttempFilePaths=res.tempFiles;varwjpath=tempFilePat......
  • JavaWeb开发
    1.学习路线前端:HTML,CSS,JS--Ajax,Axios--Vue,Element--前端工程化后端:Maven,SpringBoot开发,Mysql,JDBCWEB案例,会话跟踪技术,AOP,SpringBoot原理需求分析,表结构设计。接口文档,功能实现,测试2.Web:万维网(WorldWideWeb)......