C# use wechat scanning code to log in to the web page

Concept: when we realize wechat code scanning login, we need to consider how to display the action of wechat code scanning on the web page.
It is divided into the following four steps:
Step 1: we need to apply for website application on wechat open platform. Wechat open platform
Step 2: create a blank page and write the js operation generated by wechat QR code on the page
Step 3: obtain the code returned by wechat "asynchronously" through the applied appid and AppSecret. While obtaining the code, obtain access through the code_ token.
Step 4: get the user information. When we get the token of wechat, we can request wechat to get the api of the user's openid and get the openid identification of the code scanning user
Step 5: query whether the user exists in the user table through openid. When it exists, skip login verification.

After understanding the concept, we need to refer to this document to better develop this function: Wechat code scanning login website

The specific implementation methods are as follows:

1. Create website application

1.1 go to wechat open platform to apply for website application.
1.2 after the application is approved, you can obtain AppID and AppSecret
1.3 and apply for wechat login interface.

2. Create a blank page and write the js operation generated by wechat QR code on the page

Step 1: first introduce the following in the page JS File (support) https): 
http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js

Step 2: where wechat login is required, the following examples are provided JS Object:
 var obj = new WxLogin({
 self_redirect:true,
 id:"login_container", 
 appid: "", 
 scope: "", 
 redirect_uri: "",
  state: "",
 style: "",
 href: ""
 });

Step 3:Page definition div
<div id="login_container"></div>

In redirect_uri, for example, fill in the address https://login/WeChat
In Wechat's method, code and stat will be brought with Wechat asynchronous callback after code scanning. At this time, we can verify through these return values. Here, after I verify, it is the login address of direct callback
return Redirect("https://home/index");.

3. Get code

Official documents: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
2.1 the official documents are very detailed.

example: https://open.weixin.qq.com/connect/qrconnect?appid=wx2d31f65267d0fcb6&redirect_uri=http%3a%2f%2fwww.webus.cn&response_type=code&scope=snsapi_login&state=awen#wechat_redirect

4. Obtain user information

3.1 upper code
3.1.1 obtaining a QR code and accessing it through the returned path is a QR code.

[HttpPost]
        [ValidateInput(false)]
        public JsonResult ScanThirdGo(bool? isHttps = false)
        {
            string sign = Guid.NewGuid().ToString().Replace("-", string.Empty);

            string callBackUrl = (Convert.ToBoolean(isHttps) ? "https://" : "http://") + System.Web.HttpContext.Current.Request.Url.Host.ToString() + "/API/WeiXin/OpenThirdPartCallBack";

            callBackUrl = System.Web.HttpUtility.UrlEncode(callBackUrl);

            var openAppId = ConfigurationManager.AppSettings["WxOpenID"];

            string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + openAppId + "&redirect_uri=" + callBackUrl + "&response_type=code&scope=snsapi_login" + "&state="
                + sign + "#wechat_redirect";

            LogHelper.Info("ThirdGo:" + url + ",sign:" + sign);

            return Json(CloudHill.Framework.StandardComponents.Result.GetSuccess(url));
        }

3.1.2 wechat callback interface. The user can obtain the basic information of the user after clicking agree.

 public ActionResult OpenThirdPartCallBack(string code, string state)
        {
            LogHelper.Info("OpenThirdPartCallBack:code:" + code + ",state:" + state);

            var openAppId = ConfigurationManager.AppSettings["WxOpenID"];
            var openScript = ConfigurationManager.AppSettings["WxOpenScript"];

            var result = OAuthApi.GetAccessToken(openAppId, openScript, code);

            if (!string.IsNullOrEmpty(result.access_token))
            {

                var userInfo = CloudHill.Framework.WeiXin.Logic.WeixinHelper.OAuth2.GetAuthorizeUserInfo(result.access_token, result.openid);

                var openID = userInfo.openid;

                var uEntity = Member_Logic.GetSingle(i => i.M_openID == openID);

                var url = "";

                if (uEntity == null)
                {
                    throw new ArgumentException("The user is not bound to wechat and cannot log in. Please log in with your account and password and bind wechat to your personal data.");
                }
                else
                {

                    url = "ss";
                }

                Response.Redirect(System.Web.HttpUtility.HtmlEncode(url), true);
            }

            return null;
        }

Tags: C# Mini Program wechat

Posted by Dave2711 on Sat, 21 May 2022 05:04:12 +0300