微信JS-SDK说明文档:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
根据微信说明文档步骤:(1)绑定域名[略](2)引入js文件[略]
(3)通过config接口注入权限验证配置:
页面代码:
<script type="text/javascript"> function jssdk() { $.ajax({ url : '<%=basePath%>wx/jssdk.do',//调用java后台获取config配置信息:appid、timestamp 、nonceStr 、signature type : 'post', dataType : 'json', //contentType : "application/x-www-form-urlencoded; charset=utf-8", data : { 'url' : location.href.split('#')[0] }, success:function(data) { wx.config({ debug : true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId : data.appId, timestamp : data.timestamp, nonceStr : data.nonceStr, signature : data.signature, jsApiList : ['chooseImage','previewImage', 'uploadImage', 'downloadImage'] }); } }); } window.onload = function() { jssdk(); }; </script> |
后台获取jssdk配置信息:
@RequestMapping(value = "/jssdk" , method = {RequestMethod.POST }) /** |
配置成功后,调用上传图片接口:
HTML代码:
<form class="signup" role="form"> <div class="tit-set"> </form>
<script type="text/javascript"> |
调用上传图片接口后,需要将此图片存到自己的图片服务器时,需要将mediaId即images.serverId提交给java后台接口,后台接口接收到mediId后,调用微信获取临时素材接口:
public static void main(String[] args) throws Exception { // String token = TokenThread.accessToken.getToken(); String requrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; String url = requrl.replace("ACCESS_TOKEN", "HkAKN1zhEhIJvJ2iFHSxKBxD2i86IGe2lVVirE7iDFsSX3PeN-0mJ1wF4mTDP8Dibkv2ievaDLXUlzz6pE2hJHJ4uc6OD-jnTbsmDL1PyrFycpCMgQZ-yMW5eMepYkK1HFObACALJS").replace("MEDIA_ID", "iLXQnxsZYqjij_F3uwYMKXGM7ugE76yYkGZSxTIDCmY5ARujVBxe_9dEZUH80bRa"); InputStream inputStream = null; HttpURLConnection httpURLConnection = null; URL u = new URL(url);//创建的URL httpURLConnection = (HttpURLConnection) u.openConnection();//打开链接 httpURLConnection.setConnectTimeout(3000);//设置网络链接超时时间,3秒,链接失败后重新链接 httpURLConnection.setDoInput(true);//打开输入流 httpURLConnection.setRequestMethod("GET");//表示本次Http请求是GET方式 int responseCode = httpURLConnection.getResponseCode();//获取返回码 if (responseCode == 200) {//成功为200 //从服务器获得一个输入流 inputStream = httpURLConnection.getInputStream(); } byte[] data = new byte[1024]; int len = 0; FileOutputStream fio = null; try { fio = new FileOutputStream("D:\\demo.jpg"); while ((len = inputStream.read(data)) != -1) { fio.write(data, 0, len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fio != null) { try { fio.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |