标签:
导致这个错误是因为签名算法错误
签名需要 noncestr timestamp(因为变量长度限制,不能直接使用毫秒时间戳,要除以1000) jsapi_ticket url
根据微信的文档说明做的话 最容易出错的地方是url
文档上对url的描述反正我是没怎么看懂~
好了吐槽完毕,是时候上代码了
Java代码:
@RequestMapping("share2Firend") //from、isappinstalled参数是自定义分享接口时 微信服务器带过来的 public ModelAndView share2Firend(HttpServletRequest request, String from, String isappinstalled) { String timestamp = String.valueOf(System.currentTimeMillis() / 1000); String noncestr = UUID.randomUUID().toString().replace("-", ""); //jsapiTicket放redis中全局缓存 String jsapiTicket = wechatRemoteService.getJsApiTicket(); //微信给的例子中说url不能硬编码,但还是留了坑,下面注释是php例子中的代码段 // 注意 URL 一定要动态获取,不能 hardcode. //$protocol = (!empty($_SERVER[‘HTTPS‘]) && $_SERVER[‘HTTPS‘] !== ‘off‘ || $_SERVER[‘SERVER_PORT‘] == 443) ? "https://" : "http://"; //$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; //如果你的微信后台端口是80的话,一定不能把HTTP_HOST也拼接到url上面去,否则签名失败 String share2FirendUrl = request.getScheme() + "://" + request.getServerName() + request.getRequestURI(); if(from != null && isappinstalled != null) share2FirendUrl += "?from="+from+"&isappinstalled="+isappinstalled; log.debug("share2FirendUrl:{}", share2FirendUrl); String signature = getSignature(timestamp, noncestr, jsapiTicket, share2FirendUrl); ModelAndView mav = new ModelAndView(); mav.addObject("timestamp", timestamp); mav.addObject("noncestr", noncestr); mav.addObject("signature", signature); mav.addObject("share2FirendUrl", share2FirendUrl); mav.addObject("appId", wechatRemoteService.getAppId()); mav.setViewName("dispatcher:/share.jsp"); return mav; } private String getSignature(String timestamp, String noncestr, String jsapiTicket, String share2FirendUrl) { String[] array = { "timestamp=" + timestamp, "noncestr=" + noncestr, "jsapi_ticket=" + jsapiTicket, "url=" + share2FirendUrl }; Arrays.sort(array); String signature = array[0].concat("&"+array[1]).concat("&"+array[2]).concat("&"+array[3]); log.debug("share2Firend--> signature:{}", signature); signature = DigestUtils.sha1Hex(signature); log.debug("sha1Hex signature:{}", signature); return signature; }
前端代码:
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script> <script type="text/javascript"> wx.config({ debug: false, appId: ‘${appId}‘, timestamp: ‘${timestamp}‘, nonceStr: ‘${noncestr}‘, signature: ‘${signature}‘, jsApiList: [‘onMenuShareAppMessage‘] }); wx.ready(function () { wx.onMenuShareAppMessage({ title: ‘分享‘, desc: ‘分享测试‘, link: ‘${share2FirendUrl}‘, imgUrl: ‘http://xxxx/images/headimg.png‘, success: function () { WeixinJSBridge.call(‘closeWindow‘); } }); }); </script>
微信Js分享朋友接口invalid signature解决方法
标签:
原文地址:http://my.oschina.net/Diversity/blog/406699