java+jsp微信开发入门教程 jssdk,通过config接口注入权限验证配置,微信开发教程

来源:互联网 发布:linux 挂载u盘 编辑:程序博客网 时间:2024/05/14 09:02

1:绑定域名,先登录微信公众平台进入 设置-公众号设置-功能设置,填写“JS接口安全域名”,可在 开发-接口权限 查看对应的接口权限。




2:引入js,在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js

请注意,如果你的页面启用了https,务必引入 https://res.wx.qq.com/open/js/jweixin-1.2.0.js ,否则将无法在iOS9.0以上系统中成功使用JSSDK。最好下载JS到本地。

3:微信公众平台,开发-基本配置中设置白名单,通过开发者ID及密码调用获取access_token接口时,需要设置访问来源IP为白名单。



4:通过config接口注入权限验证配置,可以通过java获取,然后在jsp页面中赋值给js用于验证,就可以调用微信的接口了。功能:扫描二维码,拍照、本地选图,图片预览,上传图片,下载图片,获取当前网络状态,查看地理位置,获取当前地理位置打开地图,关键是使用JsSignUtil获取了signature,JSP页面才可以通过JS调用微信的功能。包含json相关依赖jar包,json-lib-2.3-jdk15.jar,ezmorph-1.0.6.jar,以及httpclient-4.5.3.jar,httpcore-4.4.6.jar等。


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%><%@ page import="java.util.*"
%><%@ page import="com.weixin.util.JsSignUtil"
%>
<%
String url = request.getRequestURL().toString();
Map<String, String> ret = new HashMap<String, String>();//从后台获取信息,用于js验证
ret = JsSignUtil.sign(url);

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base href="<%=basePath%>">
<title>微信功能演示</title>
<meta name="viewport" http-equiv="Content-Type" content="width=device-width, initial-scale=1, user-scalable=no" />
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"> </script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script type="text/javascript">
    wx.config({
        debug: false,  
        appId: '<%=ret.get("appId")%>',  
        timestamp:'<%=ret.get("timestamp")%>',  
        nonceStr:'<%=ret.get("nonceStr")%>',  
        signature:'<%=ret.get("signature")%>',  
        jsApiList : [ 'checkJsApi',
                      'scanQRCode',
                      'chooseImage',
                      'previewImage',
                      'uploadImage',
                      'downloadImage',
                      'getNetworkType',
                      'openLocation',
                      'getLocation' ]  // 必填,需要使用的JS接口列表
    });//end_config
    
    wx.error(function(res) {
        alert("出错了:" + res.errMsg);
    });
    
    wx.ready(function() {
        
        wx.checkJsApi({  
            jsApiList : ['scanQRCode'],  
            success : function(res) {
                // 以键值对的形式返回,可用的api值true,不可用为false
                // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
            }
        });

        //扫描二维码
        document.querySelector('#scanQRCode').onclick = function() {
            wx.scanQRCode({
                needResult : 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType : [ "qrCode", "barCode" ], // 可以指定扫二维码还是一维码,默认二者都有
                success : function(res) {
                    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果  
                    document.getElementById("wm_id").value = result;//将扫描的结果赋予到jsp对应值上  
                    alert("扫描成功::扫描码=" + result);
                }
            });
        };

        // 5 图片接口
        // 5.1 拍照、本地选图
        var images = {
            localId: [],
            serverId: []
          };
        document.querySelector('#chooseImage').onclick = function () {
            wx.chooseImage({
                //count: 1, // 默认9
                //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                    images.localId = res.localIds;
                    alert('已选择 ' + res.localIds.length + ' 张图片');
                    $("#faceImg").attr("src", res.localIds[0]);//显示图片到页面上
              }
            });
          };
        
        // 5.2 图片预览
        document.querySelector('#previewImage').onclick = function () {
            wx.previewImage({
            current: 'http://www.test.com/upload/images/indexad.png',//自己更改下路径
            urls: [
                'http://www.test.com/upload/images/flash.png',
                'http://www.test.com/upload/images/indexad.png',
                'http://www.test.com/upload/images/flash.png'
            ]
            });
        };
        
        // 5.3 上传图片
        document.querySelector('#uploadImage').onclick = function () {
            if (images.localId.length == 0) {
              alert('请先使用 chooseImage 接口选择图片');
              return;
            }
            var i = 0, length = images.localId.length;
            images.serverId = [];
            function upload() {
              wx.uploadImage({
                localId: images.localId[i],
                isShowProgressTips: 1,// 默认为1,显示进度提示
                success: function (res) {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    alert("服务器图片id:"+serverId);
                    i++;
                    //alert('已上传:' + i + '/' + length);
                    images.serverId.push(res.serverId);
                    if (i < length) {
                        upload();
                    }
                },
                fail: function (res) {
                  alert(JSON.stringify(res));
                }
              });
            }
            upload();
        };
        
        // 5.4 下载图片
        document.querySelector('#downloadImage').onclick = function () {
            if (images.serverId.length === 0) {
              alert('请先使用 uploadImage 上传图片');
              return;
            }
            var i = 0, length = images.serverId.length;
            images.localId = [];
            function download() {
                wx.downloadImage({
                    serverId: images.serverId[i],
                    isShowProgressTips: 1,// 默认为1,显示进度提示
                    success: function (res) {
                        var mlocalId = res.localId; // 返回图片下载后的本地ID
                        alert("本地图片id:"+mlocalId);
                        i++;
                        alert('已下载:' + i + '/' + length);
                        images.localId.push(res.localId);
                        if (i < length) {
                            download();
                        }
                    }
                });
            }
            download();
        };
           
        // 6 设备信息接口
        // 6.1 获取当前网络状态
        document.querySelector('#getNetworkType').onclick = function () {
            wx.getNetworkType({
              success: function (res) {
                alert(res.networkType);
              },
              fail: function (res) {
                alert(JSON.stringify(res));
              }
            });
        };
        //网络接口结束

        // 7 地理位置接口 开始
        // 7.1 查看地理位置
        document.querySelector('#openLocation').onclick = function () {
            wx.openLocation({
              latitude: 23.199994,
              longitude: 116.324520,
              name: '名称',
              address: '广州市',
              scale: 14,
              infoUrl: 'http://weixin.qq.com'
            });
          };
        
        // 7.2 获取当前地理位置
        document.querySelector('#getLocation').onclick = function () {
            wx.getLocation({
              success: function (res) {
                  var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                    var longitude = res.longitude ; // 经度,浮点数,范围为180 ~ -180。
                    var speed = res.speed; // 速度,以米/每秒计
                    var accuracy = res.accuracy; // 位置精度
                alert(JSON.stringify(res));
              },
              cancel: function (res) {
                alert('用户拒绝授权获取地理位置');
              }
            });
        };

        // 7.3 获取当前地理位置打开地图
        document.querySelector('#getLocationMap').onclick = function () {
            wx.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
                success: function (res) {
                    //使用微信内置地图查看位置接口  
                    wx.openLocation({  
                        latitude : res.latitude, // 纬度,浮点数,范围为90 ~ -90  
                        longitude : res.longitude, // 经度,浮点数,范围为180 ~ -180。  
                        name : '当前位置', // 位置名  
                        address : '', // 地址详情说明  
                        scale : 28, // 地图缩放级别,整形值,范围从1~28。默认为最大  
                        infoUrl : 'http://weixin.qq.com' // 在查看位置界面底部显示的超链接,可点击跳转(测试好像不可用)  
                    });

              },
              cancel: function (res) {
                alert('用户拒绝授权获取地理位置');
              }
            });
        };
        // 7 地理位置接口 结束
          
    });//end_ready  
