当前位置: 移动技术网 > IT编程>开发语言>Java > java开发微信分享接口的步骤

java开发微信分享接口的步骤

2019年07月19日  | 移动技术网IT编程  | 我要评论

微信分享接口的java开发的一些小步骤,具体内容如下

1.配置接口信息进行验证

代码如下:

  /**
   * 访问没认证的地址跳转
   *
   * @param request
   * @return 登录页面
   * @throws exception
   */
  @requestmapping(value = "/checkwxdomainurl", method = requestmethod.get)
  public void checkwxdomainurl(httpservletrequest request) throws exception {

    try {
      // 开发者提交信息后,微信服务器将发送get请求到填写的服务器地址url上,get请求携带参数 
      string signature = request.getparameter("signature");// 微信加密签名(token、timestamp、nonce。) 
      string timestamp = request.getparameter("timestamp");// 时间戳 
      string nonce = request.getparameter("nonce");// 随机数 
      string echostr = request.getparameter("echostr");// 随机字符串 
      // 将token、timestamp、nonce三个参数进行字典序排序 
      string[] params = new string[] { token, timestamp, nonce };
      arrays.sort(params);
      // 将三个参数字符串拼接成一个字符串进行sha1加密 
      string cleartext = params[0] + params[1] + params[2];
      string algorithm = "sha-1";
      string sign = new string(hex.encodehex(
          messagedigest.getinstance(algorithm).digest((cleartext).getbytes()), true));
      // 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 
      if (signature.equals(sign)) {
        response.getwriter().print(echostr);
      }
    } catch (exception e) {
      e.printstacktrace();
    }
  }

2.js配置

3.获取分享页面js需要参数   其中获取token、ticket加入缓存

  /**
  * 方法名:getwxconfig</br>
  * 详述:获取微信的配置信息 </br>
  * 开发人员:gy
  * @param request
  * @return 说明返回值含义
  * @throws 说明发生此异常的条件
   */
  @override
  public map<string, object> getwxconfig(httpservletrequest request) {
    map<string, object> ret = new hashmap<string, object>();
    string appid = wxconfigure.getappid(); // 必填,公众号的唯一标识
    string requesturl = request.getrequesturl().tostring();
    string accesstoken = null;
    string jsapiticket = null;
    string url = "";
    string timestamp = long.tostring(system.currenttimemillis() / 1000); // 必填,生成签名的时间戳
    string noncestr = uuid.randomuuid().tostring(); // 必填,生成签名的随机串
    //此处先在缓存中查询,查询不到在调用接口查询 缓存中需要设置access-token的有效时间
//    redistemplate.opsforvalue().getoperations().delete(prefix);
    // accesstoken = (string) redistemplate.opsforvalue().get(prefix);
    token accesstokenfromredis = getaccesstokenfromredis();
    accesstoken = accesstokenfromredis.getaccesstoken();
    if (accesstokenfromredis.getaccesstoken() != null) {
      jsapiticket = (string) redistemplate.opsforvalue().get(prefixticket);
      if (jsapiticket==null) {
        url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken
            + "&type=jsapi";
        jsonobject json = httprequest(url, "get", null);
        if (json != null) {
          jsapiticket = json.getstring("ticket");
          redistemplate.opsforvalue().set(prefixticket, jsapiticket);
          redistemplate.expire(prefixticket, integer.parseint(wxconfigure.getexpiretime()),
              timeunit.seconds);
        }
    } 
    }
    string signature = "";
    // 注意这里参数名必须全部小写,且必须有序
    string sign = "jsapi_ticket=" + jsapiticket + "&noncestr=" + noncestr + "×tamp="
        + timestamp + "&url=" + requesturl;
    try {
      messagedigest crypt = messagedigest.getinstance("sha-1");
      crypt.reset();
      crypt.update(sign.getbytes("utf-8"));
      signature = bytetohex(crypt.digest());
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    } catch (unsupportedencodingexception e) {
      e.printstacktrace();
    }
    ret.put("appid", appid);
    ret.put("timestamp", timestamp);
    ret.put("noncestr", noncestr);
    ret.put("signature", signature);
    return ret;
  }

  /**
  * 方法名:bytetohex</br>
  * 详述:字符串加密辅助方法 </br>
  * 开发人员:gy </br>
  * @param hash
  * @return 说明返回值含义
  * @throws 说明发生此异常的条件
   */
  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;

  }

  /**
   * 从redis中获取accesstoken,指定key的string值,过期时间7200s
   * 
   * @param key
   * @return
   */
  public token getaccesstokenfromredis() {
    token token = null;
    string assesstoken = (string) redistemplate.opsforvalue().get(wxconfigure.gettokenkey());
    if (null != assesstoken && !"".equals(assesstoken)) {
      token = new token();
      token.setaccesstoken(assesstoken);
      return token;
    } else {
      token = commonwxutil.gettoken(wxconfigure.getappid(), wxconfigure.getsecret());
      redistemplate.opsforvalue().set(wxconfigure.gettokenkey(), token.getaccesstoken());
      redistemplate.expire(wxconfigure.gettokenkey(), integer.parseint(wxconfigure.getexpiretime()),
          timeunit.seconds);
      return token;
    }
  }

