天天看點

微信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>      

繼續閱讀