Home > WeChat Applet > WeChat Development > About the implementation code of WeChat's custom sharing function

About the implementation code of WeChat's custom sharing function

不言
Release: 2018-07-26 09:58:08
Original
4889 people have browsed it

The content of this article is about the implementation code of WeChat’s custom sharing function. The content is very detailed. Friends in need can refer to it. I hope it can help you.

Front-end During the time, I developed an information project, but when the sales department promoted WeChat, the shared link was directly a web link plus a sharing symbol, which was ugly and irregular, so I studied the customized sharing function of WeChat

Preparatory work:

1. Certify the appId and appSecret of the public account

2. Various links to obtain WeChat information (look for WeChat custom sharing API in this section, address: https:// mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115)

# 获取access_token请求地址
  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/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code
  # 获取用户基本信息请求地址
  getUserInfoUrl: https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN
  #获取code
  getCodeUrl: https://open.weixin.qq.com/connect/oauth2/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
Copy after login

3.controller layer

/**
     * 微信配置信息实体
     */
    @Autowired
    private WeiXinProperties weiXinProperties;
    //微信参数
    private String accessToken;
    private String jsApiTicket;
    //获取参数的时刻
    private Long getTiketTime = 0L;
    private Long getTokenTime = 0L;
    //参数的有效时间,单位是秒(s)
    private Long tokenExpireTime = 0L;
    private Long ticketExpireTime = 0L;

 /**
     * 微信自定义分享
     */
    @RequestMapping(value = "/getShareInfo", method = RequestMethod.POST)
    public Map<String, String> getShareInfo(HttpServletRequest request,
                                            HttpServletResponse response, String url) {
        //当前时间
        long now = System.currentTimeMillis();

        //判断accessToken是否已经存在或者token是否过期
        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的时间
                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是否已经存在或者是否过期
        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~");
            }
        }
        //生成微信权限验证的参数
        Map<String, String> 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
        // 通过acessToken 获取ticket
        String requestUrl = String.format(weiXinProperties.getGetTicketUrl(), access_token);
        String result = send(requestUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject;
    }

    //生成微信权限验证的参数
    public Map<String, String> makeWXTicket(String jsApiTicket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsApiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + 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;
    }

    /**
     * 发送请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    String send(String url) {
        return HttpClientTools.post(url);
    }

    //字节数组转换为十六进制字符串
    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 createNonceStr() {
        return UUID.randomUUID().toString();
    }

    //生成时间戳
    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
Copy after login

4. Introduce share.js. The page to be shared

$(function(){
    var url = location.href.split(&#39;#&#39;).toString();//url不能写死
    $.ajax({
        type : "post",
        url : "/user/login/getShareInfo",
        dataType : "json",
        async : false,
        data:{url:url},
        success : function(data) {
            wx.config({
                debug: false,////生产环境需要关闭debug模式
                appId: data.appid,//appId通过微信服务号后台查看
                timestamp: data.timestamp,//生成签名的时间戳
                nonceStr: data.nonceStr,//生成签名的随机字符串
                signature: data.signature,//签名
                jsApiList: [//需要调用的JS接口列表
                    &#39;checkJsApi&#39;,//判断当前客户端版本是否支持指定JS接口
                    &#39;onMenuShareTimeline&#39;,//分享给好友
                    &#39;onMenuShareAppMessage&#39;//分享到朋友圈
                ]
            });
        },
        error: function(xhr, status, error) {
            //alert(status);
            //alert(xhr.responseText);
        }
    })
});
Copy after login

5. Introduce the core js and share.js shared by WeChat into the page to be shared

<script type="text/javascript" src="/resources/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="/resources/js/share.js"></script>
Copy after login

6. In the current page

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template