微信网页上传图片

根据微信文档,如果在微信中打开的网页上调用相机或从相册中上传图片,需要调用微信网页开发 /JS-SDK
步骤如下:

步骤一:绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。#

步骤二:引入JS文件

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

步骤三:权限签名

从公众号后台找到APPID与SECRET值

//读缓存的token和ticket,如果不存在就重新获取:
//..........读缓存代码略
//取得token,有效期2小时,每次获取会自动重置,
$APPID="XXX";//按实际写
$SECRET="XXX"; //按实际写
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$APPID.'&secret='.$SECRET;		
$arr = file_get_contents( $url ); 
$arr = json_decode( $arr, true );
$token = $arr[ 'access_token' ];  
	
//取得ticket,ticket从零点开始每两小时变一次,但未必旧的失效?
$ticketurl='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi';
$arr = file_get_contents( $ticketurl ); 
$arr = json_decode( $arr, true );
$jsapi_ticket = $arr[ 'ticket' ];

//存入数据库缓存
//..........代码略


$noncestr="123456abc"; //自定义加密串 
$timestamp=time();   //定义一个时间戳

$url='http://xx.com/xxx.php'; //引用js的微信页面URL
//拼接字串准备hash
$toencode='jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.time().'&url='.$url;
//取得签名
$signature=sha1($toencode); 
?>

步骤四:通过config接口注入权限验证配置

$(function(){
	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',
		'previewImage',
		'uploadImage'
		 ] // 必填,需要使用的JS接口列表
	});
});

wx.ready(function(){
 // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
 alert("33");
});

步骤五:选择图片的JS代码

function album() {
	wx.chooseImage({
		count: 1,
		// 默认9
		sizeType: ['original', 'compressed'],
		// 可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album', 'camera'],
		// 可以指定来源是相册还是相机,默认二者都有
		success: function(res) {
			var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
			// alert(localIds);
			wx.uploadImage({
				localId: localIds.toString(),
				// 需要上传的图片的本地ID,由chooseImage接口获得
				isShowProgressTips: 1,
				// 默认为1,显示进度提示
				success: function(data) {
					mediaId = data.serverId; // 返回图片的服务器端ID
					//console.log(mediaId);
					$.ajax({
						"type": "post",
						"url": "{:url('index/avatar')}",
						"dataType": "json",
						"data": {
							"mediaId": mediaId,
						},
						"success": function(res) {
							// alert(JSON.stringify(res));
							if (res.status == 1) {
								mui.toast(res.msg);
								mui('#upload_list').popover('hide', document.getElementById("upload_images")); //隐藏
								$("#loadimg").load(location.href + " #loadimg");
							} else {
								mui.toast(res.msg);
								mui('#upload_list').popover('hide', document.getElementById("upload_images")); //隐藏
								$("#loadimg").load(location.href + " #loadimg");
							}
						}
					});
				},
				fail: function(error) {
					alert(JSON.stringify(error));

				}
			});
		}
	});
}

步骤六:选择图片的按钮

<button id="uploadimg" onClick="album()" type="button">uploadimg</button>

步骤七 :服务端保存图片代码

try{
        $access_token = $this->getAccessToken();
        $user = $_COOKIE['username'];
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $access_token . "&media_id=" . $media_id;
        $content = $this->http_get_data($url);
        //创建文件夹
        
        $user_path = $_SERVER['DOCUMENT_ROOT'] .'/myapps/uploadimg/' . $_COOKIE['username'].'/';
        if (!file_exists($user_path)) mkdir ($user_path,0777,true);

        $filename = time() . rand(10, 99) . '.jpg';//文件名
        $filePath = $user_path . $filename;//本地图像绝对路径
        
        file_put_contents($filePath, $content);
        }catch(Exception $exp){
            return "error SAVEFILE";
        }
        return $filename;

全部代码参见:

