Example: Use C#.NET to teach you how to develop WeChat official account (22) -- Obtain user openid through OAuth on the web page

Part 1: Theory

If a user does not follow a certain official account, but just opens a webpage on the official account's web server in WeChat, how to obtain the user's openid and user's WeChat information in order to implement business logic? This article describes the key information of the web page authorization OAuth to obtain WeChat users. Let's first understand a concept:

Web page authorization

If a user visits a third-party webpage in the WeChat client, the official account can obtain the basic information of the user through the authorization mechanism of the WeChat webpage, and then realize the business logic.

Announcement on the Adjustment of WeChat Web Page Authorization Capabilities

In order to further standardize the use of capabilities and protect the legitimate rights and interests of users, the platform will adjust the authorization capabilities of WeChat web pages. When the developer initiates snsapi_userinfo webpage authorization in non-standard use on the webpage, WeChat will open the webpage snapshot page mode by default for basic browsing.  The capacity adjustment will take effect at 24:00 on July 12, 2022. For details, click to view the original announcement "WeChat Web Page Authorization Capability Adjustment Announcement" .

Instructions on Authorizing Callback Domain Names for Web Pages

  1. Before the WeChat official account requests user webpage authorization, the developer needs to go to the official website of the official platform to modify the authorization callback domain name in the configuration option of "Development - Interface Permission - Webpage Service - Webpage Account - Webpage Authorization to Obtain User Basic Information" on the official website of the official platform. Please note that the domain name (a character string) is filled in here, not the URL, so please do not add protocol headers such as http://;
  2. The configuration specification of the authorization callback domain name is a full domain name. For example, the domain name that requires web page authorization is: www.qq.com. After configuration, the pages under this domain name will be http://www.qq.com/music.html, http://www. Both qq.com/login.html can perform OAuth2.0 authentication. But http://pay.qq.com, http://music.qq.com, http://qq.com cannot perform OAuth2.0 authentication

Explanation on the difference between the two scopes of web page authorization

  1. The webpage authorization initiated with snsapi_base as the scope is used to obtain the openid of the user entering the page, and it is silently authorized and automatically jumps to the callback page. What the user perceives is to directly enter the callback page (often a business page)
  2. The webpage authorization initiated with snsapi_userinfo as the scope is used to obtain the basic information of the user. However, this kind of authorization requires the user's manual consent, and since the user has agreed, the basic information of the user can be obtained after authorization without paying attention.
  3. The "obtain user basic information interface" in the user management interface is to obtain the user's basic information according to the user's OpenID after the user and the official account have message interaction or follow-up event push. This interface, including other WeChat interfaces, requires the user (that is, openid) to follow the official account before calling it successfully.

About the difference between web page authorization access_token and ordinary access_token

  1. WeChat web page authorization is realized through the OAuth2.0 mechanism. After the user authorizes the official account, the official account can obtain a unique interface call certificate (web page authorization access_token), and the post-authorization interface call can be made through the web page authorization access_token. Such as obtaining basic user information;
  2. For other WeChat interfaces, you need to call the normal access_token obtained through the "obtain access_token" interface in the basic support.

About silent authorization in special scenarios

  1. As mentioned above, for web page authorization with snsapi_base as the scope, it is silently authorized, and the user has no perception;
  2. For users who have followed the official account, if the user enters the official account's webpage authorization page from the official account's session or custom menu, even if the scope is snsapi_userinfo, it is a silent authorization, and the user has no perception.

development guide

The webpage authorization process is divided into four steps:

  1. Guide the user to enter the authorization page to agree to the authorization and obtain the code
  2. Exchange code for webpage authorization access_token (different from access_token in basic support)
  3. If necessary, the developer can refresh the web page to authorize the access_token to avoid expiration
  4. Obtain basic user information through webpage authorization access_token and openid (support UnionID mechanism)

Step 1: The user agrees to authorize and obtain the code

On the premise of ensuring that the WeChat public account has the authorization scope (scope parameter) (the authenticated service account has the snsapi_base and snsapi_userinfo permissions in the scope parameter by default), guide followers to open the following page:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

If the prompt "This link cannot be accessed", please check whether the parameters are filled incorrectly, and whether you have the authorization scope permission corresponding to the scope parameter.

Pay special attention: Due to the high security level of authorization operations, when an authorization request is initiated, WeChat will perform regular strong matching verification on the authorization link. If the order of the parameters of the link is incorrect, the authorization page will not be able to be accessed normally.

Reference link (please open this link in the WeChat client to experience):

scope is snsapi_base:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect

scope is snsapi_userinfo:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

 

Step 2: Exchange the code for the web page authorization access_token

First of all, please note that what is exchanged through the code here is a special webpage authorization access_token, which is different from the access_token in the basic support (the access_token is used to call other interfaces). The official account can obtain the web page authorization access_token through the following interface. If the scope of the webpage authorization is snsapi_base, the webpage authorization access_token is obtained in this step, and the openid is also obtained, and the snsapi_base-style webpage authorization process ends here.

Pay special attention: Since the official account's secret and the obtained access_token have a very high security level, they must only be saved on the server and not allowed to be passed to the client. Subsequent steps such as refreshing access_token and obtaining user information through access_token must also be initiated from the server.

request method

After getting the code, request the following link to get the access_token:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

 

Step 3: Refresh access_token (if needed)

Since the access_token has a short validity period, when the access_token expires, it can be refreshed with the refresh_token. The refresh_token is valid for 30 days. When the refresh_token expires, the user needs to re-authorize.

request method

After obtaining the refresh_token in the second step, request the following link to obtain the access_token:

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

 

Step 4: Pull user information (requires scope as snsapi_userinfo)

If the authorization scope of the web page is snsapi_userinfo, the developer can pull user information through access_token and openid at this time.

request method

http: GET (please use https protocol):

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

When everything is normal, the returned user information fields are as follows:

 

 

Part Two: Combat

1. First prepare a dedicated class and directly upload the source code:

/*
*类名:QinMingWeixinOAuth
*归属:QinMing.WeixinOAuth命名空间
*用途:通过网页OAuth方式获取用户openid和access_token,进而可以获取微信用户的头像、昵称等信息
*作者:
*日期:8
*/

using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;  
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
using QinMing.Config;

namespace QinMing.WeixinOAuth
{
    public  class QinMingWeixinOAuth : System.Web.UI.Page
    {
		
		/// <summary>
        /// 获取CODE,后期用于获取微信用户openid,静默,不需要用户确认
        /// </summary>
		public string GetCodeBase(string appid, string redirect_url)
		{
			var state = "QinMing" + DateTime.Now.Millisecond;
			string RedirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" 
			    + "appid=" + appid 
				+ "&redirect_uri=" + redirect_url
				+ "&response_type=code&scope=snsapi_base"
				+ "&state=" + state + "#wechat_redirect";
			
			return RedirectUrl;
		}
		
		/// <summary>
        /// 用CODE换取openid,适用于获取用户openid,在scope=snsapi_base使用
        /// </summary>
		public string GetOpenId(string code)
	    {
			string appid = QinMingConfig.Weixin_AppId;
			string secret = QinMingConfig.Weixin_AppSecret;
			string strResult="";
			string openid="";
			string strurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="
			    + appid + "&secret="
				+ secret + "&code="
				+ code + "&grant_type=authorization_code";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();
				
				JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				openid = obj["openid"].ToString().Replace("\"", "");
				return openid;
			}
			catch
			{
			    strResult = "err";
				return strResult;
			}
	    }
		
		/// <summary>
        /// 获取CODE,后期用于获取微信用户信息,需要用户确认;与上面GetCodeBase的差异只是scope=snsapi_userinfo部分
        /// </summary>
		public string GetCodeUserInfo(string appid, string redirect_url)
		{
			var state = "QinMing" + DateTime.Now.Millisecond;
			string RedirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" 
			    + "appid=" + appid 
				+ "&redirect_uri=" + redirect_url
				+ "&response_type=code&scope=snsapi_userinfo"
				+ "&state=" + state + "#wechat_redirect";
			
			return RedirectUrl;
		}
		
		/// <summary>
        /// 用CODE换取openid和AccessToken,适用于获取用户信息,在scope=snsapi_userinfo使用,切忌只能用在服务器端使用,不能传递到客户端,高风险
        /// </summary>
		public string GetOpenIdAndAccessToken(string code)
	    {
            string appid = QinMingConfig.Weixin_AppId;
			string secret = QinMingConfig.Weixin_AppSecret;
			string strResult="";
			string openid="";
			string access_token="";
			string strurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="
			    + appid + "&secret="
				+ secret + "&code="
				+ code + "&grant_type=authorization_code";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();
				
				JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				openid = obj["openid"].ToString().Replace("\"", "");
				access_token = obj["access_token"].ToString().Replace("\"", "");
				return openid + "|" + access_token;
			}
			catch
			{
			    strResult = "err";
				return strResult;
			}
			
	    }
		
		/// <summary>
        /// 获取用户信息,包含头像和昵称等
        /// </summary>
		public JObject GetUserInfo(string open_id, string access_token)
	    {
			string strResult = "";
			string strurl="https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + open_id + "&lang=zh_CN";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();

				//更新weixin_user_info表中微信用户信息
				JObject tmpobj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				QinMingToolsDB.UpdateTable("update weixin_user_info set nickname='" + tmpobj["nickname"].ToString().Replace("\"", "") + "',"
				    + "headimgurl='" + tmpobj["headimgurl"].ToString().Replace("\"", "") + "',"
					+ "province='" + tmpobj["province"].ToString().Replace("\"", "") + "',"
					+ "city='" + tmpobj["city"].ToString().Replace("\"", "") + "',"
					+ "country='" + tmpobj["country"].ToString().Replace("\"", "") + "',"
					+ "sex='" + tmpobj["sex"].ToString().Replace("\"", "") + "' "
				    + " where openid='" + open_id + "'");
			}
			catch
			{
				strResult = "err";
			}
			JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
			return obj;
	    }
		/*
		//正确返回时JObject格式如下
		{   
			"openid": "OPENID",
			"nickname": NICKNAME,
			"sex": 1,
			"province":"PROVINCE",
			"city":"CITY",
			"country":"COUNTRY",
			"headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
			"privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
			"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
		}
		*/

	}
	
	
}

2. Only get WeChat user openid

How to use: http://www.xxxx.com/weixin/RedirectWithOpenIdFirst.aspx?final_url=myweb.aspx

In this way, when myweb.aspx is opened, the openid parameter of the WeChat user will be included.

RedirectWithOpenIdFirst.aspx source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RedirectWithOpenIdFirst.aspx.cs" Inherits="Jjlm.RedirectWithOpenIdFirst" %>

RedirectWithOpenIdFirst.aspx.cs source code:

using System;
using System.Web;
using QinMing.Config;
using QinMing.WeixinOAuth;

namespace Jjlm
{
	public partial class RedirectWithOpenIdFirst : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			string final_url = Request.QueryString["final_url"]; 
			string appid = QinMingConfig.Weixin_AppId;
			string redirect_url = QinMingConfig.Url_WebServer + "/weixin/RedirectWithOpenIdSecond.aspx" + "?final_url=" + final_url;
			QinMingWeixinOAuth oauth = new QinMingWeixinOAuth();
			string newurl = oauth.GetCodeBase(appid, redirect_url);
			Response.Redirect(newurl);
		}
	}
}   

RedirectWithOpenIdSecond.aspx source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RedirectWithOpenIdSecond.aspx.cs" Inherits="Jjlm.RedirectWithOpenIdSecond" %>

RedirectWithOpenIdSecond.aspx.cs source code:

using System;
using System.Web;
using QinMing.WeixinOAuth;

namespace Jjlm
{
	public partial class RedirectWithOpenIdSecond : System.Web.UI.Page
	{
		
		protected void Page_Load(object sender, EventArgs e)
		{
			string final_url = Request.QueryString["final_url"]; 
			string code = Request.QueryString["code"]; 
			QinMingWeixinOAuth oauth=new QinMingWeixinOAuth();

			//仅获取openid
			string open_id  = oauth.GetOpenId(code);
			Response.Redirect(final_url + "?open_id=" + open_id);
		}

	}
}   

3. Obtain WeChat user openid, nickname, avatar and other information

How to use: http://www.xxxx.com/Coalition/OAuthOpenidAndUserinfoFirst.aspx?final_url=myweb.aspx

In this way, when myweb.aspx is opened, the openid parameter of the WeChat user will be brought in, and the nickname nickname and avatar head_img_url parameters will be brought in at the same time.

OAuthOpenidAndUserinfoFirst.aspx source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OAuthOpenidAndUserinfoFirst.aspx.cs" Inherits="Coalition.OAuthOpenidAndUserinfoFirst" %>

OAuthOpenidAndUserinfoFirst.aspx.cs source code:

using System;
using System.Web;
using QinMing.Config;
using QinMing.WeixinOAuth;

namespace Coalition
{
	public partial class OAuthOpenidAndUserinfoFirst : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			string final_url = Request.QueryString["final_url"]; 
			string appid = QinMingConfig.Weixin_AppId;
			string redirect_url = QinMingConfig.Url_WebServer + "/Coalition/OAuthOpenidAndUserinfoSecond.aspx" + "?final_url=" + final_url;
			QinMingWeixinOAuth oauth = new QinMingWeixinOAuth();
			string newurl = oauth.GetCodeUserInfo(appid, redirect_url);
			Response.Redirect(newurl);
		}
	}
}   

OAuthOpenidAndUserinfoSecond.aspx source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OAuthOpenidAndUserinfoSecond.aspx.cs" Inherits="Coalition.OAuthOpenidAndUserinfoSecond" %>

OAuthOpenidAndUserinfoSecond.aspx.cs source code:

using System;
using System.Web;
using Newtonsoft.Json;  
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
using QinMing.WeixinOAuth;
using QinMing.Tools;

namespace Coalition
{
	public partial class OAuthOpenidAndUserinfoSecond : System.Web.UI.Page
	{
		
		protected void Page_Load(object sender, EventArgs e)
		{
			string final_url = Request.QueryString["final_url"]; 
			string code = Request.QueryString["code"]; 
			QinMingWeixinOAuth oauth=new QinMingWeixinOAuth();

			//获取openid和access_token
			string openid_accesstoken  = oauth.GetOpenIdAndAccessToken(code);
			//QinMingTools.WriteLog("oauth2.0获取信息测试", openid_accesstoken);
			
			//获取用户头像链接和昵称
			string[] array = openid_accesstoken.Split(new Char[] { '|' });
			string open_id = array[0];
			string access_token = array[1];

			JObject obj = oauth.GetUserInfo(open_id, access_token);
			string head_img_url = obj["headimgurl"].ToString().Replace("\"", "");
			string nickname = obj["nickname"].ToString().Replace("\"", "");
			Response.Redirect(final_url + "?open_id=" + open_id + "&head_img_url=" + head_img_url + "&nickname=" + nickname);
			
		}

	}
}   

Important reminder: In addition to obtaining the openid of WeChat users through the webpage, in addition to implementing business logic such as online sales, common applications include voting and canvassing, partners, and fission communication.

Guess you like

Origin blog.csdn.net/daobaqin/article/details/126861247