4.页面的相关js的引入

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

 <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

<script type="text/javascript">

 // 微信信息的以及调用的配置
// 微信信息的以及调用的配置
  var signature=$("#signature").val();
  var appid=$("#appid").val();
  var timestamp=$("#timestamp").val();
  var noncestr=$("#noncestr").val();
  var userid=$("#userid").val();
  var productname=1;
  
  alert(signature);
wx.config({
  debug: false, 
  appid:appid , 
  timestamp:timestamp, 
  noncestr: noncestr, 
  signature:signature,
  jsapilist: ['onmenusharetimeline', 'onmenushareappmessage','onmenushareqq','onmenushareweibo','onmenushareqzone'] 
});

 wx.ready(function(){
   var isok = true;
   wx.checkjsapi({
     jsapilist: ['onmenusharetimeline'],
     fail: function (res) {
       alert("微信版本太低,不支持分享给朋友的功能!");
       isok = false;
     },
     success: function (res) {
       alert("支持qq分享。");
     }
   });  
     // 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
      wx.onmenusharetimeline({
        title: '第六篇 :微信公众平台开发实战java版之如何自定义微信公众号菜单', 
        desc: '第六篇 :微信公众平台开发实战java版之如何自定义微信公众号菜单', 
        link: 'http://4d536256.ngrok.io/login', 
        imgurl: 'http://busc.4ggogo.com/media/media/img/home-show-a.png', 
        success: function (res) { 
           alert(json.stringify(res));
           if (res.errmsg=='sharetimeline:ok') {
           /*   $.ajax({
                type:"get",
                url:'insertcollectshare',
                data:{
                  userid:userid,
                },
                datatype:"json",
                async: false,
                success:function(data){
                 alert(200);
                },
                error:function(data){
                  var rurl = xhr.getresponseheader('contentpath');
                  window.location.href = rurl;
                }
              }); */
             // 用户确认分享后执行的回调函数
              /* window.location.href = contextroot + 'insertcollectshare?userid=' + userid; */
          } 
        },
        cancel: function (res) { 
          // 用户取消分享后执行的回调函数
           alert(res);
        }
      });
     
     // 获取“分享给朋友”按钮点击状态及自定义分享内容接口
      wx.onmenushareappmessage({
        title: '第七篇 :微信公众平台开发实战java版之如何获取微信用户基本信息', // 分享标题
        desc: "第七篇 :微信公众平台开发实战java版之如何获取微信用户基本信息", // 分享描述
        link:'http://4d536256.ngrok.io/login',
        imgurl: 'http://busc.4ggogo.com/media/media/img/home-show-a.png', // 分享图标
        type: 'link', // 分享类型,music、video或link,不填默认为link
      });
      
      //获取“分享到qq”按钮点击状态及自定义分享内容接口
      wx.onmenushareqq({
        title: '第六篇 :微信公众平台开发实战java版之如何自定义微信公众号菜单', // 分享标题
        desc: '第六篇 :微信公众平台开发实战java版之如何自定义微信公众号菜单', // 分享描述
        link: 'http://4d536256.ngrok.io/login', // 分享链接
        imgurl: 'http://busc.4ggogo.com/media/media/img/home-show-a.png', // 分享图标
        success: function () { 
          // 用户确认分享后执行的回调函数
        },
        cancel: function () { 
          // 用户取消分享后执行的回调函数
        }
      });
      
      //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
      wx.onmenushareweibo({
        title: '分享到腾讯微博标题', // 分享标题
        desc: '分享到腾讯微博描述', // 分享描述
        link: 'http://4d536256.ngrok.io/login', // 分享链接
        imgurl: 'http://busc.4ggogo.com/media/media/img/home-show-a.png', // 分享图标
        success: function () { 
          // 用户确认分享后执行的回调函数
        },
        cancel: function () { 
          // 用户取消分享后执行的回调函数
        }
      });
      
      //获取“分享到qq空间”按钮点击状态及自定义分享内容接口
      wx.onmenushareqzone({
        title: '分享到qq空间标题11111111111111111', // 分享标题
        desc: '分享到qq空间描述2222222222222222222', // 分享描述
        link: 'http://4d536256.ngrok.io/login', 
        imgurl:'http://busc.4ggogo.com/media/media/img/home-show-a.png', // 分享图标
        success: function () { 
          // 用户确认分享后执行的回调函数
        },
        cancel: function () { 
          // 用户取消分享后执行的回调函数
        }
      });
 });

 </script>

 备注:调转的路径为配置的域名路径,不然无法调用,图片大小不可以大于300k

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网