1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
<script type="text/javascript"> window.onload=function(){ wx.config({ debug: false, appId: '{$appid}', timestamp: '{$signPackage.timestamp}', nonceStr: '{$signPackage.nonceStr}', signature: '{$signPackage.signature}', jsApiList: [ 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'chooseWXPay', 'getLocalImgData' ] }); wx.ready(function(){ // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 var idx = 0; var serverIds=''; var images = { localId: [], serverId: [] }; ioslocId=[];//用于兼容ios的本地id列表 图片是base64格式的 document.querySelector('#chooseImage').onclick = function () { wx.chooseImage({ // sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { $("#photolist").html("");//每次选择图片完成后都清空之前已经添加的html节点 rows="";//声明一个空字符串用于保存循环出来的html images.localId =images.localId.concat(res.localIds); // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 //调用上传递归函数 uploadimg(images.localId); if (window.__wxjs_is_wkwebview) { //判断ios是不是用的 wkwebview 内核 for(var i=0;i<images.localId.length;i++){ wx.getLocalImgData({ //循环调用 getLocalImgData localId:res.localIds[i], // 图片的localID success: function (res) { var localData = res.localData; // localData是图片的base64数据,可以用img标签显示 localData = localData.replace('jgp', 'jpeg');//iOS 系统里面得到的数据,类型为 image/jgp,因此需要替换一下 ioslocId.push(localData) //把base64格式的图片添加到ioslocId数组里 这样该数组里的元素都是base64格式的 rows=""; for(var j=0;j<ioslocId.length;j++){ rows+=`<div class="z_files" style="background-image: url(`+ioslocId[j]+`)"><div class="delete" data-id="`+j+`"></div></div>` } $("#photolist").html(rows); },fail:function(res){ alert("res"); } }); } alert(rows) }else{ //如果不是用的wkwebview 内核 或者是用的安卓系统 执行下面的xunh $.each(images.localId,function (index,el) { rows+=`<div class="z_files" style="background-image: url(`+el+`);background-size:100%;background-repeat: no-repeat;"> <div class="delete" data-id="`+index+`"></div> </div>` }); $("#photolist").html(rows); } function uploadimg(localIds){ wx.uploadImage({ localId: localIds[idx].toString(), isShowProgressTips: 1, success: function (res) { idx++ //存储图片媒体ID,用,号分割 serverIds+=res.serverId+','; if(idx<localIds.length){ setTimeout(function () {uploadimg(localIds);}, 100); //调用上传递归函数 }else{ var result = ''; $.ajax({ type: "GET", url: "{:Url('Fun/get_med')}", data: {serverId:serverIds}, success: function(data){ $("#shashibiya").html(''); var bbs = eval(data); for (var i = 0; i < bbs.length; i++) { result += bbs[i].key+','; // result += '<input type="text" name="img'+i+'" value="'+bbs[i].key+'">'; } $("input[name=img]").val(result); } }); //上传序号归零 idx=0; serverIds=''; return true; } }, fail: function () { alert('1'); } }); } } }); }; }); } </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//根据微信serverId获取下载图片的路径 public function get_med(){ $serverId = input('serverId'); $serverId = rtrim($serverId, ','); $serverId_list = explode(',',$serverId); $get = new getjsapiticket(); $urls = array(); $i = 0; foreach ($serverId_list as $key => &$value) { $urls[$i]['key'] = $get->get_media($value); $i++; } echo json_encode($urls); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
<?PHP namespace app\common\jssdk;//文件夹名称func use Think\Controller; Class getjsapiticket extends Controller{ /** * 专门用来检查微信接口返回值的。 */ private function requestAndCheck($url, $method = 'GET', $fields = []) { $return = httpRequest($url, $method, $fields); if ($return === false) { $this->error('http请求出错!'); return false; } $wxdata = json_decode($return, true); // $this->debug && $this->logDebugFile(['url' => $url,'fields' => $fields,'wxdata' => $wxdata]); if (isset($wxdata['errcode']) && $wxdata['errcode'] != 0) { if ($wxdata['errcode'] == 40001) { \think\Db::name('wx_user')->where('id', 1)->update(['web_expires' => 0]);//token错误 } $this->error('错误码'.$wxdata['errcode']); return false; } if (strtoupper($method) === 'GET' && empty($wxdata)) { $this->error('微信http请求返回为空!'); return false; } return $wxdata; } public function nihao(){ // \think\Cache::connect($options); // $jsapi = \think\Cache::get('acc'); // echo $jsapi;exit; $wechat = \think\Db::name('wx_user')->where('id',1)->find(); $expire_time = $wechat['web_expires']; if($expire_time > time()){ return $wechat['web_access_token']; } $appid = $wechat['appid']; $appsecret = $wechat['appsecret']; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; $return = $this->requestAndCheck($url, 'GET'); if ($return === false) { return false; } $web_expires = time() + 7000; // 提前200秒过期 \think\Db::name('wx_user')->where('id', 1)->update(['web_access_token'=>$return['access_token'], 'web_expires'=>$web_expires]); // $this->config['web_access_token'] = $return['access_token']; // $this->config['web_expires'] = $web_expires; return $return['access_token']; } /* * 向用户推送消息 */ public function push_msg($openid,$content){ $access_token = $this->nihao(); $url ="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token; $post_arr = array( 'touser'=>$openid, 'msgtype'=>'text', 'text'=>array( 'content'=>$content, ) ); $post_str = json_encode($post_arr,JSON_UNESCAPED_UNICODE); $return = $this->requestAndCheck($url,'POST',$post_str); $return = json_decode($return,true); } //根据微信serverId获取下载图片的路径 public function get_media($serverId){ $access_token=$this->nihao(); $url ="https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$serverId; return $url; // //根据微信JS接口上传了图片,会返回上面写的images.serverId(即media_id),填在下面即可 // $str = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$serverId; //获取微信“获取临时素材”接口返回来的内容(即刚上传的图片) // return json_encode($str); // //__DIR__指向当前执行的PHP脚本所在的目录 // echo __DIR__; // //以读写方式打开一个文件,若没有,则自动创建 // $resource = fopen(__DIR__."/1.jpg" , 'w+'); // //将图片内容写入上述新建的文件 // fwrite($resource, $a); // //关闭资源 // fclose($resource); } // //获取access_token // function get_token(){ // $wechat = \think\Db::name('wx_user')->where('id',1)->find(); // $appid = $wechat['appid']; // $appsecret = $wechat['appsecret']; // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; // $data = json_decode(file_get_contents($url),true); // if($data['access_token']){ // return $data['access_token']; // }else{ // echo "Error"; // exit(); // } // } } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
$urls = rtrim($_POST['img'], ','); $url_lst = explode(',',$urls); foreach ($url_lst as $key => $value) { $url = $value; //图片存放的路径 $data_time =date('Y-m-d',time()); $path ="public/wx/".$data_time."/"; if(!file_exists($path)){ mkdir($path,0777,true); //创建目录 chmod($path,0777); //赋予权限 } //确保图片名唯一,防止重名产生覆盖 $uniName ='wx_'.time().rand(1000,9000).'.jpg'; $res =$this->getImage($url,$path,$uniName); echo json_encode($res); } //下载远程文件到本地 function getImage($url,$save_dir='',$filename='') { //根据url获取远程文件 $curl =curl_init(); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl,CURLOPT_TIMEOUT,500); 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); //把图片保存到指定目录下的指定文件 if(file_put_contents($save_dir.$filename,$res)){ return array( 'file_name' =>$filename, 'save_path'=>$save_dir.$filename, 'error' =>0 ); } } |

我的微信
把最实用的经验,分享给最需要的读者,希望每一位来访的朋友都能有所收获!