zoukankan      html  css  js  c++  java
  • 微信公众号的分享

    分享的东西页面做的比较多,后台需要去取微信的Access_token  和JsApiTicket  然后再验签

    public class WeixinShare {
        
        private static Map<String,KeyValue> map=new HashMap<String,KeyValue>();
        private static Map<String,String> urlMap=new HashMap<String,String>();
        
        static {
            urlMap.put("http://weixin8020/OhdWeixin/personal/integration.jsp", "http://www.。。。.com/OhdWeixin/UserAction!userSign.action");
            urlMap.put("http://www.。。。.com/OhdWeixin/personal/integration.jsp", "http://www.。。。.com/OhdWeixin/UserAction!userSign.action");
            urlMap.put("http://www.。。。.com/OhdWeixin/personal/personal.jsp", "http://www.。。。.com/OhdWeixin/UserAction!listUser.action");
            urlMap.put("http://weixin8020/OhdWeixin/personal/personal.jsp", "http://www.oohdear.com/OhdWeixin/UserAction!listUser.action");

    //这里可能只需要http://weixin8020开头的的自己网址的链接,因为当初我认为这个没有用 只加的自己的官网的链接地址 ,但是不对 url没有得到
        }

        private WeixinShare() {
        }
        
        /**
         * 获取接口访问凭证,凭证有效时间为7200秒
         * @param appid 凭证
         * @param appsecret 密钥
         * @return
         */
        private static String getAccess_token(String appid, String appsecret) throws Exception {
            if(map.get("access_token")==null || DateTool.getDistanceMinute(map.get("access_token").getDate(), new Date())>=120) {
                String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
                String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
                JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl,"GET",null);
                if (null != jsonObject) {
                    try {
                        KeyValue keyValue=new KeyValue(jsonObject.getString("access_token"),new Date());
                        map.put("access_token", keyValue);
                    }
                    catch(JSONException err) {
                        err.printStackTrace();
                    }
                }
            }
            return map.get("access_token").getValue();
        }
        
        /**
         * 调用微信JS接口的临时票据,凭证有效时间为7200秒
         * @param access_token 接口访问凭证
         * @return
         */
        private static String getJsApiTicket(String access_token) throws Exception {
            if(map.get("ticket")==null || DateTool.getDistanceMinute(map.get("ticket").getDate(), new Date())>=120) {
                String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
                String requestUrl = url.replace("ACCESS_TOKEN", access_token);
                JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl,"GET",null);
                if (null != jsonObject) {
                    try {
                        KeyValue keyValue=new KeyValue(jsonObject.getString("ticket"),new Date());
                        map.put("ticket", keyValue);
                    }
                    catch(JSONException err) {
                        err.printStackTrace();
                    }
                }
            }
            return map.get("ticket").getValue();
        }
            
        private static String byteToHex(final byte[] hash) {
            Formatter formatter = new Formatter();
            for (byte b : hash) {
                formatter.format("%02x", b);
            }
            String result = formatter.toString();
            formatter.close();
            return result;
        }
     
        private static String create_nonce_str() {
            return UUID.randomUUID().toString();
        }
     
        private static String create_timestamp() {
            return Long.toString(System.currentTimeMillis()/1000);
        }
        
        private static String getUrl(){
            HttpServletRequest request = ServletActionContext.getRequest();
            StringBuffer requestUrl = request.getRequestURL();
            String queryString = request.getQueryString();
            String url = requestUrl.toString();
            url=urlMap.get(url);
            if(queryString!=null) url=url+"?"+queryString;
            return url;
        }
        
        private static Map<String, String> sign(String jsapi_ticket, String url) {
            Map<String, String> ret = new HashMap<String, String>();
            String nonce_str = create_nonce_str();
            String timestamp = create_timestamp();
            String str;
            String signature = "";
             //注意这里参数名必须全部小写,且必须有序
            str = "jsapi_ticket=" + jsapi_ticket +
                      "&noncestr=" + nonce_str +
                      "&timestamp=" + timestamp +
                      "&url=" + url;
            try {
                MessageDigest crypt = MessageDigest.getInstance("SHA-1");
                crypt.reset();
                crypt.update(str.getBytes("UTF-8"));
                signature = byteToHex(crypt.digest());
            }
            catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            ret.put("url", url);
            ret.put("jsapi_ticket", jsapi_ticket);
            ret.put("nonceStr", nonce_str);
            ret.put("timestamp", timestamp);
            ret.put("signature", signature);
            return ret;
        }
        
        /**
         *
         * @param appId   公账号appId
         * @param appSecret
         * @param url    当前网页的URL,不包含#及其后面部分
         * @return
         */
        public static JSONObject getParam() throws Exception {
            String jsapi_ticket=getJsApiTicket(getAccess_token(CommonUtil.appId,CommonUtil.appSecret));
            String url = getUrl();
            Map<String, String> params = sign(jsapi_ticket, url);
            params.put("appid", CommonUtil.appId);
            JSONObject jsonObject = JSONObject.fromObject(params);  
            return jsonObject;
        }
        
        public static void main(String args[]) throws Exception {
            String appId="";
            String appsecret="";
            
            System.out.println("getAccess_token:"+getAccess_token(appId,appsecret));
            System.out.println("getJsApiTicket:"+getJsApiTicket(getAccess_token(appId,appsecret)));
        }
        
        private static class KeyValue {
            
            private String value=null;
            private Date date=null;
            
            public KeyValue(String value,Date date) {
                this.value=value;
                this.date=date;
            }

            public String getValue() {
                return value;
            }

            public Date getDate() {
                return date;
            }
        }

    前台jsp需要做的是:  调用WeixinShare.getParam();

    <head>
        <title></title>
        <meta content="initial-scale=1.0,user-scalable=no,maximum-scale=1,width=device-width" name="viewport">
        <meta content="yes" name="apple-mobile-web-app-capable">
        <meta content="black" name="apple-mobile-web-app-status-bar-style">
        <meta content="telephone=no" name="format-detection">
        <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.7.1.min.js"></script>
        <script type="text/javascript" src="<%=request.getContextPath()%>/js/alertPopShow.js"></script>
        <script type="text/javascript" src="<%=request.getContextPath()%>/js/setFont.js"></script>
        <link rel="stylesheet" href="<%=request.getContextPath()%>/css/alert.css">
        <link rel="stylesheet" href="<%=request.getContextPath()%>/css/reset.css">
        <link href="<%=request.getContextPath()%>/css/integration.css" rel="stylesheet">
        <%
        JSONObject jsonObject=WeixinShare.getParam();
        String openid=(String)session.getAttribute("openid");
        %>
        <script src="<%=request.getContextPath()%>/js/jweixin-1.2.0.js"></script>
        <script>
        wx.config({
            debug:false,
            appId:'<%=jsonObject.getString("appid")%>',
            timestamp:'<%=jsonObject.getString("timestamp")%>',       
            nonceStr:'<%=jsonObject.getString("nonceStr")%>',
            signature:'<%=jsonObject.getString("signature")%>',
            jsApiList:[
                'checkJsApi',
                'onMenuShareTimeline',
                'onMenuShareAppMessage'
            ]
        });
        wx.ready(function () {
            //分享朋友圈
            wx.onMenuShareTimeline({
               title:'分享得积分',
               link:'http://www.。。。.com/OhdWeixin/invitation.jsp?recommender=${bindWxUser.mobile}',
               imgUrl:'http://www.。。。.com/OhdWeixin/images/pheader.png',
               success: function () {
                // 用户确认分享后执行的回调函数
               }
            });
            //分享给朋友
            wx.onMenuShareAppMessage({
                title:'快快去分享给你的朋友吧可以得积分哦!!',
                desc:'开业大吉',
                link:'http://www.。。。.com/OhdWeixin/invitation.jsp?recommender=${bindWxUser.mobile}',
                imgUrl:'http://www.。。。.com/OhdWeixin/images/pheader.png',
                type:'',
                dataUrl:'',
                success: function () {
                    // 用户确认分享后执行的回调函数
                }
            });
        });
        wx.error(function (res) {
            alert(res.errMsg);  //打印错误消息。及把 debug:false,设置为debug:ture就可以直接在网页上看到弹出的错误提示
        });
        </script>

  • 相关阅读:
    ES6(二)解构赋值详解
    面试题
    说出x的结果,并解释为什么?
    23种设计模式
    自定义滚动条
    JavaScript之数据类型
    [[转]CSS浮动原理
    正选反选JS
    让2个并列的div根据内容自动保持同等高度js
    jquery鼠标滑过展示图片时显示详情
  • 原文地址:https://www.cnblogs.com/xiaoxiaojuan/p/7245312.html
Copyright © 2011-2022 走看看