博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
微信开发之网页获取用户信息
阅读量:7009 次
发布时间:2019-06-28

本文共 2135 字,大约阅读时间需要 7 分钟。

hot3.png

一、配置网页授权域名不能带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;@Controllerpublic 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

你可能感兴趣的文章
在Debian 7上配置Nginx + php-FPM + apc + MariaDB(翻译)
查看>>
解决Maven多模块项目,MavenWeb项目依赖的项目,修改无法立即生效问题
查看>>
XMPP协议实现原理介绍
查看>>
Java四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor...
查看>>
Java 一个特殊的类 ServiceLoader<S> 详解
查看>>
盒子模型中的div居中
查看>>
让你打开眼界的生活小创意!
查看>>
常用apt命令
查看>>
CSS实现3D旋转
查看>>
golang服务端, 游戏公测时遇到的socket写超时的问题, 也是游戏框架的设计问题
查看>>
oracle 定时器
查看>>
mysqld_multi 多实例启动mysql
查看>>
配置linux下的vimrc
查看>>
glusterfs Self-Heal and Re-Balance Operations
查看>>
Python文件夹与文件的操作
查看>>
Apache 启动遇到问题解决
查看>>
final和static
查看>>
win7 64位 下USB转COM驱动安装方法
查看>>
QString 与中文问题
查看>>
MPLS ××× 配置步聚
查看>>