<?php
//jssdk.php:
class JSSDK
{
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage()
    {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取,不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket()
    {
        // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("jsapi_ticket.php"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            echo "access_token=" . $accessToken;
            // 如果是企业号用以下 URL 获取 ticket
            //$url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $this->set_php_file("jsapi_ticket.php", json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }

    private function getAccessToken()
    {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("access_token.php"));
        if ($data->expire_time < time()) {
            // 如果是企业号用以下URL获取access_token
            //$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            //var_dump($this->appId);
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $this->set_php_file("access_token.php", json_encode($data));
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function get_php_file($filename)
    {
        return trim(substr(@file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/myapps/' . $filename), 15));
    }

    private function set_php_file($filename, $content)
    {
        $fp = @fopen($_SERVER['DOCUMENT_ROOT'] . '/myapps/' . $filename, "w+");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }

    /**
     * @Description: 获取图片内容
     * @Author: Yang
     * @param $media_id
     * @return string
     */
    public function getWxImage($media_id)
    {
        try{
        $access_token = $this->getAccessToken();
        $user = $_COOKIE['username'];
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $access_token . "&media_id=" . $media_id;
        $content = $this->http_get_data($url);
        //创建文件夹
        
        $user_path = $_SERVER['DOCUMENT_ROOT'] .'/myapps/uploadimg/' . $_COOKIE['username'].'/';
        if (!file_exists($user_path)) mkdir ($user_path,0777,true);

        $filename = time() . rand(10, 99) . '.jpg';//文件名
        $filePath = $user_path . $filename;//本地图像绝对路径
        
        file_put_contents($filePath, $content);
        }catch(Exception $exp){
            return "error SAVEFILE";
        }
        return $filename;
    }

    /**
     * @Description: 获取微信服务器上的图片
     * @Author: Yang
     * @param $url
     * @return string
     */
    private function http_get_data($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        return $return_content;
    }
}
?>

<?php
 //saveimg.php
include 'jssdk.php'; 
header('Content-Type:application/json; charset=utf-8');
$msg="ok";
if($_COOKIE["username"]==null) {
    $msg="no username cookie value";
    $arr = array('stat'=>'error','msg'=>$msg);
    exit(json_encode($arr));
}

if(!isset($_POST['serviceid'])){
    $msg="no serviceid";
    $arr = array('stat'=>'error','msg'=>$msg);
    exit(json_encode($arr));
}


$jssdk=new JSSDK("appid","secrit"); //按实际填 
$filename=$jssdk->getWxImage($_POST['serviceid']);
$msg=$filename; 

$arr = array('stat'=>'ok','msg'=>$msg);
exit(json_encode($arr));
?>
//upload.php
<?php 
include 'jssdk.php'; 
$jssdk=new JSSDK("appid","secript"); //按实际填 
$signPackage=$jssdk->getSignPackage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>WeUI</title>
<!-- 引入 WeUI -->
<link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/1.1.3/weui.min.css"/>
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript"></script>
<script src="zepto.js" type="text/javascript"></script>
</head>
<body>
<!-- 使用 -->
<div class="weui-cell">
  <div class="weui-cell__hd"></div>
  <div class="weui-cell__bd">
    <div class="weui-uploader">
      <div class="weui-uploader__hd">
        <p class="weui-uploader__title" style="color: #3d4145;">图片上传</p>
        <div class="weui-uploader__info"><span id="already_upload">0</span>/4</div>
      </div>
      <div class="weui-uploader__bd" style="overflow: inherit">
        <ul class="weui-uploader__files" id="uploaderFiles">
        </ul>
        <div class="weui-uploader__input-box"> <span id="uploaderInput" class="weui-uploader__input"></span> </div>
      </div>
    </div>
  </div>
</div>
 
<script>
    $(()=>{
        wx.config({
            debug: true,
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
                "chooseImage", "uploadImage", "downloadImage", "previewImage"
            ]
        });
    });



    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口,支持批量判断
        wx.checkJsApi({
            jsApiList: [
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage'
            ],
            success: function (res) {
                //alert(JSON.stringify(res));
                if (res.checkResult.getLocation == false) {
                    alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!');
                    return;
                } else {
                    $("#uploaderInput").click(function () {
                        wxChooseImage();
                    })
                }
            },
            error: function (res) {
                alert(JSON.stringify("error=" + res));
            }
        });
    });
    //上传图片
    function wxChooseImage() {
        wx.chooseImage({
            success: function (res) {
                var i = 0, length = res.localIds.length;

                function upload() {
                    //判断是否已经上传了足够的图片
                    var len = $(".file-item").length;
                    if (len >= 4) {
                        alert("上传图片数量已达上限");
                        return;
                    }
                    //图片上传到微信服务器
                    wx.uploadImage({
                        localId: res.localIds[i],
                        success: function (result) {
//                            alert(JSON.stringify(result));
                            var imgList = '<li class="weui-uploader__file file-item" style="position: relative;">' +
                                '<img src="' + res.localIds[i] + '" style="width:79px;height:79px;" />' +
                                '<span class="del" οnclick="delImg(this)">×</span>' +
                                '<input type="hidden"  name="filename" value="" />' +
                                '</li>';
                            var imgtoadd=$("#uploaderFiles").append(imgList);
                            $("#already_upload").html($(".file-item").length);
                            //转服务器下载图片,下载完成后交图片文件名取回,放到数组里 (by liheng)
                            $.ajax({
                                type: 'POST',
                                url: '/myapps/saveimg.php',
                                // data to be added to query string:
                                data: { serviceid: result.serverId },
                                // type of data we are expecting in return:
                                dataType: 'json',
                                timeout: 2000,
                                context: imgtoadd,
                                success: function(data){
                                    // Supposing this JSON payload was received:
                                    //   {stat:ok,"msg":"1223.jpg"}    
                                    if(data.stat=='error') {
                                        alert('图片保存失败:'+ data.msg);return;
                                    }else 
                                    imgtoadd.find("input").val(data.msg);
                                     
                                },
                                error: function(xhr, type,error){
                                    alert('图片保存失败:'+ error);
                                }
                            }) 



                            i++;
                            if (i < length) {
                                upload();
                            }
                        },
                        fail: function (res) {
                            alert(JSON.stringify(res));
                        }
                    });
                }

                upload();
            }
        });
    }
    wx.error(function (res) {
        alert("调用微信jsapi返回的状态:" + res.errMsg);
    });//删除图片
    function delImg(dom) {
        $(dom).parent().remove();
        $("#already_upload").html($(".file-item").length);
    }

    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值