


Detailed explanation of the steps for scanning code login processing developed by WeChat
May 19, 2018 pm 02:14 PMMany websites today use the WeChat open platform's code scanning login authentication process. This is equivalent to handing over identity authentication to a more authoritative third party for authentication. There is no need to store the user's password in the application website. . This article introduces how to log in to the website based on QR code scanning on the WeChat open platform.
1. Open platform certification
To use the website's QR code login process, you need to first conduct the developer qualification certification of the WeChat open platform account, submit relevant information, and deliver 300 per year Yuan certification fee.
After authentication and establishing relevant website applications, there will be relevant APPID and APPSecret. These key parameters can be used to obtain relevant user information.
The application details interface of the website application is as follows.
The entire open platform feels like there isn’t much, but it requires paid authentication to use these functions, which doesn’t feel very good.
The scan code login we use needs to obtain user information through an open platform, so it is also necessary to set the domain name of the interface for obtaining basic user information, otherwise the information cannot be obtained, which will cause redirection errors.
Set the domain name in the modification entry of [Interface Permissions] [Web Page Account] [Web Page Authorization to Obtain User Basic Information], as shown in the figure below.
#Then enter the domain name of the authorization callback in the pop-up dialog box.
# This setting ensures that user information is obtained.
2. Instructions and specific usage of scanning QR code to log in
Website application WeChat login is a WeChat OAuth2.0 authorized login system built based on the OAuth2.0 protocol standard.
Before performing WeChat OAuth2. Before performing WeChat OAuth2.0 authorized login and access, register a developer account on the WeChat open platform, have an approved website application, and obtain the corresponding AppID and AppSecret. After applying for WeChat login and passing the review, you can start the access process.
WeChat OAuth2.0 authorized login allows WeChat users to use WeChat identities to securely log in to third-party applications or websites. After WeChat users authorize login to third-party applications that have accessed WeChat OAuth2.0, the third party can obtain the user The interface call certificate (access_token) can be used to call the WeChat open platform authorization relationship interface through access_token, so as to obtain the basic open information of WeChat users and help users realize basic open functions.
WeChat OAuth2.0 authorized login currently supports authorization_code mode, which is suitable for application authorization with server side. The overall process of this model is:
1. A third party initiates a WeChat authorization login request. After the WeChat user allows authorization of the third-party application, WeChat will launch the application or redirect to the third-party website, and bring the authorization temporary ticket. code parameter; 2. Use the code parameter plus AppID and AppSecret, etc., to exchange for access_token through the API; 3. Make an interface call through access_token to obtain the user's basic data resources or help the user implement basic operations.
Get the access_token sequence diagram:
From the above figure we can have a general understanding of the entire scan code login process.
3. Processing of each step of scanning QR code to log in
1) Binding of user identity
In order to realize QR code scanning login, we The user's WeChat needs to be bound to the existing system so that when the user scans the QR code, the user's identity can be determined and the automatic login process can be realized.
We can make unified settings in user management, or we can set them after regular user login (username + password). This mainly depends on whether we need to retain the username and password to log in.
For example, you can bind them uniformly in user management, that is, when creating a user, let the user bind to WeChat and obtain the unique identifier of WeChat.
In addition to the login method of retaining the username and password, users can also bind WeChat by themselves after logging in to the system.
#The above interface is to pop up a layer in a page and then request the QR code to be displayed, as shown in the following interface code.
<p id="pWechat" class="easyui-dialog" style="width:450px;height:350px;padding:10px 20px" closed="true" resizable="true" modal="true" iconcls="icon-setting"> <p> <h4>掃描用戶二維碼,進行綁定</h4> </p> <p align="center"> <img id="imgQRcode" alt="使用微信掃碼進行綁定" style="height:200px;width:auto" /> </p> <p align="right"> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript: $('#pWechat').dialog('close')">關(guān)閉</a> </p> </p>
When the above layer is opened, we use JS to dynamically obtain the QR code for display. The specific JS code is as follows.
//綁定微信登陸 function BindWechat() { var url = "http://www.iqidi.com/H5/BindWechat?id=@Session["UserID"]"; url = encodeURIComponent(url); $("#imgQRcode").attr("src", "/H5/QR?url=" + url); //打開綁定窗口 $("#pWechat").dialog('open').dialog('setTitle', '使用微信掃碼進行綁定'); }
上面的JS只是做前端的數(shù)據(jù)請求和顯示,具體的QR動作Action其實就是生成掃描二維碼的過程,這個二維碼其實就是采用通用的方式,來構(gòu)建一個指向我們綁定賬號的地址,從而實現(xiàn)我們綁定賬號的判斷,二維碼的生成過程如下所示。
/// <summary> /// 轉(zhuǎn)換二維碼連接為圖片格式 /// </summary> /// <param name="url">二維碼連接</param> /// <returns></returns> [HttpGet] public ActionResult QR(string url) { //初始化二維碼生成工具 QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; qrCodeEncoder.QRCodeVersion = 0; qrCodeEncoder.QRCodeScale = 4; //將字符串生成二維碼圖片 var image = qrCodeEncoder.Encode(url, Encoding.Default); //保存為PNG到內(nèi)存流 MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Png); image.Dispose(); return File(ms.ToArray(), "image/Png"); }
為了實現(xiàn)用戶的綁定,我們需要獲取當(dāng)前用戶的身份信息,因此需要在BindWeChat的操作里面做一個轉(zhuǎn)向處理,如下接口所示。
/// <summary> /// 生成綁定微信的地址 /// </summary> /// <returns></returns> public ActionResult BindWechat()
這個函數(shù)處理里面,我們需要重新定向處理,我們把它定向到BindAccount函數(shù)里面,方便獲取用戶的openid和其他必要的信息。
另外我們基于微信開放平臺的應(yīng)用,建立了一個和微信賬號信息的聯(lián)系,因此創(chuàng)建數(shù)據(jù)庫信息如下所示。
也就是一個具體的開放平臺應(yīng)用對應(yīng)著一個具體的微信賬號,這樣我們就可以充分利用配置進行處理了。
上面提到的BindAccount的處理的邏輯就是獲取必要的信息,然后在數(shù)據(jù)庫層面對身份信息進行驗證,具體代碼如下所示。
/// <summary> /// 綁定用戶微信號 /// </summary> /// <param name="id">賬號ID</param> /// <returns></returns> public ActionResult BindAccount() { WebAppInfo appInfo = GetWebApp(ConfigData.WebAppId); AccountInfo accountInfo = GetAccount(appInfo.AccountNo); var htResult = GetOpenIdAndUnionId(accountInfo.UniteAppId, accountInfo.UniteAppSecret);//存儲openid方便使用 string openid = htResult["openid"].ToString(); var unionid = htResult["unionid"].ToString(); var userid = Request.QueryString["id"]; var state = Request.QueryString["state"]; if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(userid)) { CommonResult result = BLLFactory<User>.Instance.BindUser(openid, unionid, userid.ToInt32()); if (result.Success) { return BindSuccess(); } else { return BindFail(); } } else { throw new WeixinException("無法獲取openid" + string.Format(", openid:{0}, userid:{1}", openid, userid)); } }
在綁定的過程,我們需要考慮綁定正確賬號,重復(fù)綁定其他賬號,無效綁定幾種情況,如果成功綁定正確賬號(可多次處理結(jié)果一樣),那么得到界面如下所示(這個界面的樣式采用了weui的樣式)。
2)用戶的掃碼登錄處理
上面綁定了賬號后,就可以通過掃碼進行登錄了,掃碼回調(diào)的時候我們有自己的判斷處理,掃碼界面如下所示(我們在保留用戶名密碼登陸的方式外,增加了一個掃碼登錄的處理)。
如果是Bootstrap的界面效果
如果是EasyUI的界面效果
這個和前面的二維碼顯示規(guī)則差不多,不過他們的連接地址是不同的,這個地方用到了開放平臺的接口,也就是我們前面提到開放平臺認證的接口了。
上面的掃碼登錄的界面代碼如下所示。
<!--二維碼掃描登陸的界面層--> <p id="pWechat" class="easyui-dialog" style="width:550px;height:500px;padding:10px 20px" closed="true" resizable="true" modal="true" iconcls="icon-setting"> <p id="login_container" align="center"> </p> <p align="right"> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript: $('#pWechat').dialog('close')">關(guān)閉</a> </p> </p>
上面代碼需要引入JS文件,并使用微信JSSDK的API進行顯示的。
<!--使用微信掃碼進行登陸--> <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script> <script language="javascript"> function OpenJSLogin() { var obj = new WxLogin({ id: "login_container", appid: "@ViewBag.appid", scope: "snsapi_login", redirect_uri: "@ViewBag.redirect_uri", state: "@ViewBag.state", style: "black", href: ".impowerBox .qrcode {width: 200px;}" }); //打開綁定窗口 $("#pWechat").dialog('open').dialog('setTitle', '使用微信掃碼進行登陸'); } </script>
這個里面的參數(shù),如APPID就是來源我們認證后的開放平臺參數(shù)。
這些信息我們在MVC控制器后面獲取后綁定在ViewBag,方便界面前端的使用。
//使用JSLogin登陸 WebAppInfo appInfo = BLLFactory<WebApp>.Instance.FindByID(ConfigData.WebAppId); ArgumentValidation.CheckForNullReference(appInfo, "Web應(yīng)用程序appInfo"); if (appInfo != null) { ViewBag.appid = appInfo.OpenAppID; ViewBag.redirect_uri = appInfo.LoginCallBackUrl; ViewBag.state = ConfigData.AuthState; }
其中的redirect_uri是通過數(shù)據(jù)庫獲取的LoginCallBackUrl地址,這個地址類似如下格式:www.iqidi.com/H5/callback?uid=iqidiSoftware
也就是我們在開放平臺處理返回后進行的回調(diào)處理。
通過開放平臺的APPID和APPSecret,我們可以獲取到對應(yīng)的接口調(diào)用憑證,然后根據(jù)接口憑證,以及openid,獲得用戶的公眾平臺統(tǒng)一的UnionID,這個標(biāo)識是我們用戶的唯一標(biāo)識,代碼如下所示。
var result = baseApi.GetAuthToken(appid, appsecret, code); if (result != null && !string.IsNullOrEmpty(result.openid)) { openid = result.openid; var unionResult = baseApi.GetSnsapiUserInfo(result.access_token, result.openid); ht.Add("openid", openid); ht.Add("unionid", unionResult != null ? unionResult.unionid : ""); }
有了unionid我們就可以根據(jù)這個標(biāo)識在我們的用戶數(shù)據(jù)庫里面查找對應(yīng)的用戶,如下代碼所示。
//開放平臺的OpenID,不是公眾號的OpenID,需要轉(zhuǎn)換為unionid if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(unionid)) { UserInfo userInfo = BLLFactory<User>.Instance.FindByUnionId(unionid);
然后判斷我們?nèi)サ降挠脩粜畔⑹欠裾_,如下代碼所示
if (userInfo != null) { CommonResult loginResult = CheckLogin(userInfo.Name); if (!loginResult.Success) { LogHelper.Info(string.Format("用戶登陸不成功,{0}", loginResult.ErrorMessage)); } //登陸成功后的重定向地址 var url = appInfo.HomeUrl; //例如:http://www.iqidi.com/Home return Redirect(url); }
如果不成功,那么我們定向到指定的界面即可。
//如不成功,最后都統(tǒng)一提示信息 ViewBag.Error = "獲取信息失敗,登陸錯誤"; return View("LoginError");
如果我們登陸成功后,需要設(shè)置一些Session信息或者Cookie信息,那么就可以通過CheckLogin函數(shù)進行處理即可。
以上就是我們結(jié)合微信開放平臺實現(xiàn)微信掃碼登錄的過程,其中整個過程就是用到了下面幾個過程。
1)使用JSSDK的腳本實現(xiàn)掃碼獲取code
JS微信登錄主要用途:網(wǎng)站希望用戶在網(wǎng)站內(nèi)就能完成登錄,無需跳轉(zhuǎn)到微信域下登錄后再返回,提升微信登錄的流暢性與成功率。 網(wǎng)站內(nèi)嵌二維碼微信登錄JS實現(xiàn)辦法:
步驟1:在頁面中先引入如下JS文件(支持https):
<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
步驟2:在需要使用微信登錄的地方實例以下JS對象:
var obj = new WxLogin({ id:"login_container", appid: "", scope: "", redirect_uri: "", state: "", style: "", href: "" });
2)?第二步:通過code獲取access_token
通過code獲取access_token
api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
3)第三步:通過access_token調(diào)用接口
獲取access_token后,進行接口調(diào)用,
對于接口作用域(scope),能調(diào)用的接口有以下:
Authorization scope (scope) | Interface | Interface description |
---|---|---|
snsapi_base | /sns/oauth2/access_token | Exchange code for access_token, refresh_token and authorized scope |
Refresh or renew access_token using | ||
Check access_token validity | ||
/sns/userinfo | Get user personal information |
4) Obtain information and perform pre-login processing in the callback interface
Through the above interface, we can obtain the corresponding user identity information, so it can be combined with our user database. Identification and processing of user identity, setting necessary Session or Cookie information, etc., and finally locating to the main interface of our application.The above is the detailed content of Detailed explanation of the steps for scanning code login processing developed by WeChat. 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)

