微信openid和已有系统的用户绑定2

1、基本配置:

配置接口对应代码:

WXPublicUtils是微信提供的java示例中的代码。

    @RequestMapping(value="/", produces="text/html;charset=UTF-8")
	@ResponseBody
    public Object main(HttpServletRequest request, HttpServletResponse response) {
		
		String method = request.getMethod();
		
		// try {
			
			if(method.equals("GET")) {
				// get为微信平台校验
				String signature = request.getParameter("signature");
				String timestamp = request.getParameter("timestamp");
				String nonce = request.getParameter("nonce");
				String echostr = request.getParameter("echostr");
				
				if (StringUtils.isBlank(signature) || StringUtils.isBlank(timestamp)
						|| StringUtils.isBlank(nonce)) {
					String errorMsg = "参数为空,非微信平台请求";
					logger.error(errorMsg);
					return errorMsg;
					// response.getWriter().write(errorMsg);
		            // return  null;
				} else {
					logger.info("signature: " + signature + ", timestamp: " + timestamp + ", nonce: " + nonce + ", echostr: " + echostr);
				}
				
				try {
					if (WXPublicUtils.verifyUrl(signature, timestamp, nonce)) {
					    return echostr;
					} else {
						return "token校验失败,非法请求";
					}
				} catch (com.highland.utils.wx.AesException e) {
					e.printStackTrace();
					String errorMsg = "token校验失败,非法请求";
					logger.error(errorMsg);
					return errorMsg;
				}
			}
    }

 

 

1、根据微信文档,引导用户打开链接:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

把下面链接,放入微信自定义菜单里

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd96ae606653df34b&redirect_uri=http%3a%2f%2fxxxx.xxx.com%2fwx%2fmyoauth2&response_type=code&scope=snsapi_base&state=123#wechat_redirect

代码:

// 跳转到WXBindAction.myoauth2的action
		WXViewButton button_14 = new WXViewButton();
		button_14.setName("我的数据");
		button_14.setType("view");
		button_14.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=myappid&redirect_uri=http%3a%2f%2fxxx.xxx.com%2fwx%2fmyoauth2&response_type=code&scope=snsapi_base&state=123#wechat_redirect");

用户点击该菜单,微信根据setUrl中的链接,进入我们开发的myoauth2的action中,在action中得到CODE,然后根据CODE,得到openid和accesstoken以及expires,注意,该accesstoken与基础accesstoken不同。

然后根据openid,判断该openid是否已经绑定了用户,如果已经绑定,则跳转到mydata.jsp,如果未绑定,生成带校验的链接,发到,跳转到绑定页面,让用户输入用户名和密码,用于绑定。

@RequestMapping(value="/myoauth2", produces="text/html;charset=UTF-8")
    public String myoauth2(HttpServletRequest request, HttpServletResponse response) {
		String code = request.getParameter("code");
		System.out.println("code:" + code);
		if(!StringUtils.isBlank(code)) {
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=#APPID&secret=#SECRET&code=#code&grant_type=authorization_code";
			url = url.replace("#APPID", HighlandConstants.WX_APPID)
					.replace("#SECRET", HighlandConstants.WX_APPSECRET)
					.replace("#code", code);
			
			JsonNode rootNode = HttpUtils.httpsRequest(url, "GET", null);
			System.out.println("rootNode: " + rootNode);
			// 生成登录URL
			
			/*
			 	"access_token":"ACCESS_TOKEN",
    			"expires_in":7200,
    			"refresh_token":"REFRESH_TOKEN",
    			"openid":"OPENID",
    			"scope":"SCOPE" 
			 */
			
			String openid = rootNode.get("openid").textValue();
			String accesstoken = rootNode.get("access_token").textValue();
			String expires = rootNode.get("expires_in").textValue();
			String refreshtoken = rootNode.get("refresh_token").textValue();
			
			TbWxuserinfoExample userinfoExample = new TbWxuserinfoExample();
			userinfoExample.createCriteria().andOpenidEqualTo(openid);
			List<TbWxuserinfo> userinfoList = wxuserinfoService.selectByExample(userinfoExample);
			if(userinfoList != null && !userinfoList.isEmpty()) {
				// 已绑定过
				return "redirect:" + "/jsp/weixin/mydata.jsp";
			}
			
			
			String timeStamp = String.valueOf(System.currentTimeMillis());
			String signature = "";
			try {
				signature = SHA1.getSHA1(HighlandConstants.BIND_TOKEN, timeStamp, openid);
				HighlandContainer.MAP_OPENID_SIGNATURE.put(openid, signature);
			} catch (AesException e1) {
				e1.printStackTrace();
			}
			
			String bindurl = "/jsp/weixin/bind.jsp?timeStamp=#timeStamp&openid=#openid&signature=#signature";
			bindurl = bindurl.replace("#timeStamp", timeStamp)
					.replace("#openid", openid)
					.replace("#signature", signature);
			
			System.out.println("bindurl: " + bindurl);
			
			return "redirect:" + bindurl;
			
			
		} else {
			System.out.println("未获取到CODE");
		}
		
		return null;
	}

