微信公众号页面授权+消息推送

一、微信端配置

  • 1、微信公众号进行微信认证。
  • 2、配置微信调用接口、按照微信要求需要进行页面授权获取用户的Openid,(这里注意一下、他会提示有个微信文件要放在项目的根目录下面,如:wx.qq.com/mp/MP_verify_7aS4leptvrYzJEsn.txt )。服务器一定要开通80端口,不要使用IP访问的地址,使用加了域名的地址。在这里插入图片描述
  • 3、配置微信公众号页面授权。在这里插入图片描述

4、配置调用接口的链接(项目链接:加域名后的。)。业务域名,JS接口安全域名,页面授权域名三个都要配置。
在这里插入图片描述
5、以上配置通过后、查看开发者文档、页面授权。来获取用户的codeid。在获取codeid前,先获取微信平台的AppID,AppSecret,填写IP白名单。(公众号开发信息)
在这里插入图片描述
6、打开公众号开发者文档、查看网页授权的步骤。第一步、更具维系提供的接口进行相对应参数的配置。
https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信公众号的APPID&redirect_uri=需要授权的地址&response_type=code&scope=snsapi_userinfo&state=a-zA-Z0-9#wechat_redirect

scope分为两种授权,
1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)

2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
在这里插入图片描述
7、微信公众号配置微信授权链接。
在这里插入图片描述

二、以上为微信公众号配置链接、已下为项目代码配置。
1、后台代码:

//页面授权后获得的code
String code = request.getParameter("code");
		request.setAttribute("code", code);
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
		HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);
		String resultMap = restTemplate .postForObject( "https://api.weixin.qq.com/sns/oauth2/access_token?appid=微信公众号的appid&secret=AppSecret(开发者秘钥)&code="+code+"&grant_type=authorization_code", requestEntity, String.class);
		request.setAttribute("resultMap", resultMap);

2、页面代码:

<script type="text/javascript">
//注释掉的为记住密码。
 /*  function tijiao(){
  		//简单验证一下  
    var userName = document.getElementById("username").value;  
    if(userName == ''){  
        alert("请输入用户名。");  
        return;  
    }  
    var userPass = document.getElementById("password").value;  
    if(userPass == ''){  
        alert("请输入密码。");  
        return;  
    }  
    var objChk = document.getElementById("chkRememberPass");  
    if(objChk.checked){  
        //添加cookie  
        addCookie("userName",userName,7,"/");  
        addCookie("userPass",userPass,7,"/");  
    }
	  var data = { username: $("#username").val(),
	  				password: $("#password").val(),
	  				currpage:$("#currpage").val(),
	 			};
     $.ajax({
	   type: "POST",
	   contentType: 'application/json',
	   url: "webQualityClear/getuser",
	   data: JSON.stringify(data),
	   success: function(reginlst){
	   		if(reginlst.success) {   		
	   		  	window.location.href = "webQualityClear/getcontent/"+reginlst.gongqu+"/"+reginlst.quanx;
	   		}else{
	   			alert("输入的账号密码错误!");
	   		}
	   }
	});
    				
  } */
  
 /* function addCookie(name,value,days,path){   //添加设置cookie 
    var name = escape(name);  
    var value = escape(value);  
    var expires = new Date();  
    expires.setTime(expires.getTime() + days * 3600000 * 24);  
    //path=/,表示cookie能在整个网站下使用,path=/temp,表示cookie只能在temp目录下使用  
    path = path == "" ? "" : ";path=" + path;  
    //GMT(Greenwich Mean Time)是格林尼治平时,现在的标准时间,协调世界时是UTC  
    //参数days只能是数字型  
    var _expires = (typeof days) == "string" ? "" : ";expires=" + expires.toUTCString();  
    document.cookie = name + "=" + value + _expires + path;  
}   */
/* function getCookieValue(name){  //获取cookie的值,根据cookie的键获取值  
    //用处理字符串的方式查找到key对应value  
    var name = escape(name);  
    //读cookie属性,这将返回文档的所有cookie  
    var allcookies = document.cookie;         
    //查找名为name的cookie的开始位置  
    name += "=";  
    var pos = allcookies.indexOf(name);      
    //如果找到了具有该名字的cookie,那么提取并使用它的值  
    if (pos != -1){                                             //如果pos值为-1则说明搜索"version="失败  
        var start = pos + name.length;                  //cookie值开始的位置  
        var end = allcookies.indexOf(";",start);        //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置  
        if (end == -1) end = allcookies.length;        //如果end值为-1说明cookie列表里只有一个cookie  
        var value = allcookies.substring(start,end); //提取cookie的值  
        return (value);                           //对它解码        
    }else{  //搜索失败,返回空字符串  
        return "";  
    }  
}  
  
//实现功能,保存用户的登录信息到cookie中。当登录页面被打开时,就查询cookie  
window.onload = function(){  
    var userNameValue = getCookieValue("userName");  
    document.getElementById("username").value = userNameValue;  
    var userPassValue = getCookieValue("userPass");  
    document.getElementById("password").value = userPassValue;  
}    */
//此处为获取用户信息
  var jsonData =  ${resultMap};
  function tijiao(){
   var openid = jsonData.openid;
   var username = document.getElementById("username").value; 
    var password = document.getElementById("password").value; 
    if(username == ''){  
        alert("请输入绑定账号");  
        return;  
    }else{  
	  	  $.ajax({
				type:"post",
				async:false,
				data:{openid:openid,username:username,password:password,},
				url : "damaction.do?wxAjaxJson",// 请求的action路径
				success : function(data) {
					var d = $.parseJSON(data);
					var con = d.msg;
					var ini = d.obj;
					if(ini = "1"){
					messageBox.show(con, 1, 1000);
					}else{
					messageBox.show(con, 1, 1000);
					}
				}
			});
	    }
    }
