天天看点

微信jssdk之微信浏览器上传图片

为了在公众号页面中上传图片,需要配置微信jssdk。

各项配置操作流程,请参照微信官网:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115;

为了提高代码复用性,封装了一下上传图片类:

<?php

class WxUploadImg{

    //1.获取access_token,7000秒内,读取文件存档,否则重新获取

    function get_access_token_and_jsticket($appid,$appsecret){

        $file_addr='./server/cache.text';

        if(file_exists($file_addr)){

            $content=file_get_contents($file_addr);

            $content=json_decode($content);

            $access_token=$content->access_token;

            $jsticket=$content->jsticket;

            $time_limit=$content->time_limit;

            $arr['time_limit']=$time_limit;

            $arr['access_token']=$access_token;

            $arr['jsticket']=$jsticket;

            if(time()<= $time_limit){

                return $arr;

            }else{

                $file=fopen($file_addr,'w');

                $time_limit=time()+7000;

                $access_token=$this->get_new_access_token($appid,$appsecret);

                $jsticket=$this->get_jsticket($access_token);

                $arr=array();

                $arr['time_limit']=$time_limit;

                $arr['access_token']=$access_token;

                $arr['jsticket']=$jsticket;

                fwrite($file,json_encode($arr));

                fclose($file);

                return $arr;

            }

        }else{

            $file=fopen($file_addr,'w');

            $time_limit=time()+7000;

            $access_token=$this->get_new_access_token($appid,$appsecret);

            $jsticket=$this->get_jsticket($access_token);

            $arr=array();

            $arr['time_limit']=$time_limit;

            $arr['access_token']=$access_token;

            $arr['jsticket']=$jsticket;

            fwrite($file,json_encode($arr));

            fclose($file);

            return $arr;

        }

    }

    //随机字符串

    function make_nonceStr()  { 

         $codes=array();

        $codeSet = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        for ($i = 0; $i<16; $i++) {

            $codes[$i] = $codeSet[mt_rand(0, strlen($codeSet)-1)];

        }

        $nonceStr = implode($codes);

        return $nonceStr;

    }

    //缓存过期,获取新的access_token

    function get_new_access_token($appid,$appsecret){

   $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;

        $rurl = file_get_contents($url);

        $rurl = json_decode($rurl,true);

        if(array_key_exists('errcode',$rurl)){

            return 'err1';

        }else{

            return $access_token = $rurl['access_token'];

        }

    }

    //2.获取jsticket

    function get_jsticket($access_token){

        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi"; // 两小时有效

        $rurl = file_get_contents($url);

        $rurl = json_decode($rurl,true);//var_dump($rurl);return;

        if($rurl['errcode'] != 0){

            return 'err2';

        }else{

            $jsticket = $rurl['ticket'];

            return $jsticket;

        }

    }

    //3.获取 signature

    function get_signature($jsticket,$timestamp,$noncestr,$url){

        $string1 = 'jsapi_ticket='.$jsticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;

        return $signature = sha1($string1);

    }

}

前端:

插入页面的php代码,以便页面配置wx.config

最容易出错的是获取当前页面的完整url,参数一个不能少,可用

alert(location.href.split('#')[0])查看当前url;      
<?php
    include 'wx_upload_img.php';//引入封装类
    $wximg=new WxUploadImg();
    $timestamp = time();
    $appid='wxxxxxxxxxxx';
    $appsecret ="xxxxxxxxxxxxxxxxxxx";
    $url= 'http://wx.unair.cn/insure/etc_add.php?openid='.$_REQUEST['openid'];
    $noncestr=$wximg->make_nonceStr();
    $arr=$wximg->get_access_token_and_jsticket($appid,$appsecret);
    $access_token=$arr['access_token'];
    $signature=$wximg->get_signature($arr['jsticket'],$timestamp,$noncestr,$url);
?>      
js部分      
<script>
   
    //alert(location.href.split('#')[0])
    wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId:"<?php echo  $appid; ?>" , // 必填,公众号的唯一标识
        timestamp:"<?php echo  $timestamp; ?>" , // 必填,生成签名的时间戳
        nonceStr: "<?php echo  $noncestr; ?>", // 必填,生成签名的随机串
        signature: "<?php echo  $signature; ?>",// 必填,签名
        jsApiList: [
            'chooseImage',
            'uploadImage'
        ] // 必填,需要使用的JS接口列表
    });

    function chooseImage(obj){
        var id=$(obj).attr('id');
        // 选择张片
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function(res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
               // $(obj).attr('src', localIds);
                // 上传照片
                wx.uploadImage({
                    localId: '' + localIds,
                    isShowProgressTips: 1,
                    success: function(res) {
                        serverId = res.serverId;
                        $(obj).attr(id,serverId); // 把上传成功后获取的值附上
                        var img = '<img src="' +localIds+ '" style="width: 180px;height:130px;"/>';
                        $("#"+id).empty();
                        $("#"+id).append(img);//显示选中的图片
                        var url="http://wx.unair.cn/insure/server/download_wx_img.php";
                        $.get(url,{access_token:access_token,media_id:serverId},function (data) {
                           alert(data);//从微信服务器获取图片到本地,后台脚本就不提供了
                        });
                    }
                });
            }
        });
    }      
<html>部分      
<div class="main_in_input_image_label">请上传正反面身份证照片:</div>
<div οnclick="chooseImage(this)" id="idcardimg1" class="main_in_input_image_pit" style="float: left;">
    <span id="jiajia" style="font-size:105px;">+</span>
</div>      

继续阅读