Hot Topics

Everyone can use Douyin APP to watch various short videos every day. By watching these videos, you can relieve your worries and pass the time. It is a very good choice for anyone. Sometimes, we can cut a large number of short videos, and there are some new videos every day that can be pushed to you to satisfy the viewing needs of different users. Many times, everyone will need to use the scan function on the platform. The scanning function requires authorization to log in on other platforms. Scanning the QR code to log in like this can make everyone feel more convenient, but most of my friends still don’t know how to scan the QR code. Log in, so the editor of this site is very thoughtful and brings you some specific scan codes.

Mango TV is a very useful platform for watching dramas. It is a drama-watching artifact specially created for Hunan Satellite TV. It satisfies those friends who want to watch dramas. There are a lot of rich film and television resources here, including the latest movies, popular TV series, etc., you can easily watch them. So do you know how to scan the QR code to log in to Mango TV? The detailed steps to scan the QR code to log in to Mango TV: 1. Search the browser and enter the Mango TV website. 2. After clicking on the upper right corner of the page to log in, click on the QR code icon. Software advantages 1. High-definition and smooth: high-quality video resources, new playback core 2. Historical viewing function: quickly find the last program you watched and continue playing 3. Perfect support for online on-demand and local playback 4. Format compatibility: fully compatible with mainstream media formats

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

iQiyi is a well-known audio and video playback platform. You can watch a variety of videos here. The software has many functions. Current members can also share it and borrow it from others. Member account, log in together here, and enjoy membership services. There are various login methods, and you can choose freely. Everyone is still not clear about how to scan the code to log in to other people's members, so the editor will also give you I have brought you specific operation methods, I hope it can help you. How to scan the iQiyi QR code to log in to other people’s members: 1. Open the iQiyi app and click the “+” sign in the upper right corner of the interface 2. Click the “Scan” function on the third line

For crawlers to crawl websites that require login, verification code or scan code login is a very troublesome problem. Scrapy is a very easy-to-use crawler framework in Python, but when processing verification codes or scanning QR codes to log in, some special measures need to be taken. As a common browser, Mozilla Firefox provides a solution that can help us solve this problem. The core module of Scrapy is twisted, which only supports asynchronous requests, but some websites require the use of cookies and

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat
