Home  >  Article  >  WeChat Applet  >  WeChat public platform development: OAuth2.0 description

WeChat public platform development: OAuth2.0 description

高洛峰
高洛峰Original
2017-02-27 13:28:031423browse

Understanding OAuth2.0

First, let’s understand the operating mode of OAuth2.0 through a picture:

WeChat public platform development: OAuth2.0 description

## We can see from the picture above The whole process went through two "handshakes", and finally used the authorized AccessToken to make a series of requests. The relevant process is explained as follows:

A: The client sends a verification request to the server, and the request usually contains Carrying these parameters

ID identification, such as appId

The URL to jump to after verification (redirectUrl)

State parameter (optional)

Authorization function Domain scope (optional)

Response type (optional)

B: The server returns a grant authorization identification (WeChat calls it code by default), similar to a one-time temporary String key. If redirectUrl is provided in A, the server will make a jump and access redirectUrl with grant and status parameters.

C: The redirectUrl corresponding page of the client uses grant to initiate a request again. This request usually carries some sensitive information:

ID identification

Password

grant string (code)

grant type (optional, the default is code in WeChat)

D: After the server verifies that the ID, password, and grant are correct, it returns AccessToken (note, The AccessToken here has nothing to do with the AccessToken introduced in the previous general interface and advanced interface, and cannot be used cross-wise)

E: The client uses the AccessToken to request a series of APIs, and will no longer carry appId, Secret, and grant in the process. and other sensitive information.

F: The server returns the request result.

WeChat’s OAuth2.0 usage

After understanding the basic principles of OAuth2.0, let’s take a look at how OAuth2.0 is used in WeChat.

Assume a scenario: the user enters a WeChat public account, and then opens a game webpage in the WeChat embedded browser through the link in the message. This game requires the user to log in and record the user's game score.

We have two ways to deal with this situation:

Let the user register and log in on the webpage (and they may have to log in again every time they open this webpage, because WeChat has built-in browsing The server's cookie storage time is very short), this is of course a very cheating design.

Utilize OAuth2.0. When the user enters this page, it first determines whether the user is logged in. If not, it automatically jumps to the OAuth2.0 authorization page. This page automatically performs the above-mentioned ABCD series of verifications, and then obtains the user's OpenId through EF and even more detailed information. information (including avatar), automatically complete the login (or necessary registration) process, and then the user directly enters the game in the logged-in state.

It can be seen that using OAuth2.0 greatly improves the user experience, and can automatically bind and identify the user's WeChat OpenId.

It should be noted that the "OAuth2.0 authorization page" mentioned above also has two forms:

When the Scope in request A is snsapi_base, the entire authorization process is automatically completed. There will not be any intermediate page displayed on the user's client, but the authorization result can only obtain the user's OpenId (regardless of whether the user has followed the user, of course, if the user is following the user, again use the user information interface in the advanced interface to obtain the user's OpenId The information is also available, but it just takes a few detours)

When the Scope in request A is snsapi_userinfo, an authorization page needs to be provided (similar to the authorization that many websites use Weibo accounts and QQ accounts to log in) ), only after the user agrees, the user's detailed information is immediately obtained. The user here can be a following user or an unfollowed user, and the content returned is the same.

In other words, the method of snsapi_base can obtain the user's OpenId "without anyone noticing" and fully automatically complete the login and registration process, but the amount of information is limited; snsapi_userinfo requires the user to authorize it on the specified interface and then completes it automatically. During the entire process, this authorization has a time period, and the user needs to be asked again after the time expires.

Senparc.Weixin.MP OAuth2.0 interface

Source file folder: Senparc.Weixin.MP/AdvancedAPIs/OAuth

The relevant methods in the source code are as follows:

namespace Senparc.Weixin.MP.AdvancedAPIs
{
    //官方文档:http://mp.weixin.qq.com/wiki/index.php?title=%E7%BD%91%E9%A1%B5%E6%8E%88%E6%9D%83%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E5%9F%BA%E6%9C%AC%E4%BF%A1%E6%81%AF#.E7.AC.AC.E4.B8.80.E6.AD.A5.EF.BC.9A.E7.94.A8.E6.88.B7.E5.90.8C.E6.84.8F.E6.8E.88.E6.9D.83.EF.BC.8C.E8.8E.B7.E5.8F.96code

    /// <summary>
    /// 应用授权作用域
    /// </summary>
    public enum OAuthScope
    {
        /// <summary>
        /// 不弹出授权页面,直接跳转,只能获取用户openid
        /// </summary>
        snsapi_base,
        /// <summary>
        /// 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息
        /// </summary>
        snsapi_userinfo
    }

    public static class OAuth
    {
        /// <summary>
        /// 获取验证地址
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="redirectUrl"></param>
        /// <param name="state"></param>
        /// <param name="scope"></param>
        /// <param name="responseType"></param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope, string responseType = "code")
        {
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                                appId, redirectUrl.UrlEncode(), responseType, scope, state);

            /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。
             * 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。这里的code用于换取access_token(和通用接口的access_token不通用)
             * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
             */
            return url;
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="code">code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。</param>
        /// <param name="grantType"></param>
        /// <returns></returns>
        public static OAuthAccessTokenResult GetAccessToken(string appId, string secret, string code, string grantType = "authorization_code")
        {
            var url =
                string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type={3}",
                                appId, secret, code, grantType);

            return CommonJsonSend.Send<OAuthAccessTokenResult>(null, url, null, CommonJsonSendType.GET);
        }

        /// <summary>
        /// 刷新access_token(如果需要)
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="refreshToken">填写通过access_token获取到的refresh_token参数</param>
        /// <param name="grantType"></param>
        /// <returns></returns>
        public static OAuthAccessTokenResult RefreshToken(string appId, string refreshToken, string grantType = "refresh_token")
        {
            var url =
                string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type={1}&refresh_token={2}",
                                appId, grantType, refreshToken);

            return CommonJsonSend.Send<OAuthAccessTokenResult>(null, url, null, CommonJsonSendType.GET);
        }

        public static OAuthUserInfo GetUserInfo(string accessToken,string openId)
        {
            var url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}",accessToken,openId);
            return CommonJsonSend.Send<OAuthUserInfo>(null, url, null, CommonJsonSendType.GET);
        }
    }
}

For specific example methods, see Senparc.Weixin.MP.Sample/Controllers/OAuth2Controller.cs, as well as the code for the corresponding view.

Note

You must have an authenticated service account to use the OAuth interface.

The AccessToken used in the interface and the AccessToken used in the advanced interface (including the general interface) are not related to each other, even if they are obtained through the same AppId and Secret.

The current official authorization page is not 100% stable. Sometimes it takes several clicks to pass smoothly. If you find such a situation, you need to make some judgments and make repeated requests. At least on the surface, users can not see the error page.

For security reasons, before using OAuth2.0, you need to enter [My Service] in the WeChat background to set the domain name of the callback page:

WeChat public platform development: OAuth2.0 description

WeChat public platform development: OAuth2.0 description

For more WeChat public platform development: OAuth2.0 instructions, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn