


This article mainly introduces .NET C# to use WeChat public account to log in to the website, and teaches you to use WeChat public account to log in to the website. Interested friends can refer to it
Applicable to: This article is applicable to Users with a certain WeChat development foundation
Introduction:
After spending 300 oceans to apply for the WeChat public platform, I found that I could not use the WeChat public account to log in to the website (not opened by WeChat) to obtain WeChat account number. After careful study, I found out that I have to spend another 300 yuan to apply for the WeChat open platform to log in to the website. So as a loser programmer, I thought of making a login interface myself.
Tools and environment:
1. VS2013 .net4.0 C# MVC4.0 Razor
2. Plug-in
A. Microsoft.AspNet.SignalR ;Get background data all the time
B.Gma.QrCodeNet.Encoding;Text generation QR code
Goal achieved
1. Open the website login page on the computer, prompt Users use WeChat to scan and log in to confirm.
2. After the user scans and confirms via WeChat, the computer automatically receives the confirmation message and jumps to the website homepage.
Principle Analysis
1.SignalR is a magical tool that can send information from browser A to the server, and the server automatically pushes the message to the specified browser B. Then my plan is to use a computer browser to open the login page, generate a QR code (the content is the URL with the user authorization of the WeChat public platform web page), and use WeChat's code scanning function to open the website. Send the obtained WeChat user OPENID to the computer browser through SignalR to implement the login function
Implementation process
1. Registration and permissions of the WeChat public platform (skip ...)
2. Create a new MVC website in VS2013. The environment I use is .NET4.0 C# MVC4.0 Razor engine (personal habit).
3. Install SignalR
VS2013 Click Tools==> Library Package Manager==> Package Management Console
Enter the following command:
Install-Package Microsoft.AspNet.SignalR -Version 1.1.4
.net4.0 It is recommended to install 1.1.4 high in Mvc4 environment The version cannot be installed
Installed SingnalR successfully
Set up SignalR
var config = new Microsoft.AspNet.SignalR.HubConfiguration();
config.EnableCrossDomain = true;
RouteTable.Routes.MapHubs(config);
Create a new class PushHub.cs
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WD.C.Utility { /// <summary> /// 标注Single javascription要连接的名称 /// </summary> [HubName("pushHub")] public class PushHub : Hub { /// <summary> /// 临时保存请求的用户 /// </summary> static Dictionary<string, string> rlist = new Dictionary<string, string>(); /// <summary> /// 登录请求的用户;打开Login页执行本方法,用于记录浏览器连接的ID /// </summary> public void ruserConnected() { if (!rlist.ContainsKey(Context.ConnectionId)) rlist.Add(Context.ConnectionId, string.Empty); //Client方式表示对指定ID的浏览器发送GetUserId方法,浏览器通过javascrip方法GetUserId(string)得到后台发来的Context.ConnectionId Clients.Client(Context.ConnectionId).GetUserId(Context.ConnectionId); } /// <summary> /// 实际登录的用户 /// </summary> /// <param name="ruser">请求的用户ID</param> /// <param name="logUserID">微信OPENID</param> public void logUserConnected(string ruser, string logUserID) { if (rlist.ContainsKey(ruser)) { rlist.Remove(ruser); //Client方式表示对指定ID的浏览器发送GetUserId方法,浏览器通过javascrip方法userLoginSuccessful(bool,string)得到后台发来的登录成功,和微信OPENID Clients.Client(ruser).userLoginSuccessful(true, logUserID); } } } }
Create a new MVC controller "LoginController.cs", this will not read other tutorials;
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WD.C.Controllers { public class LoginController : Controller { // // GET: /Login/ /// <summary> /// 登录主页,电脑端打开 /// </summary> /// <returns></returns> public ActionResult Index() { /*参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN *1.URL用于生成二维码给微信扫描 *2.格式参考微信公从平台帮助 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。 *3.REDIRECT_URI内容为返回地址,需要开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名 *4.REDIRECT_URI应回调到WxLog页并进行URLEncode编码,如: redirect_uri=GetURLEncode("http://你的网站/Login/WxLog?ruser="); ruser为PushHub中的Context.ConnectionId到View中配置 * */ ViewBag.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", B.Helper.AppID, GetURLEncode("http://你的网站/Login/WxLog?ruser="), Guid.NewGuid()); return View(); } /// <summary> /// 登录确认页,微信端打开 /// </summary> /// <param name="ruser"></param> /// <returns></returns> public ActionResult WxLog(string ruser) { //使用微信登录 if (!string.IsNullOrEmpty(code)) { string loguser= B.Helper.GetOpenIDByCode(code); Session["LogUserID"] =loguser; ViewBag.LogUserID = loguser; } ViewBag.ruser = ruser; return View(); } } }
Control The device "QRController.cs" is used to generate QR codes from text
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WD.C.Controllers { public class QRController : Controller { // // GET: /QR/ public ActionResult Index() { return View(); } /// <summary> /// 获得2维码图片 /// </summary> /// <param name="str"></param> /// <returns></returns> public ActionResult GetQRCodeImg(string str) { using (var ms = new System.IO.MemoryStream()) { string stringtest = str; GetQRCode(stringtest, ms); Response.ContentType = "image/Png"; Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length); System.Drawing.Bitmap img = new System.Drawing.Bitmap(100, 100); img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); Response.End(); return File(ms.ToArray(), @"image/jpeg"); } } private static bool GetQRCode(string strContent, System.IO.MemoryStream ms) { Gma.QrCodeNet.Encoding.ErrorCorrectionLevel Ecl = Gma.QrCodeNet.Encoding.ErrorCorrectionLevel.M; //误差校正水平 string Content = strContent;//待编码内容 Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules QuietZones = Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules.Two; //空白区域 int ModuleSize = 12;//大小 var encoder = new Gma.QrCodeNet.Encoding.QrEncoder(Ecl); Gma.QrCodeNet.Encoding.QrCode qr; if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵 { var render = new Gma.QrCodeNet.Encoding.Windows.Render.GraphicsRenderer(new Gma.QrCodeNet.Encoding.Windows.Render.FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, System.Drawing.Imaging.ImageFormat.Png, ms); } else { return false; } return true; } } }
View opens SignalR
var chat = $.connection.pushHub;
$.connection.hub.start() .done(function () {
chat.server.ruserConnected();
});
$.connection.pushHub corresponds to
chat.server.ruserConnected(); corresponding to
means calling "pushHub" and executing the runserConnected method after running , add the current browser’s ConnectionID
chat.client.getUserId = function (ruserid) { //二维码生成的文本 $("#loga").attr("src", "@ViewBag.Url" + ruserid); }
in the temporary table to represent the background data
Return to the tour after receiving the data
chat.client.userLoginSuccessful = function (r, userid) { if (r) { $.post("/Login/AddSession/", { userid: userid }, function (r2) { if (r2) { location.href = "/Home/"; } }) } };
After the user logs in through WeChat
Receives WeChat OpenID
$.post("/Login/AddSession/ ", { userid: userid }, function (r2) {
if (r2) {
location.href = "/Home/";
}
})
Execute Post to add login information in the background. After success, go to /Home/Homepage
/// <summary> /// 保存微信确认登录后返回的OPENID,做为网站的Session["LogUserID"] /// </summary> /// <param name="userid"></param> /// <returns></returns> public JsonResult AddSession(string userid) { Session["LogUserID"] = userid; return Json(true); }
Login/WxLog.cshtml This page is opened on WeChat
@{ ViewBag.Title = "WxLog"; } <script src="~/Scripts/jquery.signalR-1.1.4.min.js"></script> <script src="~/signalr/hubs"></script> <script> $(function () { //连接SignalR pushHab var chat = $.connection.pushHub; //启动 $.connection.hub.start().done(); $("#btnLog").click(function () { //登录,发送信息到服务器 chat.server.logUserConnected("@ViewBag.ruser","@ViewBag.LogUserID"); }); }); </script> <h2 id="WxLog">WxLog</h2> <a href="#" id="btnLog">登录</a> @{ ViewBag.Title = "Index"; } @Scripts.Render("~/bundles/jquery") <script src="~/Scripts/jquery.signalR-1.1.4.min.js"></script> <script src="~/signalr/hubs"></script> <script type='text/javascript'> $(function () { var chat = $.connection.pushHub; $.connection.hub.start().done(function () { chat.server.ruserConnected(); }); chat.client.getUserId = function (ruserid) { $("#loga").attr("src", "@ViewBag.Url" + ruserid); } chat.client.userLoginSuccessful = function (r, userid) { if (r) { location.href = "/Home/"; }) } }; }); </script> <header> <a href="~/Home/" class="iconfont backIcon"><</a> <h1 id="用户登录">用户登录</h1> </header> <p style="height:1rem;"></p> 请使用微信登录扫描以下二维码生产图片 <p> <img src="/static/imghwm/default1.png" data-src="#" class="lazy" id="loga" style="max-width:90%" / alt=".NET C# Example analysis of using WeChat official account to log in to the website" > </p>
GetOpenIDByCode(code) method
For users who have followed the official account, if the user enters the official account's web authorization page from the official account's session or custom menu, even if the scope is snsapi_userinfo, It is also a silent authorization, without the user being aware of it.
具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
public static string GetOpenIDByCode(string code) { 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); using (System.Net.WebClient client = new System.Net.WebClient()) { string tempstr= client.DownloadString( url); var regex= new Regex(@"\""openid\"":\""[^\""]+?\"",", RegexOptions.IgnoreCase); string tempstr2= regex.Match(tempstr).Value; return tempstr2.Substring(10, tempstr2.Length - 12); } }
The above is the detailed content of .NET C# Example analysis of using WeChat official account to log in to the website. For more information, please follow other related articles on the PHP Chinese website!

如何使用C#编写时间序列预测算法时间序列预测是一种通过分析过去的数据来预测未来数据趋势的方法。它在很多领域,如金融、销售和天气预报中有广泛的应用。在本文中,我们将介绍如何使用C#编写时间序列预测算法,并附上具体的代码示例。数据准备在进行时间序列预测之前,首先需要准备好数据。一般来说,时间序列数据应该具有足够的长度,并且是按照时间顺序排列的。你可以从数据库或者

如何使用Redis和C#开发分布式事务功能引言分布式系统的开发中,事务处理是一项非常重要的功能。事务处理能够保证在分布式系统中的一系列操作要么全部成功,要么全部回滚。Redis是一种高性能的键值存储数据库,而C#是一种广泛应用于开发分布式系统的编程语言。本文将介绍如何使用Redis和C#来实现分布式事务功能,并提供具体代码示例。I.Redis事务Redis

如何实现C#中的人脸识别算法人脸识别算法是计算机视觉领域中的一个重要研究方向,它可以用于识别和验证人脸,广泛应用于安全监控、人脸支付、人脸解锁等领域。在本文中,我们将介绍如何使用C#来实现人脸识别算法,并提供具体的代码示例。实现人脸识别算法的第一步是获取图像数据。在C#中,我们可以使用EmguCV库(OpenCV的C#封装)来处理图像。首先,我们需要在项目

如何使用C#编写动态规划算法摘要:动态规划是求解最优化问题的一种常用算法,适用于多种场景。本文将介绍如何使用C#编写动态规划算法,并提供具体的代码示例。一、什么是动态规划算法动态规划(DynamicProgramming,简称DP)是一种用来求解具有重叠子问题和最优子结构性质的问题的算法思想。动态规划将问题分解成若干个子问题来求解,通过记录每个子问题的解,

Redis在C#开发中的应用:如何实现高效的缓存更新引言:在Web开发中,缓存是提高系统性能的常用手段之一。而Redis作为一款高性能的Key-Value存储系统,能够提供快速的缓存操作,为我们的应用带来了不少便利。本文将介绍如何在C#开发中使用Redis,实现高效的缓存更新。Redis的安装与配置在开始之前,我们需要先安装Redis并进行相应的配置。你可以

如何实现C#中的图像压缩算法摘要:图像压缩是图像处理领域中的一个重要研究方向,本文将介绍在C#中实现图像压缩的算法,并给出相应的代码示例。引言:随着数字图像的广泛应用,图像压缩成为了图像处理中的重要环节。压缩能够减小存储空间和传输带宽,并能提高图像处理的效率。在C#语言中,我们可以通过使用各种图像压缩算法来实现对图像的压缩。本文将介绍两种常见的图像压缩算法:

当今人工智能(AI)技术的发展如火如荼,它们在各个领域都展现出了巨大的潜力和影响力。今天大姚给大家分享4个.NET开源的AI模型LLM相关的项目框架,希望能为大家提供一些参考。https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel是一种开源的软件开发工具包(SDK),旨在将大型语言模型(LLM)如OpenAI、Azure


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
