欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java调用微信接口实现网页分享小功能

程序员文章站 2023-12-10 18:57:34
本文实例为大家分享了java调用微信接口实现网页分享小功能的具体代码,供大家参考,具体内容如下 // 获取access_token  *注意* 经过实际开发测试...

本文实例为大家分享了java调用微信接口实现网页分享小功能的具体代码,供大家参考,具体内容如下

// 获取access_token  *注意* 经过实际开发测试,微信分享不支持跨域请求,因此获取access_token的请求必须从服务器发起,否则无法获取到access_token所以以下都是服务端操作

微信接口说明

参考文章:java微信分享接口开发详解

一、微信util类

public class shareconstants {
 //微信获取ticket的接口
 public static final string ticket_url_test = "https://api.weixin.qq.com/cgi-bin/ticket/getticket" ;
 public static final string type = "jsapi" ;
 //微信获取token的接口
 public static final string get_token_url = "https://api.weixin.qq.com/cgi-bin/token";
 public static final string grant_type = "client_credential" ;
 
}
public class weixinutil {
 
 private static logger logger = loggerfactory.getlogger(weixinutil.class) ;
 
 public static boolean signaturecheck(string token,string timestamp,string nonce,string signature) throws exception{
 
 list<string > list = new arraylist<string>(3){
  public string tostring(){
  return this.get(0)+this.get(1)+this.get(2) ;
  }
 } ;
 
 list.add(token) ;
 list.add(timestamp) ;
 list.add(nonce) ;
 
 collections.sort(list) ;
 messagedigest md = messagedigest.getinstance("sha-1") ;
 byte[] digest = md.digest(list.tostring().getbytes()) ;
 string teststr = weixinutil.bytearraytohexstring(digest) ;
 logger.info("token:{},timestamp:{},nonce:{},teststr:{}");
 if(teststr.equalsignorecase(signature.touppercase())){
  return true;
 }else{
  return false ;
 }
 }
 
 public static string signature(string jsapiticket,string noncestr,long timestamp,string url) throws exception{
 
 string str = string.format("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s",
  jsapiticket,noncestr,timestamp,url) ;
 logger.info("signature url:{}",str);
 messagedigest md = messagedigest.getinstance("sha-1") ;
 byte[] digest = md.digest(str.getbytes()) ;
 
 string sigstr = weixinutil.bytearraytohexstring(digest) ;
 return sigstr ;
 }
 
 public static string bytearraytohexstring(byte[] array){
 string strdigest = "" ;
 for(int i = 0 ;i<array.length;i++){
  strdigest+=bytetohexstring(array[i]) ;
 }
 return strdigest ;
 }
 
 public static string bytetohexstring(byte ib){
 char[] digit = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'} ;
 char [] ob = new char[2] ;
 ob[0] = digit[(ib >>> 4) & 0x0f] ;
 ob[1] = digit[ib &0x0f] ;
 string s = new string(ob) ;
 return s ;
 }
 
 
 public static string getweixinsharetoken(string appid,string secret) throws exception{
 map<string,string> maps = new hashmap<string,string>() ;
 maps.put("grant_type", shareconstants.grant_type) ;
 maps.put("appid",appid) ;
 maps.put("secret",secret) ;
 try{
  string result = httpinvokeutil.httpget(shareconstants.get_token_url,maps) ;
  jsonobject jsonobject = jsonobject.parseobject(result) ;
  string access_token = (string) jsonobject.get("access_token") ;
  integer expires_in = (integer) jsonobject.get("expires_in") ;
  logger.debug("gettoken access_token:{},expires_in:{}",access_token,expires_in);
  if(access_token !=null && expires_in!=null && expires_in==7200)
  return access_token ;
  else
  return null ;
 }catch (exception ex){
  logger.error("ex:stack:{}",ex.getstacktrace().tostring());
  throw new exception("get token failed");
 }
 }
 
 public static string getjsapiticket(string token) throws exception{
 map<string,string> maps = new hashmap<string,string>() ;
 maps.put("access_token",token);
 maps.put("type",shareconstants.type);
 try{
  string result = httpinvokeutil.httpget(shareconstants.ticket_url_test,maps) ;
  jsonobject jsonobject = jsonobject.parseobject(result) ;
  integer errcode = (integer) jsonobject.get("errcode") ;
  if(errcode==null || (errcode!=null &&errcode!=0)){
  logger.error("get jsapiticket is failed, errcode:{}",errcode);
  return null ;
  }else{
  string ticket = (string) jsonobject.get("ticket") ;
  return ticket ;
  }
 }catch (exception ex){
  logger.error("ex.stack:{}",ex.getstacktrace().tostring());
  throw new exception("getjsapi ticket is failed") ;
 }
 }
 
}

注意上面httpinvokeutil.httpget()是httpclint这个可以自己去写,只要能发请求就行,

二、controller层

//currurl ==前端想要分享的网页地址
 @requestmapping(value = "/getwconfig", method = requestmethod.get)
 @responsebody
 //@requiredlogin
 public frameresp getwconfig(@param("currurl") string currurl) throws userexception, exception {
 if (currurl == null) {
  return builderrorresp(errorcodeconst.error_param_error);
 }
 logger.info("get the encode currurl {}", currurl);
 
 string urltmp = urldecoder.decode(currurl, "utf-8");
 
 logger.info("decode currurl {}", currurl);
 
 long timestamp = new date().gettime() / 1000;
 string url = urltmp.split("#")[0];
 
 wconfigresp wconfigresp = new wconfigresp();
 
 //修改为本地加载分享
 //shareconfig.getappid()==自己的appid
 //shareconfig.getuxinappsecret()==自己的appsecret
 string token = weixinutil.getweixinsharetoken(shareconfig.getappid(), shareconfig.getuxinappsecret());
 string ticket = weixinutil.getjsapiticket(token);
 if (ticket == null) {
  logger.error("get jsapiticketsec is failed");
  throw new exception("get jsapi is failed");
 }
 wconfigresp.setappid(shareconfig.getappid());
 wconfigresp.settimestamp(timestamp);
 wconfigresp.setnoncestr(randomstringutils.random(10, true, true));
 
 logger.info("appid:{},ticket:{},timestamp:{},noncestr:{},url:{}", shareconfig.getappid(), ticket, timestamp, wconfigresp.getnoncestr(), url);
 
 string signature = weixinutil.signature(ticket, wconfigresp.getnoncestr(), wconfigresp.gettimestamp(), url);
 if (signature != null) {
  wconfigresp.setsignature(signature);
  return buildsuccessresp(wconfigresp);
 } else {
  logger.error("getwcconfig is failed");
  throw new exception("error getwconfig");
 }
}

三、自定义的返回值类-wconfigresp

@data
public class wconfigresp extends basemodel{
 private string appid ;
 private long timestamp ;
 private string noncestr;
 private string signature ;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。