How to obtain wechat user openid

Posted by veronicabend on Thu, 03 Feb 2022 16:28:39 +0100

📒 Blog home page: A professional who advocates learning technology
Xiao Xiao is here 🏇
🍣 Today's article is "how to obtain wechat user openid" 🍣
🍣 I hope you can finish reading this article patiently 🍣
🙏 Bloggers are also in the learning stage. If you find any problems, please let us know. Thank you very much 🙏
💗 At the same time, thank you very much for your support 💗

1. Foreword

With the development of technology, a series of wechat services have penetrated into our life, but how should we develop wechat. I believe many of my friends are eager to know. This article is to solve some of your doubts. First, if we want to carry out relevant development, we need to obtain the openid of wechat first. So how do we get Yingai? Here I will introduce two ways.

2. Manual mode

Official documents

2.1. SET domain name

(1). Register the corresponding official account and find the location below.

(2). In natapp Buy your own domain name for wechat development on cn

Company Registered Address

Ha ha, the domain name on this website is not particularly expensive. If I buy a domain name on this website for one month, it will be only 12 yuan. Moreover, the changed type belongs to the secondary domain name, which has been documented, so there is no need to file.

(3). Download the corresponding client to start

  1. Commands started on windows
natapp -authtoken Yours authtoken
  1. After startup

It can be seen that my domain name points to 127.0.0.1:8080.

(4). Fill in our domain name in the official account, JS interface, submit the security domain name.

Before submitting, we need to download the files in the red box in the figure above and place them in the static directory of the project. After the test access passes, we can submit them.

2.2. Get code

It can be described as twists and turns. I thought my project was going gg. But I'm too pediatrician myself. How could wechat not have thought of such a problem. The official account of WeChat public is authorized to obtain basic information function of users. Its functional service must only have a service number, but in fact, each user can get a test number without registration, which contains this special functional service.

  • (1). Log in to your test number

Wechat test number is free of registration. We can scan the code and log in directly.

  • (2). Write corresponding interface
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : Xiao Xiao
 * @date : Created in 2022/2/1 21:55
 */
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code){
        log.info("Entered auth method...");
        log.info("code = {}",code);
    }
}

  • (3). Web page authorization after logging in the test number

The authorized domain name is our website at natapp If the domain name purchased on CN is not authorized, it will report 10003 redirect_ The URI domain name is inconsistent with the background configuration error.

  • (4). Visit the url to test

https://open.weixin.qq.com/connect/oauth2/authorize?appid= Appid & redirect of test number_ Uri = http: / / your domain name / sell / Weixin / auth & response_ type=code&scope=snsapi_ base&state=STATE#wechat_ redirect

Attention

The tested object must first pay attention to the corresponding test number and must be accessed at the wechat client.

  • (5). test result

Successfully obtained the user's code information.

2.3 exchange access_token

  • (1). controller written by
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author : Xiao Xiao
 * @date : Created in 2022/2/1 21:55
 */
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code){
        log.info("Entered auth method...");
        log.info("code = {}",code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=appsecret&code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
    }
}

  • (2). Composition of visited URLs

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

parameterIs it necessaryexplain
appidyesThe only sign of official account number
secretyesappsecret of the official account
codeyesFill in the code parameters obtained in step 1
grant_typeyesFill in as authorization_code
  • (3). Results of access
{
  "access_token": "53_HK355v2MhOolNlGkaoUf4oDCkyX0WDollvsQNU5SvhsvmvF2S2VoqdPXuokfERI2oqFvQijVShq8aQzeQ9n01mGKSJn7q5rLAcYbTjm1H7k",
  "expires_in": 7200,
  "refresh_token": "53_C1us_G770mgzXjd-PuK329qB65lXiK483_qxUXjKudwWIdHkOz5ntwlByEgUQfMEy_-7tCCzcO4DoHaFbY0JurpZYD3Bys6DLs8ua8J_CjU",
  "openid": "Yours openid",
  "scope": "snsapi_base"
}

3. Using a third-party sdk

3.1. Introducing third-party dependency

        <!--WeChat official account development needs to be introduced.-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>3.1.0</version>
        </dependency>

3.2, the official account configuration of WeChat is written into yaml file and introduced into class.

wechat:
  mpAppId: Your wechat test number appId
  mpAppSecret: Your wechat test number secret
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author : Xiao Xiao
 * @date : Created in 2022/2/2 10:31
 */
@Component
@Data
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {

    /**
     * The official account id
     */
    private String mpAppId;

    /**
     * Official account key
     */
    private String mpAppSecret;

}

3.3. Write configuration class initialization settings wxMpService configuration

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author : Xiao Xiao
 * @date : Created in 2022/2/2 10:24
 */
@Component
public class WechatMpConfig {


    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Autowired
    private WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage;

    @Bean
    public WxMpService wxMpService(){
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
        return wxMpService;
    }

    @Bean
    public WxMpInMemoryConfigStorage wxMpConfigStorage(){
        /**
         * It should be noted here that the corresponding interface is not defined in the parent class
         * Therefore, all methods are in their implementation classes, so we need to construct implementation classes
         */
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
        wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
        return wxMpConfigStorage;
    }
}

3.4. Write the corresponding controller

import com.xiao.enums.ResultEnum;
import com.xiao.exception.SellException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : Xiao Xiao
 * @date : Created in 2022/2/2 10:20
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        String url = "http://xiao-sell.natapp1.cc/sell/wechat/userInfo";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,returnUrl);
        return "redirect:" +  redirectUrl;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try{
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        }catch (WxErrorException e){
            log.error("[Wechat webpage authorization error] exception = {}",e);
            throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(),e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("openid = {}",openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }
}

3.5. debug test

  • First breakpoint

The url of the redirect is obviously the url of the code we obtained manually.

  • Second breakpoint

Successfully obtained code and openid.

Topics: Back-end Mini Program wechat