java版微信获取jssdk的config信息案例

发布时间:2024年01月22日

自行准备appid各种东西

1.controller

    @Operation(summary = "获取微信jssdk的配置", description = "获取微信jssdk的配置")
    @GetMapping("/getWxJssdkConfig")
    public R<Map<String,String>> getWxJssdkConfig(
            @RequestParam(value = "url") String url
    ) throws IOException {
        return R.success(menuConfigService.getWxJssdkConfig(url));
    }

2.service


    @Autowired
    StringRedisTemplate redisTemplate; // 因为一天内不能重复获取太多

    @Override
    public Map<String, String> getWxJssdkConfig(String myUrl) throws IOException {
        try {
            String ticket = null;
            String cacheKey = CacheConfig.CACHE_WEIXIN_JSSDK_KEY;
            if(redisTemplate.hasKey(cacheKey)){
                ticket = redisTemplate.opsForValue().get(cacheKey);
                if(StrUtil.isBlank(ticket)){
                    clearCache(cacheKey);
                    getWxJssdkConfig(myUrl);
                }
            }else{
                URL url = new URL(WeChatConfig.TOKEN_URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println(response.toString());  // 这里会输出access_token和其他相关信息
                JSONObject entries = JSONUtil.parseObj(response.toString());
                String token = entries.getStr("access_token");
                String ticketResponse = HttpUtil.get(WeChatConfig.TICKET_URL + token);
                System.out.println(ticketResponse);
                JSONObject ticketRes = JSONUtil.parseObj(ticketResponse.toString());
                ticket = ticketRes.getStr("ticket");
                // 设置缓存
                redisTemplate.opsForValue().set(cacheKey, ticket,  7000, TimeUnit.SECONDS);
            }
            return sign(ticket, myUrl);
        } catch (Exception e) {
            redisTemplate.delete(CacheConfig.CACHE_WEIXIN_JSSDK_KEY);
            throw e;
        }
    }


    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);
    }

3.sign方法

public 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 string1;
        String signature = "";

        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException | 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);
        ret.put("appid", WeChatConfig.WECHAT_PUBLIC_APPID); // 这里设置APPID

        return ret;
    }

4.前端

写在一起了,注意区分

<script src="//res2.wx.qq.com/open/js/jweixin-1.6.0.js" type="text/javascript"></script>


export const getWxJssdkConfig = (params) => {
    return get('resource/getWxJssdkConfig', params);
};

  getWxJssdkConfig({
    url: location.href
  }).then(res => {
    wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印
      appId: res.data.appid, // 必填,公众号的唯一标识
      timestamp: res.data.timestamp, // 必填,生成签名的时间戳
      nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
      signature: res.data.signature,// 必填,签名
      jsApiList: ['getLocation','scanQRCode'], // 必填,需要使用的JS接口列表
      openTagList: ['wx-open-launch-weapp']
    });
    wx.ready(function () {
     	// 获取成功
    });

    wx.error(function (res) {
      console.log(res)
    });
  }) 
})
文章来源:https://blog.csdn.net/u014131617/article/details/135744815
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。