首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微信开发之网页获取用户信息 原

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

作者头像
用户2603479
发布2018-08-16 09:50:56
7670
发布2018-08-16 09:50:56
举报
文章被收录于专栏:JAVA技术站JAVA技术站

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

二、获取用户信息

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接口获取用户信息

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档