微信公众号开发小坑:确认访问的微信是否为已关注公众号,秘钥使用全局access_token不能使用局部变量access_token

环境说明:

1.项目功能:年会抽奖活动开发,子功能:获取客户的相对公众号的唯一oppenid,然后确认是否关注本公众号,关注则获取客户信息后发抽奖券保存,否则先关注微信公众号;

2.java环境:SSM、jdk1.8、tomcat8、jar包直接导入项目、eclipe

小坑说明:判断是否关注微信公众号,使用如下的url 

String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";

关注则返回客户头像昵称等信息,不关注返回subscribe=0;

其中参数access_token为秘钥,分为全局和局部的秘钥,这里只能使用全局秘钥,但是在调试时候验证局部秘钥是否对oppenid有效的时候测试有效,一直使用局部秘钥访问报错,一度怀疑oppenid获取的和本公众号不匹配,最后百度有人说用全局秘钥更换后OK;

注意:全局access_token使用线程每2小时生成一次;

全部代码:、

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%@ page import="net.sf.json.JSONArray"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import="com.hy.system.thread.TokenThread_hy"%>
<%        String code = request.getParameter("code");
        /*根据客户code获取客户openID  */
        String openId = "";    
        String access_token= "";    
        String nickname = "";        //客户昵称
        String headimgurl= "";    //客户头像地址
        String subscribe ="";    //客户是否关注公众号        
        int cont = 1;
        if (code != null) {
             //获取openid连接
             String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx538164e175f2dfaf&secret=2c067baa70a74fce98c22ca7fee55247&code="+code+"&grant_type=authorization_code";         
             try {
                    URL getUrl=new URL(requestUrl);
                    HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
                    http.setRequestMethod("GET");
                    http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
                    http.setDoOutput(true);
                    http.setDoInput(true);
                    http.connect();
                    InputStream is = http.getInputStream();
                    int size = is.available();
                    byte[] b = new byte[size];
                    is.read(b);
                    String message = new String(b, "UTF-8");
                    JSONObject json = JSONObject.fromObject(message);
                    System.out.println("1.返回值集合json="+json);
                    openId = json.getString("openid");        
                    access_token = json.getString("access_token");    
                    cont = 10;
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                }                    
        }        
         //获取客户信息:昵称、头像
        if (openId != "" && openId != null ) {         
             access_token =  TokenThread_hy.access_token.getAccess_token();
             System.out.println("全局秘钥="+access_token);
             System.out.println("openId="+openId);
             String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";     
    
             try {
                    URL getUrl=new URL(requestUrl);
                    HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
                    http.setRequestMethod("GET");
                    http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
                    http.setDoOutput(true);
                    http.setDoInput(true);
                    http.connect();
                    InputStream is = http.getInputStream();
                    int size = is.available();
                    byte[] b = new byte[size];
                    is.read(b);
                    String message = new String(b, "UTF-8");
                    JSONObject json = JSONObject.fromObject(message);
                    System.out.println("2.返回值集合json="+json);
                    subscribe = json.getString("subscribe");    
                    /*为零则未关注本公众号  */
                    if(!("0".equals(subscribe))){
                        nickname = json.getString("nickname");        
                        headimgurl = json.getString("headimgurl");    
                    }                    
                    
                    cont = 11;
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                }                    
        }
        
        
             

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<!--引入微信js接口  -->
<script src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

 


<meta charset="utf-8"><!--控制字体不乱码-->
<title>年会抽奖卡发放、抽奖签到页面</title>
<style type="text/css">

 .index_tc{
 width:100%;
    height:50%;    
 }
 #img11{
    background:url(../img_weixin/beijing2.jpg);
    max-width:100%;
    width:100%;
    height:30%;
 }
  #qianggou{
      background-color: rgba(197, 0, 18, 0.98);
  }
  .row11{color:rgba(197, 0, 18, 0.98);
  text-align:center;
  }
    .row11,.reg1_tit{font-weight:bold}
   #userInfo{width:100%;height:30%;margin-top:15%;}
   #user_headimgurl{width:50px;height:50px;}
 
