The webpage developed by WeChat obtains user information

1. Configure the authorized domain name of the webpage without http, www

2. Obtain user information

package com.dongpeng.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongpeng.utils.HttpUtils;

@Controller
public class OAuthTokenController {
	
	public static final String  APP_ID="";
	public static final String  APP_SECRET="";

	/**
	 * 跳转到微信端获取code信息
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/auth")
	public String auth() throws UnsupportedEncodingException {
		StringBuilder authUrl = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
		authUrl.append("appid=").append(APP_ID).append("&").append("redirect_uri=").append(URLEncoder.encode("http://lianghao.xdp8.cn/getUserInfo","utf-8"))
		.append("&").append("response_type=code").append("&").append("scope=snsapi_userinfo").append("&").append("state=1").append("#wechat_redirect");
		System.out.println(authUrl);
		return "redirect:"+authUrl.toString();
	}
	
	/**
	 * 通过code获取用户信息
	 * @param code
	 * @return
	 */
	@RequestMapping("/getUserInfo")
	@ResponseBody
	public String getUserInfo(String code) {
		StringBuilder accessTokenUrl  = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?");
		accessTokenUrl.append("appid=").append(APP_ID).append("&").append("secret=").append(APP_SECRET).append("&").append("code=").append(code).append("&grant_type=authorization_code");
		String result = HttpUtils.get(accessTokenUrl.toString());
		JSONObject jsonObject = JSON.parseObject(result);
        StringBuilder userUrl = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?");
        userUrl.append("access_token=").append(jsonObject.getString("access_token")).append("&").append("openid=").append(jsonObject.getString("openid")).append("&lang=zh_CN");
		return HttpUtils.get(userUrl.toString());
	}
	
}

First visit the /auth interface and jump to the WeChat terminal to get the code

Then specify the callback address through redirect_uri and jump to the getUserInfo interface to obtain user information

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325058906&siteId=291194637