THINKPHP5+微信公众号多图片上传预览

THINKPHP5+微信公众号多图片上传预览

1.首先集成JSSDK

在extend目录下创建org/wechant文件夹,新建Jssdk.php,将下面的代码放进去,在统计目录下创建access_token.php和jsapi_ticket.php,用来存放微信accesstoken以及ticket;

<?php
namespace org\wechat;

class JSSDK {
  private $appId;
  private $appSecret;
  private $path;
  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
    $this->path = __DIR__.DS;
  }

  public function getSignPackage($url) {
    $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();
      // 如果是企业号用以下 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;
  }

  public 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));
     
      $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($this->path . $filename), 15));
  }
  private function set_php_file($filename, $content) {
    $fp = fopen($this->path.$filename, "w");
    fwrite($fp, "<?php exit();?>" . $content);
    fclose($fp);
  }
}


html页面

<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>吕太公</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="__ROOT__/static/api/css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" href="__ROOT__/static/api/css/public.css"/>
	</head>
	<style>
		body{
			background-color: #FFFFff;
		}
		textarea{
			font-size: 15px;
            margin-top: 10px;
		}
		img{
			width: 98px;
		}
		
	</style>
	<body>
		<!--头部-->
		<div class="tou">
			<header id="header" class="mui-bar mui-bar-nav">
				<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
				<h1 class="mui-title">发圈子信息</h1>
			</header>
		</div>
		<div>
		<form method="post" enctype="multipart/form-data">
			<div>
				<textarea id="textarea" rows="5" name="content" placeholder="请输入内容"></textarea>
			</div>
			<div style="margin-top: -26px;">
				<div id="pox">
					
					<img class="sc" name="image" style="width: 80px;height: 80px;" src="__ROOT__/imgs/shangchuan.png"> 
				</div>
				<div id="dd"></div>
				<button type="submit" class="mui-btn mui-btn-warning" style="width: 100%;">发表</button>
			</div>
		</form>	
		</div>
		<script src="__ROOT__/static/api/js/mui.min.js"></script>
		<script type="text/javascript" src="__ROOT__/static/api/js/jquery.min.js" ></script>
		  <script src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
		<script type="text/javascript">
			mui.init();
			$(function(){
				//选择相应的等级后发送请求从后台后去相应等级提升条件
				//ajax
				$("select").change(function(){
					console.log($(this).val());
				});
              $.ajax({
				    type:"post",
				    url:"{:url('api/user/getSignPackage')}",//自己填写请求地址
				    data:{
                    	"url" : location.href.split('#')[0]
                    },
				    success:function(result){
				        console.log(JSON.parse(result));
                        var resr = JSON.parse(result);
				        wx.config({
					        // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
					        debug: false,
					        // 必填,公众号的唯一标识
					        appId: resr.appId,
					        // 必填,生成签名的时间戳
					        timestamp:""+resr.timestamp,
					        // 必填,生成签名的随机串
					        nonceStr:resr.nonceStr,
					        // 必填,签名,见附录1
					        signature:resr.signature,
					        // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
					        jsApiList : ["chooseImage",
                        "previewImage",
                        "uploadImage", ]
				        });
				    }
			    })
			
				wx.error(function(resf) {
				    alert("出错了:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
				});
				
				wx.ready(function() {
				    wx.checkJsApi({
				         jsApiList : [
                        "chooseImage",
                        "previewImage",
                        "uploadImage",],
				         success : function(resa) {
				
				         }
				    });
              	var imgs = new Array();
				$('.sc').click(function () {
					var that = this;
					var num = 1; 
					var name = $(that).attr("name");; 
					num = $(that).attr("data-id");
					wx.chooseImage({
						count:num,
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
						success: function (res) {
							var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
							for (var i=0;i<localIds.length;i++){
								var im = "<img  src='"+localIds[i]+"' style='width: 60px;' />";
								$(that).before(im);
							    wx.uploadImage({
									localId: localIds[i], // 需要上传的图片的本地ID,由chooseImage接口获得
									isShowProgressTips: 1, // 默认为1,显示进度提示
									success: function (res) {
                                        $(that).after('<input type="hidden" name="'+name+'[]" value="'+res.serverId+'" />');
									},
									fail: function (error) {
										alert('上传错误,请稍候重试!', 'text');
									}
							    });
							}
						}
					});
				});
                
                  
			})
			})

          

		</script>
	</body>

</html>

后端获取微信服务器图片并保存

//添加朋友圈
	public function add_pyq(){
		$user = Session::get('user');
		if(request()->post()){
			if(input('post.content') == ''){
				$this->error('请输入内容');
			}
         	
			$data = array(
				'member_id'=>$user['member_id'],
				'content'=>input('post.content'),
				'status'=>0,
				'add_time'=>date('Y-m-d H:i:s'),
			);
          
			$res = Db::name('friend_moments')->insertGetId($data);
            $images = $_POST['image'];
            $sys = Db::name('wxsystem')->where('id',1)->find(); 
           //实例化Jssdk类
            $jssdkObj = new Jssdk($sys['appid'], $sys['appscrect']);
            //获取token
            $access_token = $jssdkObj->getAccessToken();
            $path = ROOT_PATH . 'public' . DS . 'uploads'. DS . 'friend';
              if(!empty($_POST['image'])){
                foreach($images as $y){
                	//根据token获取图片信息
                    $str = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$y";
                    $a = file_get_contents($str);
                      // dump($a);die;
                    $file_name =uniqid().".jpg";
                    $resource = fopen($path.'/'.$file_name , 'w+');
                    fwrite($resource, $a);
                    fclose($resource);
                     Db::name('friend_moments_images')->insert(array('moments_id'=>$res,'image_url'=>$file_name));
                   // $image_y[] =$file_name; 
                }
              }
            
			
			 $this->success('发布成功,审核通过后即可在朋友圈首页显示','friend/index');
		}else{

			return $this->fetch();
		}
	}

获取签名信息

public function getSignPackage() {
     	 $sys = Db::name('wxsystem')->where('id',1)->find();
		$jssdkObj = new Jssdk($sys['appid'], $sys['appscrect']);
		$url = input('post.url');
	    $signPackage = $jssdkObj->getSignPackage($url);
      
    	return json_encode($signPackage); 
  }

注意:后端操作和获取签名信息都需要在控制器引入Jssdk类;即:use extend\org\Jssdk;

猜你喜欢

转载自blog.csdn.net/qq_35654886/article/details/86148232