用于绑定的bing.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<base href="<%=basePath%>">

	<title>绑定帐号</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=no" />
	
	<link type="text/css" rel="stylesheet" href="/css/weixin/weui.css"/>
    <link type="text/css" rel="stylesheet" href="/css/weixin/example.css"/>
	
	<script type="text/javascript" src="/js/jquery-easyui-1.7.6/jquery.min.js"></script>
    <script type="text/javascript" src="/js/jquery-easyui-1.7.6/jquery.easyui.min.js"></script> 
    <script type="text/javascript" src="/js/jquery-easyui-1.7.6/jquery.easyui.mobile.js"></script>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script src="https://res.wx.qq.com/open/libs/weuijs/1.0.0/weui.min.js"></script>
    <script src="/js/weixin/bind.js"></script>
	
</head>

<body>
	<div class="weui-cells__title">请输入用户名密码以绑定微信号</div>
	<div class="weui-cells">
		<div class="weui-cell">
			<div class="weui-cell__bd">
				<input class="weui-input" type="text" id="loginname" placeholder="请输入用户名" />
			</div>
		</div>
		
		<div class="weui-cell">
			<div class="weui-cell__bd">
				<input class="weui-input" type="password" id="password" placeholder="请输入密码" />
			</div>
		</div>
		
		<div id="toast" style="display: none;">
	        <div class="weui-mask_transparent"></div>
	        <div class="weui-toast">
	            <i class="weui-icon-success-no-circle weui-icon_toast"></i>
	            <p class="weui-toast__content" id="mytoast">已完成</p>
	        </div>
    	</div>
		
		<!-- 用于校验链接合法 -->
		<input type="hidden" name="timeStamp" id="timeStamp" value="<%=request.getParameter("timeStamp")%>"> 
		<input type="hidden" name="openid" id="openid" value="<%=request.getParameter("openid")%>">
	</div>

	<div class="button-sp-area" style="margin-top: 2em;">
		<a href="javascript:;" class="weui-btn weui-btn_plain-primary" id="bindwx" onclick="bindwx();" style="width: 60%">绑&nbsp;&nbsp;定</a>
	</div>
	
	
</body>
</html>

用户输入用户名密码后,点击绑定,进入的action:

/**
	 * 绑定用户名和openid
	 * @param loginname
	 * @param password
	 * @param timeStamp
	 * @param openid
	 * @return
	 */
	@RequestMapping(value="/bind", produces="text/html;charset=UTF-8")
	@ResponseBody
    public String bind(HttpServletRequest request, HttpServletResponse response) {
		
		String loginname = request.getParameter("loginname");
		String password = request.getParameter("password");
		String timeStamp = request.getParameter("timeStamp");
		String openid = request.getParameter("openid");
		
		String data = request.getParameter("data");
		
		RtnMsgDto msg = new RtnMsgDto(); 
		try {
			
			if(StringUtils.isBlank(loginname) || StringUtils.isBlank(password)) {
				msg.setMsgCode(1);
				msg.setRtnMsg("请输入用户名和密码");
				return JSON.toJSONString(msg);
			}
			
			if (StringUtils.isBlank(timeStamp) || timeStamp.equals("null")) {
				msg.setMsgCode(1);
				msg.setRtnMsg("未获取到timestamp, 系统异常");
				return JSON.toJSONString(msg);
			}
			
			if (StringUtils.isBlank(openid) || timeStamp.equals("null")) {
				msg.setMsgCode(1);
				msg.setRtnMsg("未获取到openid, 系统异常");
				return JSON.toJSONString(msg);
			}
			
			
			long currentTimestamp = System.currentTimeMillis();
			long hisTimestamp = Long.valueOf(timeStamp);
			if(currentTimestamp > hisTimestamp + 5*60*1000) {
				// 5分钟内有效
				msg.setMsgCode(1);
				msg.setRtnMsg("链接超时,请重新点击");
				return JSON.toJSONString(msg);
			}
			
			
			String hisSignature = HighlandContainer.MAP_OPENID_SIGNATURE.get(openid);
			String signature = SHA1.getSHA1(HighlandConstants.BIND_TOKEN, timeStamp, openid);
			if (hisSignature.equals(signature)) {
				// 插入/更新userinfo表
				// System.out.println("签名通过");
				TbWxuserinfoExample example = new TbWxuserinfoExample();
				example.createCriteria().andFlagEqualTo(1)
				// .andOpenidEqualTo(openid)
				.andLoginnameEqualTo(loginname)
				.andPasswordEqualTo(password);
				
				List<TbWxuserinfo> userinfoList = wxuserinfoService.selectByExample(example);
				
				if (userinfoList == null || userinfoList.isEmpty()) {
					msg.setMsgCode(1);
					msg.setRtnMsg("用户名或密码错误");
					return JSON.toJSONString(msg);
				} else if(userinfoList != null && userinfoList.size() > 1) {
					msg.setMsgCode(1);
					msg.setRtnMsg("数据异常,请联系管理员");
					return JSON.toJSONString(msg);
				} else if(userinfoList != null && userinfoList.size() == 1) {
					TbWxuserinfo update = new TbWxuserinfo();
					update.setUid(userinfoList.get(0).getUid());
					update.setOpenid(openid);
					wxuserinfoService.updateByPrimaryKeySelective(update);
				}
				
				
			} else {
				msg.setMsgCode(1);
				msg.setRtnMsg("签名异常,请重新点击");
				return JSON.toJSONString(msg);
			}
			
			
		
		} catch (Exception e) {
			e.printStackTrace();
			msg.setMsgCode(1);
			msg.setRtnMsg(e.getLocalizedMessage());
		}
		
		return JSON.toJSONString(msg);
    }

 

 

 

 

 

 

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值