真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

微信開(kāi)發(fā)中自定義分享功能怎么實(shí)現(xiàn)

這篇文章主要介紹微信開(kāi)發(fā)中自定義分享功能怎么實(shí)現(xiàn),文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),贛縣企業(yè)網(wǎng)站建設(shè),贛縣品牌網(wǎng)站建設(shè),網(wǎng)站定制,贛縣網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷(xiāo),網(wǎng)絡(luò)優(yōu)化,贛縣網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M(mǎn)足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專(zhuān)業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶(hù)成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。

前端時(shí)間,開(kāi)發(fā)了一個(gè)資訊類(lèi)的項(xiàng)目,但銷(xiāo)售部門(mén)進(jìn)行微信推廣時(shí),分享的鏈接直接是網(wǎng)頁(yè)鏈接加分享符號(hào),即難看又不正規(guī),于是研究了一下微信自定義的分享功能

前期準(zhǔn)備工作:

1.認(rèn)證公眾號(hào)的appId,appSecret

2.各種獲取微信信息鏈接(此部分查找微信自定義分享API,地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115)

# 獲取access_token請(qǐng)求地址
  getAccessTokenUrl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s
  #獲取accessToken
  getAccessTokenOAuthUrl: https://api.weixin.qq.com/sns/oauth3/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code
  # 獲取用戶(hù)基本信息請(qǐng)求地址
  getUserInfoUrl: https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN
  #獲取code
  getCodeUrl: https://open.weixin.qq.com/connect/oauth3/authorize?appid=%s&redirect_uri=%s&response_type=%s&scope=%s&state=%s#wechat_redirect
  #獲取ticket
  getTicketUrl: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi

3.controller層

/**
     * 微信配置信息實(shí)體
     */
    @Autowired
    private WeiXinProperties weiXinProperties;
    //微信參數(shù)
    private String accessToken;
    private String jsApiTicket;
    //獲取參數(shù)的時(shí)刻
    private Long getTiketTime = 0L;
    private Long getTokenTime = 0L;
    //參數(shù)的有效時(shí)間,單位是秒(s)
    private Long tokenExpireTime = 0L;
    private Long ticketExpireTime = 0L;

 /**
     * 微信自定義分享
     */
    @RequestMapping(value = "/getShareInfo", method = RequestMethod.POST)
    public Map getShareInfo(HttpServletRequest request,
                                            HttpServletResponse response, String url) {
        //當(dāng)前時(shí)間
        long now = System.currentTimeMillis();

        //判斷accessToken是否已經(jīng)存在或者token是否過(guò)期
        if (StringUtils.isBlank(accessToken) || (now - getTokenTime > tokenExpireTime * 1000)) {
            JSONObject tokenInfo = getAccessToken();
            if (tokenInfo != null) {
                accessToken = tokenInfo.getString("access_token");
                tokenExpireTime = tokenInfo.getLongValue("expires_in");
                //獲取token的時(shí)間
                getTokenTime = System.currentTimeMillis();
                log.info("accessToken====>" + accessToken);
                log.info("tokenExpireTime====>" + tokenExpireTime + "s");
                log.info("getTokenTime====>" + getTokenTime + "ms");
            } else {
                log.info("====>tokenInfo is null~");
                log.info("====>failure of getting tokenInfo,please do some check~");
            }
        }
        //判斷jsApiTicket是否已經(jīng)存在或者是否過(guò)期
        if (StringUtils.isBlank(jsApiTicket) || (now - getTiketTime > ticketExpireTime * 1000)) {
            JSONObject ticketInfo = getJsApiTicket(accessToken);
            if (ticketInfo != null) {
                log.info("ticketInfo====>" + ticketInfo.toJSONString());
                jsApiTicket = ticketInfo.getString("ticket");
                ticketExpireTime = ticketInfo.getLongValue("expires_in");
                getTiketTime = System.currentTimeMillis();
                log.info("jsApiTicket====>" + jsApiTicket);
                log.info("ticketExpireTime====>" + ticketExpireTime + "s");
                log.info("getTiketTime====>" + getTiketTime + "ms");
            } else {
                log.info("====>ticketInfo is null~");
                log.info("====>failure of getting tokenInfo,please do some check~");
            }
        }
        //生成微信權(quán)限驗(yàn)證的參數(shù)
        Map wechatParam = makeWXTicket(jsApiTicket, url);
        return wechatParam;

    }

    //獲取accessToken
    private JSONObject getAccessToken() {
        //String accessTokenUrl = https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        //獲取微信端的accessToken
        String requestUrl = String.format(weiXinProperties.getGetAccessTokenUrl(), weiXinProperties.getAppId(), weiXinProperties.getAppSecret());
        String result = send(requestUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject;
    }

    //獲取ticket
    private JSONObject getJsApiTicket(String access_token) {
        //String apiTicketUrl = https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
        // 通過(guò)acessToken 獲取ticket
        String requestUrl = String.format(weiXinProperties.getGetTicketUrl(), access_token);
        String result = send(requestUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject;
    }

    //生成微信權(quán)限驗(yàn)證的參數(shù)
    public Map makeWXTicket(String jsApiTicket, String url) {
        Map ret = new HashMap();
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意這里參數(shù)名必須全部小寫(xiě),且必須有序
        string1 = "jsapi_ticket=" + jsApiTicket +
                "&noncestr=" + nonceStr +
                "×tamp=" + timestamp +
                "&url=" + url;
        log.info("String1=====>" + string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            log.info("signature=====>" + signature);
        } catch (NoSuchAlgorithmException e) {
            log.error("WeChatController.makeWXTicket=====Start");
            log.error(e.getMessage(), e);
            log.error("WeChatController.makeWXTicket=====End");
        } catch (UnsupportedEncodingException e) {
            log.error("WeChatController.makeWXTicket=====Start");
            log.error(e.getMessage(), e);
            log.error("WeChatController.makeWXTicket=====End");
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsApiTicket);
        ret.put("nonceStr", nonceStr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", weiXinProperties.getAppId());

        return ret;
    }

    /**
     * 發(fā)送請(qǐng)求
     *
     * @param url
     * @return
     * @throws Exception
     */
    String send(String url) {
        return HttpClientTools.post(url);
    }

    //字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串
    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;
    }

    //生成隨機(jī)字符串
    private static String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    //生成時(shí)間戳
    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

4.引入share.js.要分享的頁(yè)面

$(function(){
    var url = location.href.split('#').toString();//url不能寫(xiě)死
    $.ajax({
        type : "post",
        url : "/user/login/getShareInfo",
        dataType : "json",
        async : false,
        data:{url:url},
        success : function(data) {
            wx.config({
                debug: false,////生產(chǎn)環(huán)境需要關(guān)閉debug模式
                appId: data.appid,//appId通過(guò)微信服務(wù)號(hào)后臺(tái)查看
                timestamp: data.timestamp,//生成簽名的時(shí)間戳
                nonceStr: data.nonceStr,//生成簽名的隨機(jī)字符串
                signature: data.signature,//簽名
                jsApiList: [//需要調(diào)用的JS接口列表
                    'checkJsApi',//判斷當(dāng)前客戶(hù)端版本是否支持指定JS接口
                    'onMenuShareTimeline',//分享給好友
                    'onMenuShareAppMessage'//分享到朋友圈
                ]
            });
        },
        error: function(xhr, status, error) {
            //alert(status);
            //alert(xhr.responseText);
        }
    })
});

5.在要分享的頁(yè)面中引入,微信分享的核心js和share.js


6.在當(dāng)前頁(yè)面