前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java,获取微信分享需要的获取 signature、jsapi_ticket和access_token

java,获取微信分享需要的获取 signature、jsapi_ticket和access_token

作者头像
allsmallpig
发布2021-02-25 15:15:28
1K0
发布2021-02-25 15:15:28
举报
文章被收录于专栏:allsmallpi博客

 废话不多,代码说话,那个url是你需要分享的url,需要传进来,然后入参加密。

代码语言:javascript
复制
java,获取微信需要的获取 jsapi_ticket和access_token 
代码语言:javascript
复制
@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    @Value("${weixin.test.appid}")
    String appid ;

    @Value("${weixin.test.sercert}")
    String sercert;
    // 获取token

    /**
     * 获取 微信H5页面 分享需要获得的
     *
     * @return
     */
    @Override
    public BaseResponse getWechatJSShare(String url) {
        String lastResult = null;
        try {
            String token = WechatToken.getAccessToken(appid, sercert);
            log.info("微信H5页面分享 当次获得到的 token={}",token);
            String jsapiTicket = WechatToken.getJsapiTicket(token);
            log.info("微信H5页面分享 当次获得到的 jsapiTicket={}",jsapiTicket);
            UUID uuid = UUID.randomUUID();
            String nonceStr = String.valueOf(uuid);
            long timeMillis = System.currentTimeMillis()/1000;

            ConcurrentHashMap objectObjectConcurrentHashMap = new ConcurrentHashMap<>(4);
            objectObjectConcurrentHashMap.put("noncestr", nonceStr);
            objectObjectConcurrentHashMap.put("timestamp", timeMillis);
            objectObjectConcurrentHashMap.put("jsapi_ticket", jsapiTicket);
            objectObjectConcurrentHashMap.put("url",url);
            TreeMap stringObjectTreeMap = new TreeMap<>();
            stringObjectTreeMap.putAll(objectObjectConcurrentHashMap);

            Iterator> iterator = stringObjectTreeMap.entrySet().iterator();
            StringBuilder stringBuilder = new StringBuilder();
            while (iterator.hasNext() == true) {
                Map.Entry mapMiddle = iterator.next();
                stringBuilder.append(mapMiddle.getKey());
                stringBuilder.append("=");
                stringBuilder.append(mapMiddle.getValue());
                stringBuilder.append("&");
            }
            String str = stringBuilder.toString();
            str = str.substring(0, str.length() - 1);
            System.out.println("str = " + str);
            byte[] bytes = Digests.sha1(str.getBytes("UTF-8"));
            String signature = byteToHex(bytes);

            ImmutableMap ofMap = ImmutableMap.of("appId", appid, "timestamp", timeMillis, "nonceStr", nonceStr, "signature", signature);
            lastResult = JSON.toJSONString(ofMap);
            log.info("微信H5页面分享 当次最终获得到的参数为 lastResult={}",lastResult);
        } catch (Exception e) {
            log.info("微信H5页面分享 当次最终获得到的参数为 lastResult={}",lastResult);
            log.info("微信H5页面分享 获取参数失败 e={}",e);
            BaseResponse.buildSuccess("获取参数失败");
        }
        return  BaseResponse.buildSuccess("获取成功",lastResult);
    }
}
代码语言:javascript
复制
package com.fh.hr.web.api.util;

import org.apache.commons.lang3.Validate;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Formatter;

/**
 * 摘要算法, 支持md5与sha1算法
 * @author Luxor
 * @version 2016/11/2.
 */
public class Digests {

    private static final String SHA1 = "SHA-1";
    private static final String MD5 = "MD5";

    private static SecureRandom random = new SecureRandom();

    /**
     * 对输入字符串进行sha1散列.
     */
    public static byte[] sha1(byte[] input) {
        return digest(input, SHA1, null, 1);
    }

    public static byte[] sha1(byte[] input, byte[] salt) {
        return digest(input, SHA1, salt, 1);
    }

