微信授权(二) 获取openid

一: 获取openid

   阅读微信授权(一) 后,通过访问https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxabc670e3c404adf9&redirect_uri=http%3A%2F%2F1864rg4803.imwork.net%2F%2FweChat%2FgetCode&response_type=code&scope=snsapi_userinfo&state=students-photo.html 调回java方法

  我写的方法名是/weChat/getCode,下面上代码:

@Controller
@RequestMapping(value = "/weChat")
public class WeChatController {
	@RequestMapping(value = "/getCode", produces = "text/html;charset=UTF-8")
	public String resultCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = null;
		code = request.getParameter("code");// 用户授权码
		String state = request.getParameter("state");// 
	
		// 通过code获取网页授权access_token
		AuthToken authToken = WebChatUtil.getTokenByAuthCode(code);

		String openId = authToken.getOpenid();
		System.out.println("openid " + openId);

        String url="重定向到H5页面?openid="+openId;
		return url;
	}
}

  2.WebChatUtil:

package com.web.wx.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.codehaus.jackson.map.ObjectMapper;

import com.web.common.AuthToken;
import com.web.common.WxConstant;



public class WebChatUtil {
	/**
	 * 扩展xstream,使其支持name带有"_"的节点
	 */
	// public static XStream xStream = new XStream(new DomDriver("UTF-8", new
	// XmlFriendlyNameCoder("-_", "_")));
	private static ObjectMapper jsonObjectMapper = new ObjectMapper();

	/**
	 * 根据code获取微信授权access_token
	 */
	public static AuthToken getTokenByAuthCode(String code) {
		// public static AuthToken getTokenByAuthCode() {
		AuthToken authToken = null;
		StringBuilder json = new StringBuilder();
		try {
			URL url = new URL(WxConstant.Authtoken_URL(code));
			URLConnection uc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
				System.out.println("遍历json" + json.toString());
			}
			in.close();
			// 将json字符串转成javaBean
			authToken = jsonToEntity(json.toString(), AuthToken.class);
		} catch (IOException ex) {
			System.out.println("获取access_token异常");
		}
		return authToken;
	}

	/**
	 * Json字符转Java实体
	 * 
	 * @param jsonString
	 *            Json字符串
	 * @param entityType
	 *            实体类型
	 * @return default null,表示转换失败
	 */
	public static <T> T jsonToEntity(String jsonString, Class<T> entityType) {
		T entity = null;

		try {
			entity = jsonObjectMapper.readValue(jsonString, entityType);
		} catch (Exception e) {
			System.out.println("Json转换异常");
		}

		return entity;
	}

}

 3.WxConstant:

package com.web.common;

public class WxConstant {
	
    /**
	 * 公众号AppId wx9dfff98fb16feb04
	 */
	public static final String APP_ID = "AppId";

	/**
	 * 公众号AppSecret defc6832db583495c9101a961836fdfc
	 */
	public static final String APP_SECRET = "AppSecret ";

	/**
	 * 返回成功字符串
	 */
	public static final String RETURN_SUCCESS = "SUCCESS";

	/**
	 * 支付地址(包涵回调地址)
	 */
	static String redirectUrl = "";
	public static final String PAY_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri=" + redirectUrl
			+ "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

	/**
	 * 通过code获取授权access_token的URL
	 */
	public static String Authtoken_URL(String code) {
		StringBuffer url = new StringBuffer();
		// api.weixin.qq.com 10.10.208.11:8033
		url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
		url.append(WxConstant.APP_ID);
		url.append("&secret=");
		url.append(WxConstant.APP_SECRET);
		url.append("&code=");
		url.append(code);
		url.append("&grant_type=authorization_code");
		return url.toString();
	}
}

即可授权后拿到openId

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uni微信h5静默授权是指在用户进入uni微信H5页面时,通过微信授权接口获取用户的openid,并且不弹出授权页面让用户手动授权的一种授权方式。 实现uni微信H5静默授权获取openid的步骤如下: 1. 首先,在uni-app中引入微信JSSDK,通过在index.html中引入微信JS SDK库文件,或者通过npm安装并在main.js中引入微信JSSDK。 2. 在uni微信H5页面中编写获取openid的逻辑。可以在页面加载完成后,通过微信JSSDK提供的接口wx.config进行微信JS SDK的配置。在配置完成后,可以通过调用wx.ready函数,在ready回调函数中进行获取openid的操作。 3. 使用uni.request或uni.get请求后端接口,将微信提供的code发送至后端。 4. 后端接口需要通过微信的网页授权接口,调用接口获取access_token和openid。接口调用成功后,可以把openid返回给前端。 5. 前端接收到openid后,可以进行后续的业务逻辑处理,例如用户登录、数据统计等。 需要注意的是,uni微信H5静默授权获取openid需要满足一定的条件,包括要求用户在微信客户端中已经授权过且未取消授权,页面的域名需要与微信公众平台的配置一致等。 总结起来,通过微信JSSDK的配置和调用微信的网页授权接口,可以实现uni微信H5静默授权获取openid的功能。这使得开发者能够更加便捷地获取用户的openid,并基于openid实现个性化的功能和服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值