首页 > 微信 > 详细

微信js分享第三方链接

时间:2019-05-07 18:21:28      阅读:151      评论:0      收藏:0      [点我收藏+]
  1. 公众号配置

  2. 后台接口

  3. 前端js

  4. 个别问题解决方法

 

 


 

1、公众号配置

  前提:公众号必须经过认证

  登录公众号 ------> 公众号配置 ------> 功能设置

  找到“JS接口安全域名”,配置域名(域名必须经过认证)

  具体规则如下

  【以百度域名为例,下面输入框中填写的就是www.baidu.com(不知道只写baidu.com能不能行)】

  【如果填写的指定路径,那么分享的页面需在此路径下】

  技术分享图片

 

2、后台接口

  控制层

  注:

  其中HttpUtils 中只使用了httpGet 来请求微信api接口

  RedisClient把token和ticket保存进redis,限制过期时间

  getSiteConfig仅仅用来获取appid和secrect

  加密的工具类在控制层的代码下面

  

package com.mingtai.yuqing.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.mingtai.base.model.ApiResult;
import com.mingtai.yuqing.common.redis.RedisClient;
import com.mingtai.yuqing.common.util.HttpUtils;
import com.mingtai.yuqing.plat.tenant.service.ITenantService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
import static com.mingtai.yuqing.common.util.SHA1.SHA1;

@RestController
@RequestMapping("/wx/js/")
public class WxJsConfigController {

    @Autowired
    private ITenantService tenantService;
    private static final Integer siteId = 180;
    private String token = null;
    private String appId = null;
    private String secret = null;
    private String ticket = null;

    /**
     * 获取微信JS配置信息
     * @param url
     * @param datetime
     * @return
     * @throws Exception
     */
    @RequestMapping("getConfig")
    public ApiResult getConfig(String url, String datetime) throws Exception {
        String key = "wx.ticket." + this.siteId;
        String nowTicket = RedisClient.get(key);
        getSiteConfig();
        if (StringUtils.isBlank(nowTicket)) {
            getAccessToken();
            getTicket(key);
        } else {
            this.ticket = nowTicket;
        }
        //随机字符串
        String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        //时间戳
        String timestamp = datetime;
        //生成内容
        url = url + "&t=" + datetime;
        String str = "jsapi_ticket=" + this.ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        String signature = SHA1(str);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", this.appId);
        jsonObject.put("timestamp", timestamp);
        jsonObject.put("nonceStr", nonceStr);
        jsonObject.put("signature", signature);
        return new ApiResult(jsonObject);
    }

    public void getAccessToken() throws Exception {
        String key = "wx.token." + this.siteId;
        String accessToken = RedisClient.get(key);
        if (StringUtils.isBlank(accessToken)) {
            String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
            tokenUrl = tokenUrl.replace("APPID", this.appId).replace("APPSECRET", this.secret);
            String result = HttpUtils.doGet(tokenUrl);
            JSONObject json = JSONObject.parseObject(result);
            String newToken = json.getString("access_token");
            Integer expireTime = json.getInteger("expires_in");
            this.token = newToken;
            RedisClient.set(key, newToken, expireTime - 10);
        } else {
            this.token = accessToken;
        }
    }

    public void getTicket(String key) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + this.token + "&type=jsapi";
        String nowTicket = RedisClient.get(key);
        String result = HttpUtils.doGet(url);
        JSONObject json = JSONObject.parseObject(result);
        nowTicket = json.getString("ticket");
        Integer expireTime = json.getInteger("expires_in");
        this.ticket = nowTicket;
        RedisClient.set(key, nowTicket, expireTime - 10);
    }

    private void getSiteConfig() {
        String allConfig = tenantService.getTenantById(this.siteId).getTeExpandField();
        JSONObject jsonObject = JSONObject.parseObject(allConfig);
        this.appId = jsonObject.getString("appId");
        this.secret = jsonObject.getString("secret");
    }


}

  工具类

  

package com.mingtai.yuqing.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1 {

    public static String SHA1(String decript) throws UnsupportedEncodingException {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes("utf-8"));
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            //转为十六进制
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}

 

3、前端JS

  注:需先调用wxJsConfig方法

//微信js配置
    wxJsConfig: function (config) {
        wx.config({
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: [
                ‘updateAppMessageShareData‘,
                ‘updateTimelineShareData‘,
                ‘onMenuShareAppMessage‘,  //旧的接口,即将废弃
                ‘onMenuShareTimeline‘ //旧的接口,即将废弃
            ]
        });
    },
    //微信分享
    wxJsShare: function (data) {
        //自定义“分享给朋友”及“分享到QQ”按钮的分享内容
        wx.ready(function () {
            wx.updateAppMessageShareData({
                title: data.title,
                desc: data.desc,
                link: data.link,
                imgUrl: data.imgUrl,
                success: function () {
                    console.log("自定义分享1");
                }
            });
        });
        //自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
        wx.ready(function () {
            wx.updateTimelineShareData({
                title: data.title,
                link: data.link,
                imgUrl: data.imgUrl,
                success: function () {
                    console.log("自定义分享2");
                }
            });
        });
    }

 

4、个别问题解决方法

  注:只作补充,具体问题解决方法见官方JS文档----附录5

  (1)可以使用“微信开发者工具”来调试

  (2)“js-sdk 没有此SDK或暂不支持此SDK模拟”。

    微信开发者工具不支持此方法的调用,用手机上的微信是没问题的。

    例如:updateAppMessageShareData

微信js分享第三方链接

原文:https://www.cnblogs.com/ys382815832/p/10826960.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!