    public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA1, salt, iterations);
    }

    /**
     * 对输入字符串进行MD5
     */
    public static byte[] md5(byte[] input) {
        return digest(input, MD5, null, 1);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
        	throw new RuntimeException(e);
        }
    }

    /**
     * 生成随机的Byte[]作为salt.
     *
     * @param numBytes byte数组的大小
     */
    public static byte[] generateSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }

    /**
     * 对文件进行md5散列.
     */
    public static byte[] md5(InputStream input) throws IOException {
        return digest(input, MD5);
    }

    /**
     * 对文件进行sha1散列.
     */
    public static byte[] sha1(InputStream input) throws IOException {
        return digest(input, SHA1);
    }

    public static byte[] digest(InputStream input, String algorithm) throws IOException {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            int bufferLength = 8 * 1024;
            byte[] buffer = new byte[bufferLength];
            int read = input.read(buffer, 0, bufferLength);

            while (read > -1) {
                messageDigest.update(buffer, 0, read);
                read = input.read(buffer, 0, bufferLength);
            }
            return messageDigest.digest();
        } catch (GeneralSecurityException e) {
        	throw new RuntimeException(e);
        }
    }

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


}
代码语言:javascript
复制
@Slf4j
public class WechatToken {

    private static final String    URL    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    /**
     * 获取微信H5分享的js_ticket 过期时间为 7200s == 2小时
     */
    public static final String   TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";

    public static Map TOKENS = new ConcurrentHashMap<>();

    public static Map TICKET_TOKENS = new ConcurrentHashMap<>();

    public static String getAccessToken(String appId, String secret) {

        TokenItem tokenItem = TOKENS.get(appId);
        Long now = System.currentTimeMillis();
        if (tokenItem != null && tokenItem.expiresIn - now > 0) {
            return tokenItem.token;
        }
        synchronized (WechatToken.class) {
            now = System.currentTimeMillis();
            if (tokenItem != null && tokenItem.expiresIn.compareTo(now) > 0) {
                return tokenItem.token;
            }
            String url = String.format(URL, appId, secret);
            String rawResponse = HttpClientUtil.post(url);
            JSONObject response = JSON.parseObject(rawResponse);
            if (response.containsKey("errcode")) {
                // TODO EXCEPTION
                log.info("get weChat Access_Token has error! rawResponse={}",rawResponse);
                return null;
            }
            if (tokenItem == null) {
                TOKENS.put(appId, new TokenItem());
            }

            // 提前2分钟
            TOKENS.get(appId).expiresIn = now + (response.getLong("expires_in") - 120) * 1000;
            TOKENS.get(appId).token = response.getString("access_token");
            return TOKENS.get(appId).token;
        }
    }

    public static class TokenItem {
        private String token     = null;
        private Long   expiresIn = -1L;
    }


    public static class TicketItem {
        private  Integer errcode;
        private String errmsg;
        private String ticket = null;
        private Long expiresIn = -1L;
    }

    public static String getJsapiTicket(String access_token) {

        TicketItem ticketItem = WechatToken.TICKET_TOKENS.get(WechatConstant.TICKET_TOKEN_STR);
        Long now = System.currentTimeMillis();
        if (ticketItem != null && ticketItem.expiresIn - now > 0) {
            return ticketItem.ticket;
        }
        synchronized (WechatToken.class) {
            now = System.currentTimeMillis();
            if (ticketItem != null && ticketItem.expiresIn.compareTo(now) > 0) {
                return ticketItem.ticket;
            }
            String params = "type=jsapi&access_token=" + access_token;
            String result = HttpUtil.get(new StringBuilder().append(TICKET_URL).append("?").append(params).toString());
            JSONObject response = JSON.parseObject(result);
            if (0 != (int)response.get("errcode") && !("ok").equals(response.get("errmsg"))) {
                    log.info("get weChat Ticket_Token has error! result={}", result);
                    return null;
                }
            if (ticketItem == null) {
                TICKET_TOKENS.put(WechatConstant.TICKET_TOKEN_STR, new TicketItem());
            }

            // 提前2分钟
            TICKET_TOKENS.get(WechatConstant.TICKET_TOKEN_STR).expiresIn = now + (response.getLong("expires_in") - 120) * 1000;
            TICKET_TOKENS.get(WechatConstant.TICKET_TOKEN_STR).ticket = response.getString("ticket");
            return TICKET_TOKENS.get(WechatConstant.TICKET_TOKEN_STR).ticket;
        }
    }


}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/05/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档