java获取微信jsapi_ticket方法

                                java获取微信jsapi_ticket

首先要在公共账号中绑定域名,进入公共账号--设置


设置js安全域名


设置好以后就可以开始开发

可以参照https://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95


获取jsapi_ticket

jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下, jsapi_ticket的有效期为7200秒 ,通过access_token来获取。由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务, 开发者必须在自己的服务全局缓存jsapi_ticket  


在数据库中加入一张表专门用来存放/刷新jsapi_ticket用的,里面有失效时间 每次更新时间和失效时间相差10分钟(有效时间1小时50分钟) 保证在没有失效前就去刷新

每次先去查看有没有未失效的jsapi_ticket  如果有就直接取到后去生成签名  
如果没有则去请求access_token 用access_token在去请求jsapi_ticket

上代码

@Service
public class JssdkService {
  private final	String appid = "公共账号id";
  private final	String secret = "公共账号secret";
	@Autowired
	private JssdkDao jssdkDao;
//url为分享的url
	public Jssdk getInfo(String url) {
		Jssdk jssdk = jssdkDao.getInfo();
		String jsapi_ticket="";
        if(jssdk==null||StringUtils.isEmpty(jssdk.getJsapiTicket())){
        	jsapi_ticket=getJsapiTicket();
        }else{
        	jsapi_ticket=jssdk.getJsapiTicket();
        }
        jssdk=getSign(url,jsapi_ticket); 
		return jssdk;
	}

	private String getJsapiTicket(){
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?";
		String params = "grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";
		String result = HttpRequestUtils.httpGet(requestUrl+params);
		String access_token = JSONObject.parseObject(result).getString("access_token");
		requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
		params = "access_token=" + access_token + "&type=jsapi";
		result = HttpRequestUtils.httpGet(requestUrl+params);
		String jsapi_ticket = JSONObject.parseObject(result).getString("ticket");
		int activeTime=Integer.parseInt(JSONObject.parseObject(result).getString("expires_in"));
		Jssdk jssdk = new Jssdk();
		jssdk.setActiveTime(activeTime-600);
		jssdk.setJsapiTicket(jsapi_ticket);
		jssdkDao.update(jssdk);
		return jsapi_ticket;
	}
	private Jssdk getSign(String url,String jsapi_ticket) {
		String noncestr =  getNonceStr();
		String timestamp =  getTimeStamp();
		String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
		sign = Sha1Util.getSha1(sign);
		Jssdk jssdk = new Jssdk();
        jssdk.setAppid(appid);
        jssdk.setNoncestr(noncestr);
        jssdk.setTimestamp(timestamp);
        jssdk.setSign(sign);
		return jssdk;
	}
private String getNonceStr() {
 Random random = new Random();
        return MD5Util.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
 }

 private String getTimeStamp() {
 return String.valueOf(System.currentTimeMillis() / 1000);
 
}


import java.io.IOException;
import java.net.URLDecoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class HttpRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
 
 
    /**
     * post请求
     * @param url         url地址
     * @return
     */
    public static String httpPost(String url){
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        String str = "";
        try {
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功,并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        return str;
    }
 
 
    /**
     * 发送get请求
     * @param url    路径
     * @return
     */
    public static String httpGet(String url){
        //get请求返回结果
    	 String strResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                  strResult = EntityUtils.toString(response.getEntity());
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return strResult;
    }
}

json解析可以用alibaba.fastjson也可以用别的工具

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>