Home > Backend Development > Golang > How to use Golang to implement WeChat authorized login for web applications

How to use Golang to implement WeChat authorized login for web applications

王林
Release: 2023-06-24 08:16:54
Original
2417 people have browsed it

With the popularity of WeChat, WeChat login has become an essential function for many web applications. By logging in with WeChat authorization, users can easily log in to web applications using their WeChat account and avoid cumbersome registration processes. This article will introduce how to use Golang to implement WeChat authorized login for web applications.

  1. Get the AppID and AppSecret of the WeChat Open Platform application

First, we need to register and create an application on the WeChat Open Platform and obtain the AppID and AppSecret of the application. On the application management page of the WeChat open platform, you can see the applications you created and obtain the AppID and AppSecret of the application.

  1. Construct the URL for WeChat authorized login

When constructing the URL for WeChat authorized login, you need to follow the requirements of the WeChat open platform to add the AppID of the application, the redirected URL and some Other parameters are spliced ​​together according to certain rules. The following is a sample URL, in which "APPID" and "REDIRECT_URI" need to be replaced with the AppID and redirect URL of your own application:

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

The parameter description is as follows:

  • appid :AppID of the application.
  • redirect_uri: The callback link address redirected after authorization. Please use urlencode to process the link.
  • response_type: return type, fixed to code.
  • scope: application authorization scope, snsapi_base means to only get the user openid, snsapi_userinfo means to get the user details.
  • state: Used to maintain the status of requests and callbacks, and bring them back to the third party as they are after authorizing the request.

In Golang, you can use url.Values ​​to build URL parameters. The following is a sample code:

func buildAuthURL(appID, redirectURI, state string) string {
    values := make(url.Values)
    values.Set("appid", appID)
    values.Set("redirect_uri", redirectURI)
    values.Set("response_type", "code")
    values.Set("scope", "snsapi_userinfo")
    values.Set("state", state)
    return "https://open.weixin.qq.com/connect/oauth2/authorize?" + values.Encode() + "#wechat_redirect"
}
Copy after login

This function accepts three parameters: the AppID of the application, the URL of the callback after authorization, and a random string state. The function returns a constructed WeChat authorized login URL.

  1. Get the access_token of the WeChat user

After the user verifies the identity in the WeChat client, WeChat will pass the authorization code back and redirect to the preset callback on the URL. In the callback URL, we need to parse the URL parameters, obtain the authorization code code, and use the code to exchange for access_token. The following is a sample code:

func getAccessToken(appID, appSecret, code string) (string, error) {
    url := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID +
        "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"

    resp, err := http.Get(url)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }

    var data struct {
        AccessToken string `json:"access_token"`
        ExpiresIn   int    `json:"expires_in"`
        OpenID      string `json:"openid"`
        Scope       string `json:"scope"`
    }

    if err := json.Unmarshal(body, &data); err != nil {
        return "", err
    }

    return data.AccessToken, nil
}
Copy after login

This function accepts three parameters: the application's AppID, the application's AppSecret and the authorization code code. The function uses the http.Get() method to send a GET request to the WeChat server to obtain the access_token. This function returns an access_token value of type string, or an error if an error occurs.

  1. Get the basic information of WeChat users

After obtaining access_token, we can send a request to obtain user information to the WeChat server, and parse the returned JSON format data to obtain Basic information of WeChat users. Here is a sample code:

func getUserInfo(accessToken, openID string) (*userInfo, error) {
    url := "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openID

    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    var user userInfo

    if err := json.Unmarshal(body, &user); err != nil {
        return nil, err
    }

    return &user, nil
}
Copy after login

This function accepts two parameters: access_token and user openid. The function uses the http.Get() method to send a GET request to the WeChat server to obtain the basic information of the WeChat user. This function returns a pointer type variable pointing to the userInfo structure, or an error if an error occurs.

  1. Write a handler for WeChat authorized login

Finally, we need to write a handler to integrate the above functions to realize WeChat authorized login. The following is a sample code:

func wxLoginHandler(w http.ResponseWriter, r *http.Request) {
    appID := "your app id"
    appSecret := "your app secret"
    state := "random string"
    redirectURI := url.QueryEscape("http://your_server_url/callback")

    if r.Method == "GET" {
        // Redirect to Wechat login page
        http.Redirect(w, r, buildAuthURL(appID, redirectURI, state), 302)
    } else if r.Method == "POST" {
        // Get user info after login succeeds
        code := r.FormValue("code")
        if code == "" {
            http.Error(w, "Missing code parameter", http.StatusBadRequest)
            return
        }

        accessToken, err := getAccessToken(appID, appSecret, code)
        if err != nil {
            http.Error(w, "Failed to get access token", http.StatusInternalServerError)
            return
        }

        user, err := getUserInfo(accessToken, openID)
        if err != nil {
            http.Error(w, "Failed to get user info", http.StatusInternalServerError)
            return
        }

        // Do something with user info
        fmt.Fprintf(w, "Hello, %s!", user.Nickname)
    } else {
        http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
        return
    }
}
Copy after login

This function implements the entire process of WeChat authorized login. When the user accesses "/wx_login", the function will redirect to the WeChat authorization login page. After the user logs in on this page, the function will redirect back to the callback URL with the authorization code code parameter. In the callback function, we will use the authorization code to obtain the access_token and basic user information, and can save the user information to the server or perform other processing.

Summary

This article introduces how to use Golang to implement WeChat authorized login for web applications. Through the introduction of this article, we can understand the implementation principle of WeChat authorized login, and write a simple WeChat authorized login processing program. In practical applications, we also need to consider issues such as security and performance, and make corresponding optimizations and improvements based on actual needs.

The above is the detailed content of How to use Golang to implement WeChat authorized login for web applications. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template