微信扫描二维码,跳转到第三方网页,并获取用户OpenId和基本信息

扫描二维码后,通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

实现步骤:

1、确定回调URL,即扫描二维码,并通过微信授权后,需要跳转的后台URL地址,例如:

http://xialtian.w3.luyouxia.net/wx/index

2、构造微信网页授权URL

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4e3c9eb0558k73ae&redirect_uri=http%3A%2F%2Fxial9527.w3.luyouxia.net%2Fwx%2FgetOAuth2UserInfo&response_type=code&scope=snsapi_userinfo&state=&connect_redirect=1#wechat_redirect

微信网页授权具体参考官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

3、生成二维码

使用二维码生成工具将上述授权链接:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4e3c9eb0558k73ae&redirect_uri=http%3A%2F%2Fxial9527.w3.luyouxia.net%2Fwx%2FgetOAuth2UserInfo&response_type=code&scope=snsapi_userinfo&state=&connect_redirect=1#wechat_redirect

生成二维码。

4、Web后台获取OpenId和用户基本信息

/**
	 * 通过code获得基本用户信息 详情请见:
	 * http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html
	 *
	 * @param code
	 *            code
	 * @param lang
	 *            zh_CN, zh_TW, en
	 */
	@RequestMapping(value = "/getOAuth2UserInfo")
	public void getOAuth2UserInfo(HttpServletResponse response, @RequestParam(value = "code") String code) {
		ReturnModel returnModel = new ReturnModel();
		WxMpOAuth2AccessToken accessToken;
		WxMpUser wxMpUser;
		try {
			accessToken = this.wxMpService.oauth2getAccessToken(code);
			wxMpUser = this.wxMpService.getUserService().userInfo(accessToken.getOpenId(), "zh_CN");
			returnModel.setResult(true);
			returnModel.setDatum(wxMpUser);
			//renderString(response, returnModel);
		} catch (WxErrorException e) {
			returnModel.setResult(false);
			returnModel.setReason(e.getError().toString());
			//renderString(response, returnModel);
			this.logger.error(e.getError().toString());
		}
		try {
			response.sendRedirect("./index");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

完!!!

你可能感兴趣的:(微信公众号,javaweb)