</script>
</head>

<body>
<input type="text" id="wm_id" name="wm_id" value="">
<button id="scanQRCode" >扫描二维码</button><br>

<p>基础接口之判断当前客户端是否支持指定的js接口</p>   
<input type="button" value="checkJSAPI" id="checkJsApi"><br>
<span class="desc" style="color: red">地理位置接口-使用微信内置地图查看位置接口</span><br>
<button class="btn btn_primary" id="getLocationMap">getLocationMap</button><br>
<button class="btn btn_primary" id="openLocation">openLocation</button><br>
<span class="desc" style="color: red">地理位置接口-获取地理位置接口</span><br>
<button class="btn btn_primary" id="getLocation">getLocation</button><br>

<div>
<span class="desc" style="color: red">获取网络状态接口</span><br>
<button class="btn btn_primary" id="getNetworkType">getNetworkType</button><br>
<h3 id="menu-image">图像接口</h3>
<span class="desc">拍照或从手机相册中选图接口</span><br>
<button class="btn btn_primary" id="chooseImage">chooseImage</button><br>
<span class="desc">预览图片接口</span><br>
<button class="btn btn_primary" id="previewImage">previewImage</button><br>
<span class="desc">上传图片接口</span><br>
<button class="btn btn_primary" id="uploadImage">uploadImage</button><br>
<span class="desc">下载图片接口</span><br>
<button class="btn btn_primary" id="downloadImage">downloadImage</button><br>

<br>
显示图片<img alt="" src="" id="faceImg">
</div>

</body>
</html>


JsSignUtil和WeixinUtil里面
private static final String APPID = "wx5273e9f0edd7****";//改为你自己公众号的APPID
private static final String APPSECRET = "1496052a0937834fd7593a6d1e74****";//改为你自己公众号的APPSECRET


源码下载地址,http://download.csdn.net/download/greenfly/10106096,设置一下公众号的APPID和APPSECRET就可以使用了



原创粉丝点击