


.NET C# Example analysis of using WeChat official account to log in to the website
Apr 25, 2017 am 09:53 AMThis 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頁執(zhí)行本方法,用于記錄瀏覽器連接的ID /// </summary> public void ruserConnected() { if (!rlist.ContainsKey(Context.ConnectionId)) rlist.Add(Context.ConnectionId, string.Empty); //Client方式表示對指定ID的瀏覽器發(fā)送GetUserId方法,瀏覽器通過javascrip方法GetUserId(string)得到后臺發(fā)來的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的瀏覽器發(fā)送GetUserId方法,瀏覽器通過javascrip方法userLoginSuccessful(bool,string)得到后臺發(fā)來的登錄成功,和微信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 若提示“該鏈接無法訪問”,請檢查參數(shù)是否填寫錯誤,是否擁有scope參數(shù)對應的授權作用域權限。 *3.REDIRECT_URI內(nèi)容為返回地址,需要開發(fā)者需要先到公眾平臺官網(wǎng)中的“開發(fā) - 接口權限 - 網(wǎng)頁服務 - 網(wǎng)頁帳號 - 網(wǎng)頁授權獲取用戶基本信息”的配置選項中,修改授權回調(diào)域名 *4.REDIRECT_URI應回調(diào)到WxLog頁并進行URLEncode編碼,如: redirect_uri=GetURLEncode("http://你的網(wǎng)站/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://你的網(wǎng)站/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;//待編碼內(nèi)容 Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules QuietZones = Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules.Two; //空白區(qū)域 int ModuleSize = 12;//大小 var encoder = new Gma.QrCodeNet.Encoding.QrEncoder(Ecl); Gma.QrCodeNet.Encoding.QrCode qr; if (encoder.TryEncode(Content, out qr))//對內(nèi)容進行編碼,并保存生成的矩陣 { 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,做為網(wǎng)站的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 () { //登錄,發(fā)送信息到服務器 chat.server.logUserConnected("@ViewBag.ruser","@ViewBag.LogUserID"); }); }); </script> <h2>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>用戶登錄</h1> </header> <p style="height:1rem;"></p> 請使用微信登錄掃描以下二維碼生產(chǎn)圖片 <p> <img id="loga" src="#" width="90%" /> </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.
具體而言,網(wǎng)頁授權流程分為四步:
1、引導用戶進入授權頁面同意授權,獲取code
2、通過code換取網(wǎng)頁授權access_token(與基礎支持中的access_token不同)
3、如果需要,開發(fā)者可以刷新網(wǎng)頁授權access_token,避免過期
4、通過網(wǎng)頁授權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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

1. The Origin of .NETCore When talking about .NETCore, we must not mention its predecessor .NET. Java was in the limelight at that time, and Microsoft also favored Java. The Java virtual machine on the Windows platform was developed by Microsoft based on JVM standards. It is said to be the best performance Java virtual machine at that time. However, Microsoft has its own little abacus, trying to bundle Java with the Windows platform and add some Windows-specific features. Sun's dissatisfaction with this led to a breakdown of the relationship between the two parties, and Microsoft then launched .NET. .NET has borrowed many features of Java since its inception and gradually surpassed Java in language features and form development. Java in version 1.6

C# multi-threaded programming is a technology that allows programs to perform multiple tasks simultaneously. It can improve program efficiency by improving performance, improving responsiveness and implementing parallel processing. While the Thread class provides a way to create threads directly, advanced tools such as Task and async/await can provide safer asynchronous operations and a cleaner code structure. Common challenges in multithreaded programming include deadlocks, race conditions, and resource leakage, which require careful design of threading models and the use of appropriate synchronization mechanisms to avoid these problems.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

The advantage of multithreading is that it can improve performance and resource utilization, especially for processing large amounts of data or performing time-consuming operations. It allows multiple tasks to be performed simultaneously, improving efficiency. However, too many threads can lead to performance degradation, so you need to carefully select the number of threads based on the number of CPU cores and task characteristics. In addition, multi-threaded programming involves challenges such as deadlock and race conditions, which need to be solved using synchronization mechanisms, and requires solid knowledge of concurrent programming, weighing the pros and cons and using them with caution.
