Process for enterprise wechat application access to obtain UserId

  • 1 Create an application and obtain the enterprise ID, application ID(AgentId) and application key (Secret).
  • 2 byhttps://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRETThe interface retrieves accessToken and stores it in redis or global static variables
  • 3 Configuring a trusted Domain name (domain name + port)
  • 4-1 JAVA Authentication Mode 1
	@RequestMapping("/")
	public class TxtApi {
	    @getMapping (" Your file name is.txt")
	    @ResponseBody
	    public String text(a){
	        return "You have to name and content the file."; }}Copy the code
  • 4-2 Nginx Authentication Mode 2
Server {listen Your port; server_name localhost; location / { root C:\Users\Administrator\Desktop\; }}Copy the code
  • 5 Create the system entry path and callback address
@Controller
@RequestMapping("api/sys")
@Slf4j
public class SystemController {

    @GetMapping("getCode")
    public ModelAndView getCode(String code, HttpSession session){
    	/ / get userId
        String result = HttpUtil.getResult("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE".replace("ACCESS_TOKEN"AccessToken (previous article said how to get).replace("CODE", code));
        JSONObject jsonObject = JSONObject.fromObject(result);
        log.info("Get data {}",jsonObject);
        String userId = jsonObject.getString("UserId");
        return new ModelAndView(new RedirectView("Front-end page path? userId="+userId));
    }

    /** * System path construction *@return* /
    @GetMapping("buildCode")
    public String buildCode(a){
        String buildUrl = "";
        // Callback address
        String url = "Trusted Domain prefix" + "api/sys/getCode";
        return "redirect:"+ "https://open.weixin.qq.com/connect/oauth2/authorize"
			+ "? appid=CORPID"/ / enterprise id
			+ "&redirect_uri=REDIRECT_URI"// Callback address
			+ "&response_type=code"// Always fill in
			+ "&scope=snsapi_base"// Always fill in
			+ "&state=STATE"// Customize the field
			+ "#wechat_redirect".replace("CORPID", CORP_ID).replace("REDIRECT_URI", url); }}Copy the code
  • 6. The user data is successfully obtained on the page