微信接口调用

微信端项目,项目中调用了微信的选择图片接口,上传图片接口,分享接口、获取地理位置接口、扫一扫接口

调用微信接口步骤

1、页面上引用微信js 

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

2、获得微信config里的4个配置值,这4个配置值一般是通过ajax从后台获得的

EasyAjax.ajax_Post_Json({
        url:''
    },function(res){
        wx.config({
            debug: false,
            appId  :  res.appId, // 必填,公众号的唯一标识
            timestamp  :  res.timestamp, // 必填,生成签名的时间戳
            nonceStr:  res.nonceStr, // 必填,生成签名的随机串
            signature  :  res.signature,// 必填,签名,见附录1
            jsApiList: [
                        'checkJsApi',
                        'scanQRCode',
                        'chooseImage',
                        'previewImage',
                        'uploadImage',
                        'downloadImage',
                        'getNetworkType',
                        'openLocation',
                        'getLocation',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                        ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
        });
        console.log('appid:'+res.appId);
    });

 

上面2步实现后,就可以直接看文档,调微信端的接口了

选择图片接口

html+效果展示

 

js:

var imageSize = 5;//设置图片张数
var images = {
  localAbId: [],  //保存选择图片接口返回的路径
  serverId:[]  //保存调用上传图片接口后返回的值
};

function chooseImage(arr){    
    wx.chooseImage({
        count : imageSize, // 默认9
        sizeType : ['compressed' ], // 可以指定是原图还是压缩图,默认二者都有
        sourceType : [ 'album', 'camera' ], // 可以指定来源是相册还是相机,默认二者都有
        success : function(res) {
            var localIds = res.localIds;  //是一个数组,里面的值是每一张图片的路径,将这个值赋值给img的src,就可以显示图片
            var imagestr="";
            for(var i=0;i<localIds.length;i++){
                arr.push(localIds[i]);   //将所有图片的路径放到一个空数组中,这个数组是微信上传图片接口需要的
                imagestr += '<li class="weui-uploader__file z_photo" imgSrc="'+localIds[i]+'">'+
                            '<img src="'+localIds[i]+'"/>'+
                            '<span class="close-img"></span>';
            }
            $('#uploaderFiles').append(imagestr);
            //点击删除图片,不光要删除页面上的节点,还要删除images.localAbId 这个数组中的对应的路径值,这样上传图片的时候才不会出错
            $('#uploaderFiles').delegate('.close-img','click',function(event){
                var $parentLi = $(this).parent('li');
                $.confirm({
                      title: '确认删除图片?',
                      text: '',
                      onOK: function () {
                        var imgSrc = $parentLi.attr('imgSrc');
                          $parentLi.remove();
                          for(var i=0;i<arr.length;i++){
                              if(imgSrc == arr[i]){
                                  arr.splice(i,1);
                              }
                          }
                      }
                });    
                event.stopPropagation(); //阻止事件冒泡
            })
    });
}

比如说现在选中2张图片

alert(res.localIds),值

点击+调用选择图片接口

$('#uploaderRecipt').click(function(){
  chooseImage(images.localAbId);
})

这样选择图片功能就实现了

上传图片接口

点击确定上传的时候,需要将图片的路径上传到微信服务器

//异常上报
$('#abTooltips').click(function(){
    images.serverId = [];   //空数组,用来存储传调用上传图片接口后,微信的返回值,这个值我们是要传给后台的
    var i=0,len=images.localAbId.length;
    if(len>0){  //若是没有上传图片这个步骤,直接点确定上传,是没有反应的,wx.uploadImage这个方法是不执行的
        uploadImg();
    }else{  //所以没有上传图片后就直接调后台接口了
        submitAbnormalMsg({
            serverId  :  '',
            wayBillId : wayBillId,
            content   : areaTxt,
            flag      : 0
        });
    }
    function uploadImg(){
        wx.uploadImage({
            localId: images.localAbId[i], // 需要上传的图片的本地ID,由chooseImage接口获得
            success: function (res) {
                //var serverId = res.serverId; // 返回图片的服务器端ID,是单个id
                i++;
                images.serverId.push(res.serverId);
                if(i<len){
                    uploadImg();
                }else{
                    //调后台接口,将服务器端id传给后台
                    submitAbnormalMsg({
                        serverId  :  images.serverId.join(','),
                        wayBillId : wayBillId,
                        content   : areaTxt,
                        flag      : 0
                    });

                }
            }
        });
    }
})

ps:上传图片的id,只能一个一个的传,就是 localId :
images.localAbId[i] 但是不能将整个数组都传进去,不能写 localId : images.localAbId

比如说现在点击确定上传,传了2张图片,images.serverId的值:

扫一扫接口

现在要扫一个二维码

在需要调微信扫一扫接口的地方,直接调用这个函数即可

function scanCode(){
    wx.scanQRCode({
        needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
        success: function (res) {
            var result = res.resultStr; // 我的项目中是返回一个地址,获得地址后,可以直接跳转,至于具体怎么跳转,后台处理
            if(result.indexOf('mobile')>=0 || result.indexOf('weixin')>=0){
                window.location.href=result;
            }else{
                 $.toptip('无效条码','cancel');
            }
        }
    });
}

获取地理位置接口

通过微信的获取地理位置接口,我们可以得到当前位置的经纬度,注意2点:

1、肯定是需要将经纬度转成具体的文字地址的,用的是高德地图的反向地理编码

2、微信的默认坐标是wgs84,而高德的地图的坐标是gcj02,所以需要转一下坐标

wx.ready(function(){
    wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
        success: function (res) {
                var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                var speed = res.speed; // 速度,以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                geocoder(latitude,longitude);
        },
        fail: function (res) {
            window.location.href = '定位失败页';
        }
    }); 
});

//反向地理编码
function geocoder(latitude, longitude) {
    var wgs84togcj02 = coordtransform.wgs84togcj02(longitude, latitude);
    longitude=wgs84togcj02[0];
    latitude=wgs84togcj02[1];
    $('#address').attr('data-latitude',latitude);
    $('#address').attr('data-longitude',longitude);
    AMap.service('AMap.Geocoder',function(){//回调函数
        //逆地理编码
        var lnglatXY=[longitude, latitude];//地图上所标点的坐标
        var geocoder = new AMap.Geocoder();
        geocoder.getAddress(lnglatXY, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                //获得了有效的地址信息,将地址放到需要的地方
                $('#address').text(result.regeocode.formattedAddress+"("+result.regeocode.addressComponent.district+result.regeocode.addressComponent.township+result.regeocode.addressComponent.street+result.regeocode.addressComponent.streetNumber+")");
            }else{
               //获取地址失败
              $.toast("获取地址失败",'cancel');
              window.location.href = '定位失败页面';
            }
        });  
    });
}

 

posted @ 2017-09-17 14:19  丁九九  阅读(498)  评论(0编辑  收藏  举报