微信开发之网页获取用户信息

一、配置网页授权域名不能带http,www

175214_QcYC_136848.png

二、获取用户信息

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());
	}
	
}

先访问/auth接口跳转微信端获取code

再通过redirect_uri指定回调地址跳转到getUserInfo接口获取用户信息

转载于:https://my.oschina.net/u/136848/blog/1802948

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值