</script>
<body>
<div id="wrapper">
<input id="code" name="code" type="hidden" value="${code}">
		<div class="login">
	    	<div class="login-container">
	    		<div style="position:relative;bottom:60px;"><img src="plug-in/wx/assets/images/weixin.png"></div>
	    		<div class="form-box">
		    		<ul class="input">
		    			<li>
		    				<i class="cz-skdb">&#xe61f;</i>
		    				<input class="username" name="username" type="text" id="username" title="用户名" iscookie="true" value=""  placeholder="请输入绑定账号"  nullmsg="请输入绑定账号" />
		    			</li>
		    			<li>
		    				<i class="cz-skdb">&#xe61e;</i>
		    				<input class="password" name="password" type="password" id="password" title="密码" value="" nullmsg="请输入密码!"  placeholder="请输入密码"  />
		    			</li>
		    		</ul>
		    		<!-- <ul>
		    			<li align="center" colspan="2">
	             			 <span style="font-size:15px; color:blue; vertical-align:middle;">是否记住密码</span>  
	            			 <input type="checkbox" id="chkRememberPass" name="chkRememberPass" style="vertical-align:middle;width:20px;height:20px;" />  
	          			 </li>
		    		</ul> -->
		    		<ul class="button" onclick="tijiao()">
		    			<li>
		    				<input class="submit" type="submit" value="绑定已有账号" />	
		    			</li>	    			
		    		</ul>
	    		</div>
	    	</div>
		</div>
</div>
</body>
</html>

3、微信消息推送。先在微信公众平台设置模板,获取模板ID。

//获取需要推送人的openid
//获取当前时间
		Date day=new Date();    
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 	
//查询模板ID
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
		HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>(postParameters,headers);
//调取access_token
		String resultMap = restTemplate .postForObject( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret, requestEntity, String.class);
		
		JSONObject jsonObject = JSONObject.fromObject(resultMap);
		JSONObject datas = new JSONObject();
		//String access_token = "123";
		String access_token = jsonObject.getString("access_token").toString();
		datas.put("touser",id);
		datas.put("template_id",maptj.get("template_id").toString());
		JSONObject data = new JSONObject();
		JSONObject data1 = new JSONObject();
		data1.put("value", mapname.get("btname"));//标题
		JSONObject data2 = new JSONObject();
		data2.put("value", names);//审核人
		JSONObject data3 = new JSONObject();
		data3.put("value", name);//提交人
		JSONObject data4 = new JSONObject();
		data4.put("value", map.get("FSDYGCMC").toString()+" ; "+ mapqbs.get("FSQBSMC").toString());//工序表
		JSONObject data5 = new JSONObject();
		data5.put("value", fsgc +";"+ FSZH);//桩号
		JSONObject data6 = new JSONObject();
		data6.put("value", df.format(day));//提交时间
		JSONObject data7 = new JSONObject();
		data7.put("value", mapname.get("jwname"));//下标
		data.put("first", data1);
		data.put("keyword1", data2);
		data.put("keyword2", data3);
		data.put("keyword3", data4);
		data.put("keyword4", data5);
		data.put("keyword5", data6);
		data.put("remark",data7);
		datas.put("data", data.toString());
		String resultMaps = restTemplate .postForObject( "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token, datas, String.class);

猜你喜欢

转载自blog.csdn.net/qq_43420577/article/details/83060869