/*   .panel-body{background:#FFFF99;} */
.panel-body{background:url(../img_weixin/beijing3.png);}
.panel-heading{background:url(../img_weixin/beijing.jpg);}
#pactsMsg{color:#FFFFFF}
#msgPhone{    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;}
#yanzhang{
    width: 60%;
    height: 90px;
        margin: 25px auto;
}
#yanzhengForm{margin-top: 5px;}

#heardimg{width: 80px;height: 80px;}
/*美工戴贝贝css  */

body {margin-left: 0px;margin-top: 0px;margin-right: 0px;margin-bottom: 0px;}
img{vertical-align:bottom;display:block; text-align:center}
.box{ width:100%;    margin:auto; background:#b51622 url(img/s_01.jpg); height:auto;  background-repeat:no-repeat; background-size:100% auto;-webkit-background-size:100% auto;}

.tx{ width:100px; height:100px; margin:50px auto 30px auto; }
.tx img{border-radius:100px; border:8px solid rgba(255,255,255,0.5);   -webkit-border-radius: 50%;
    -moz-border-radius: 50%;}
.text1{ width:50%; height:40px; margin:auto; color: #FFF; text-align: center; font-family:"微软雅黑"; font-size:22px;}
.text2{ width:80%; height:40px; margin:0 auto 20px auto; color: #FFF; text-align: center; font-family: Arial; font-size:25px;}

.nk{ width:90%;  margin:auto; background:#b51622 url(img/s_03.png); height:auto; overflow:hidden;
 background-repeat:no-repeat;
 background-size:100% auto;
 -webkit-background-size:100% auto;
 
}
 
.text3{ width:80%;font-family: Arial; color:#FFF; font-size:22px; float:left; margin:7% 0 11% 10%;  }
 
/* end */

</style>
</head>
<body>


<div id="all">
<!-- 一、客户信息 -->
    <!-- 客户基本信息 -->
    <%-- <div id="userInfo"   align="center">
         <img id="user_headimgurl" src="<%=headimgurl%>"  />
         <h6 id="user_nickname">昵称:<%=nickname%></h6>
    </div>
    <!-- 抽奖券信息 -->
    <div id="choujianguqna" style="background-color: #66CCFF;">        
        <!-- <h3><img id="heardimg" src="http://mo.ys31837777.com/img_weixin/beijing.jpg" ><span id="nicheng">关羽</span></h3>
        <h4 id="tickeId">HJ000012</h4> -->
    </div> --%>
    
    
</div>


<!--客户xixni-->
<div class="box">
<img src="img/logo_01.png" style="max-width:50%; " />
<div class="tx"><img src="<%=headimgurl%>" width="100" height="100"></div>
<div class="text1"><%=nickname%></div>
<div class="text2" id="textNo" >NO: </div>
<h4  style=" width:80%;font-family: Arial; color:#FFF; font-size:15px; float:left; margin:7% 0 11% 10%; "> 说明:查看年会抽奖卡请至"沪佳家装工厂店"微信公众号,正下方菜单栏中主菜单"沪佳家装"下子菜单"年会抽奖卡"!</h4>

<div class="nk" id="nk">
<img src="img/e_07.png" style="max-width:23%; margin:5% 5% 0 0; float:right" />
<div class="text3"></div>
</div>
<img src="img/s_10.png" style="max-width:100%; bottom:0" />
</div>


    

 


</body>
<script type="text/javascript">

    
//客户未关注微信公众号的让其关注,关注过的发送调用微信API的验证请求信息
$(function(){

     var openId =  '<%=openId%>';
     var subscribe =  '<%=subscribe%>';
    
     console.info("subscribe="+subscribe);    
    /*     openId ='46546465dfffddfdff'; */    
     if("0" == subscribe  ){
         console.info("请您先关注'沪佳家装工厂店'公众号后再来领取");
        /*     $("#all").empty();    
         alert("请您先关注'沪佳家装工厂店'公众号后再来领取!") */
         window.location.href="guanzhugongzonghao.html";   //在当前窗口中打开新页面
        
        
     }else{
        
        <%--  var code = '<%=code%>';     --%>        
         /*微信公众号平台 调用其js SDK 接口 的验证请求 */        
        <%--  $.ajax({
            url:"<%=request.getContextPath()%>/weixin/getverifyJSSDKCode_sendTicketAndsignInJSP.do",    
            type:"post",
            dataType:"json",
            data:{"code":code},
            success:function(date){
                //console.info("date="+date);
                console.info(date);
                 /*步骤三:通过config接口注入权限验证配置  */
                 wx.config({
                     debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                     appId: date.appId, // 必填,公众号的唯一标识
                     timestamp: date.timestamp, // 必填,生成签名的时间戳
                     nonceStr: date.nonceStr, // 必填,生成签名的随机串
                     signature: date.signature,// 必填,签名
                     jsApiList: ['addCard'] // 必填,需要使用的JS接口列表
                 });
                 /*
                  wx.error(function (res) {
                        alert("出错了:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
                    });
                  */
                
            }
         }); --%>
    /*保存客户信息到数据库 并显示抽奖券的信息,已经领取过的显示抽奖券的信息 */
         insertUserInfoToData();    
     }    
    });
    
/*保存客户信息到数据库 并显示抽奖券的信息,已经领取过的显示抽奖券的信息 */
function insertUserInfoToData(){
    var nickename =  '<%=nickname%>';
    var headimgurl = '<%=headimgurl%>';        
    var openId =  '<%=openId%>';
/*     
    openId ='46546465dfffddfdff';
    nickename = '张飞2'; */
      var getContextPath = '<%=request.getContextPath()%>';
    console.info("获取的项目路径getContextPath = " + getContextPath);
    
    $.ajax({
        url:"<%=request.getContextPath()%>/weixin/insertUserInfoOrGetLottoleInfo.do",
        type:"post",
        data:{
            "nickename":nickename,
            "headimgurl":headimgurl,
            "openId":openId
            },
        dataType:"json",
        success:function(datas){
            var msg = datas.msg;//结果信息
            var code = datas.code;//结果代码
            console.info("结果信息="+msg);
            console.info("结果代码="+code);
            if(code != 0 ){
                var data = datas.info;//抽奖券信息
                console.info("抽奖券信息="+data);
                console.info(data);
                var jsp ='';    
                jsp +='<img src="img/e_07.png" style="max-width:23%; margin:5% 5% 0 0; float:right" />   ';
                jsp +='<div class="text3">NO:'+data.comment2+'</div>  ';                
                
            $("#nk").empty().append(jsp);        
            $("#textNo").empty().append("NO:"+data.comment2);
        
            
            }else{                    
                alert("网络延时,请重试!");                    
            }
            
         }            
    });
    
}

    //发放年会抽奖券
    function sendLotteryTicket(){    
         var code = '<%=code%>';
         console.info(" code="+code);            
         $.ajax({
                url:"<%=request.getContextPath()%>/weixin/sendTicketLottery.do",    
                type:"post",    
                data:{"code":code},
                dataType:"json",                
                success:function(data){
                    console.info("发放年会抽奖券=");
                    console.info(data);
                     /*发放年会抽奖券  到微信卡包*/
                
                     wx.addCard({
                        cardList: [{
                              cardId: data.cardId,
                              cardExt: '{"code":"", "openid": "'+data.openid+'", "nonce_str":"'+data.nonceStr+'","timestamp": "'+data.timestamp+'", "signature":"'+data.signature+'"}'                        
                        }], // 需要添加的卡券列表
                        success: function (res) {
                            var cardList = res.cardList; // 添加的卡券列表信息
                        }
                    });            
                
                }
            });
            
    }
        
    
</script>
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值