微信自定義分享

  1. 前端
var vxurl = location.href.split('#')[0];
 $.ajax({
        type: "POST",
        url: path + "/m/product/*",
        dataType: "json",
        data: JSON.stringify(encodeURIComponent(vxurl)),
        async: false,
        success: function (res) {
            if(res.success){
                var config = res.data.data;
                console.log(config)
                wx.config({
                    debug: false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
                    appId: config.appId, // 必填,公衆號的唯一標識
                    timestamp : config.timestamp, // 必填,生成簽名的時間戳
                    nonceStr: config.nonceStr, // 必填,生成簽名的隨機串
                    signature: config.signature,// 必填,簽名,見附錄1
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage']// 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
                });

                wx.ready (function () {
                    // 微信分享的數據  
                    var shareData = {
                        "imgUrl" : 'http://**/images/single-title.jpg',
                        "link" : config.link, 
                        "desc" : shareDesc,   // 分享描述  
                        "title" : shareTitle,   // 分享標題  
                        success : function () {
                        }
                    }
                    wx.onMenuShareTimeline (shareData);   
                    wx.onMenuShareAppMessage (shareData);   
                });  
            }
        },
        error: function(a, b) {
            alert("error")
        }
    });

2 後端

@RequestMapping(value = "/set", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void set(HttpServletRequest request,HttpServletResponse response,@RequestBody String requestBody) {
        try {
            ResponseVo responseVo = new ResponseVo();
            String searchtext=URLDecoder.decode(requestBody,"UTF-8");
             String url = searchtext.substring(1, searchtext.length()-2);

             String appId = "wx0a5665a6*******";
             String AppSecret = "4fac1f122123a00ba39d0715391*****";

             TokenResponse tokenVo = null;
             JSTicketResponse ticketVo = null;

             String key = "WX_JSAPITICKET*";
             String jsapiTicket = cacheService.getStrValue(key);
             LOGGER.info("1.獲取緩存:{}", jsapiTicket);
             String signature = null;
             if(jsapiTicket == null){
                try {
                    String tokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+AppSecret;

                    String jsonObject = HttpClientUtil.get(tokenURL, 60000);
                    LOGGER.info("2.獲取token,url:{},result:{}", tokenURL,jsonObject);
                    tokenVo = JsonFormatter.toObject(jsonObject.toString(), TokenResponse.class);
                    if(null != tokenVo && !tokenVo.getAccess_token().isEmpty()){
                        String ticketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+tokenVo.getAccess_token()+"&type=jsapi";
                        String res = HttpClientUtil.get(ticketURL, 60000);
                        ticketVo = JsonFormatter.toObject(res.toString(), JSTicketResponse.class);
                        LOGGER.info("3.獲取ticket,url:{},result:{}",ticketURL, res);
                        if(null != ticketVo ){
                            cacheService.setJsonVlaueForRedis(key, ticketVo.getTicket(), ticketVo.getExpires_in());
                            jsapiTicket = ticketVo.getTicket();
                        }
                    }else{
                        LOGGER.error("獲取token爲空");
                    }
                } catch (Exception e) {
                      LOGGER.error("獲取異常", e);
                }
            }

            WXconfig config = new WXconfig();
            String nonce_str = create_nonce_str();
            String timestamp = create_timestamp();
            String string1 = "jsapi_ticket=" + jsapiTicket +
                    "&noncestr=" + nonce_str +
                    "&timestamp=" + timestamp +
                    "&url=" + url;
            LOGGER.info("4.驗籤string1:{}", string1);
            signature = DigestUtils.shaHex(string1);

            config.setLink(url);
            config.setAppId(appId);
            config.setTimestamp(timestamp);
            config.setNonceStr(nonce_str);
            config.setSignature(signature);
            responseVo.setData(config);
            TNCUtils.setResponseVo(response, responseVo, null);
        } catch (Exception e) {
            LOGGER.error("cleancache Exception", e);
        }

3.項目要能直接訪問該文件:MP_verify_XheMvg3q1lQU1Epf.txt ,文件內容XheMvg3q1lQU1Epf
http://**/inm/MP_verify_XheMvg3q1lQU1Epf.txt

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章