一 准备工作。

一 受限于wx 上传图片时,要getToken ,而调access_token 时,需要加ip 白名单。不然报 invalid signature

出现如下情况,优先考虑ip 白名单问题,当然还有可能 ngix 反向代理引发的问题,我暂时没碰到。

其次就是 js 安全域名设置

进入后按微信平台要求设好对应的域名。

二 代码实现

//控制器层
$data = MyWxServ::getParams();
$this->render("index" , $data);//视图层<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"><!--图片类型验证方法1--><input type="button"  value="选择上传文件" class  = 'chooseImg' /><input type="button"  value="上传" class  = 'uploadImg' /><h4>选择文件如下:</h4><img  id="img1"  src = '/1.jpg'  style="width: 250px;"/>
</div><script>function wxConfig(appId,timestamp,nonceStr,signature) {wx.config({debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。appId: appId, // 必填,公众号的唯一标识timestamp:timestamp , // 必填,生成签名的时间戳nonceStr: nonceStr, // 必填,生成签名的随机串signature: signature,// 必填,签名jsApiList: ['chooseImage', 'previewImage','uploadImage','downloadImage','getLocalImgData'] // 必填,需要使用的JS接口列表});wx.ready(function(){     });wx.error(function(res){    });}wxConfig('<?php echo $appid;?>' , <?php echo $time;?>  , '<?php echo $noncestr;?>', '<?php echo $sign; ?>' )wx.ready(function(){// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。});wx.error(function(res){// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。});var images = {localId: [],serverId: []};$(".uploadImg").click(function(){wx.uploadImage({localId: images.localId[0],success: function (res) {var serverId = res.serverId; // 返回图片的服务器端ID$.get("/wxpic/upload", {media_id:serverId},function(r){alert(r);})},fail: function (res) {alert(JSON.stringify(res));}});});$(".chooseImg").click(function() {wx.chooseImage({count:1,success: function (res) {images.localId = res.localIds;//  alert('已选择 ' + res.localIds.length + ' 张图片');$("#img1").attr("src" ,res.localIds[0] );if (images.localId.length == 0) {alert('请先使用 chooseImage 接口选择图片');return;}}});});</script>class MyWxServ
{static function getParams(){$appid =  "xxxx";$sercet =  "yyyy";$ticket = self::getJsapiTicket($appid, $sercet, 0);$data["appid"] = $appid;$data["sercet"] = $sercet;$data["ticket"] = $ticket;$noncestr = "1234567";$data["noncestr"] = $noncestr;$time = time();$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];$sign = sha1("jsapi_ticket=$ticket&noncestr=$noncestr×tamp=$time&url=$url");$data["sign"] = $sign;$data["is_wx"] = true;$data["time"] = $time;return $data;}static function getToken($time, $appid, $secret){$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;$obj = self::accessapi($url, 0, "GET");if (!isset($obj->expires_in)) {return false;}$obj->expires_in = $time + $obj->expires_in - 30;return $obj;}public static function getAccessToken($update = 0, $appid = '', $secret = ''){$time = time();$token_file = COMMON_FOLDER . '/logs/' . $appid . '.token';if (is_file($token_file)) {$token = file_get_contents($token_file);$obj = json_decode($token);if ($obj->expires_in < $time || $update == 1) {$obj = self::getToken($time, $appid, $secret);if (!$obj) {return false;}file_put_contents($token_file, json_encode($obj));}} else {$obj = self::getToken($time, $appid, $secret);if (!$obj) {return false;}file_put_contents($token_file, json_encode($obj), 777);}return $obj->access_token;}static function accessapi($url, $method = 'POST', $jsonData = '', $repeat = 1, $appid = '', $secret = ''){$ch = curl_init($url);curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);curl_setopt($ch, CURLOPT_AUTOREFERER, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$tmpInfo = curl_exec($ch);if (curl_errno($ch)) {echo 'Errno:' . curl_error($ch);exit;}curl_close($ch);$obj = json_decode($tmpInfo);Yii::log($tmpInfo, 'error', '$obj');if (!is_object($obj)) {Yii::log( "accessapi异常:".print_r($obj , 1), CLogger::LEVEL_ERROR ,'log_error');return $tmpInfo;}if (isset($obj->errcode)) {if ($obj->errcode == 40001 && $repeat == 1) {$arr = parse_url($url);$arr1 = explode('&', $arr['query']);$query = '';if (count($arr1) > 0 && $arr['query']) {$i = 0;foreach ($arr1 as $arr2) {$arr3 = explode("=", $arr2);if ($arr3[0] == 'access_token') {$token = self::getAccessToken(1, $appid, $secret);$arr2 = $arr3[0] . '=' . $token;}if ($i > 0) {$query .= '&' . $arr2;} else {$query .= $arr2;}$i++;}}$url = $arr['scheme'] . '://' . $arr['host'] . $arr['path'] . '?' . $query;return self::accessapi($url, $method, $jsonData, 0);}}return $obj;}static function getJsapiTicket($appid, $sercet, $update = 0){$time = time();$token_file = COMMON_FOLDER . '/logs/' . $appid . '.ticket';if (!$update && is_file($token_file)) {$token = file_get_contents($token_file);$obj = json_decode($token);if (!isset($obj->expires_in) || $obj->expires_in < $time || $update == 1) {self::getJsapiTicket($appid, $sercet, 1);}} else {$token = self::getAccessToken(0, $appid, $sercet);$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=jsapi";$obj = WxServ::accessapi($url, 'get');if (!$obj || $obj->errcode) {return false;}$obj->expires_in = $time + $obj->expires_in - 30;file_put_contents($token_file, json_encode($obj));}return $obj->ticket;}public static function getMaterialImage($media_id, $appid = '', $sercet = ''){$token = self::getAccessToken(0, $appid, $sercet);Yii::log($token, 'error', '$token');$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $token . "&media_id=" . $media_id;$json = self::accessapi($url, 'POST', '', 1, $appid, $sercet);$filename =  $media_id . '.jpg';file_put_contents($_SERVER["DOCUMENT_ROOT"]."/" . $filename, $json);return $filename;}
}

三 其它

如果需要把从微信下载到服务器上。

  var serverId = res.serverId; // 返回图片的服务器端ID
//将服务器端的serverId 做为参数传参。                     $.get("/wxpic/upload", {media_id:serverId},function(r){alert(r);})
//服务器端保存下即可。$media_id  = $_GET["media_id"];$appid = "xxx";$sercet = "yyy";$name = MyWxServ::getMaterialImage($media_id, $appid , $sercet);echo $name;
    public static function getMaterialImage($media_id, $appid = '', $sercet = ''){$token = self::getAccessToken(0, $appid, $sercet);  //调用微信得到media 数据的接口。$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $token . "&media_id=" . $media_id;$json = self::accessapi($url, 'POST', '', 1, $appid, $sercet);$filename =  $media_id . '.jpg';file_put_contents($_SERVER["DOCUMENT_ROOT"]."/" . $filename, $json);return $filename;}

总结:  难点在于微信授权这块的折腾。

//所以 MyWxServ 的 getJsapiTicket 方法 
 $obj = WxServ::accessapi($url, 'get');if (!$obj || $obj->errcode) {return false;}

//返回为异常时,多多调试。

微信上传图片。【代码示例】相关推荐

  1. 在哪里能收到python实例代码-python实现网站微信登录的示例代码

    最近微信登录开放公测,为了方便微信用户使用,我们的产品也决定加上微信登录功能,然后就有了这篇笔记. 根据需求选择相应的登录方式 python实现网站微信登录的示例代码 微信现在提供两种登录接入方式 移 ...

  2. java微信支付代码_Java微信支付之服务号支付代码示例

    Java微信支付之服务号支付实现,网上的java微信支付sdk和Demo基本上是水的,看着头疼所以我决心自己开始写Java微信支付之公众号支付,多的不说见下面源码,为了方便使用我分别用了两个Servl ...

  3. php 微信实时更新,微信小程序修改data使页面数据实时更新的代码示例

    本篇文章给大家带来的内容是关于微信小程序修改data使页面数据实时更新的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 需求:通过点击button修改dataList中che ...

  4. 通过调试微信小程序示例代码解析flex布局参数功能(一)

    通过调试微信小程序示例代码解析flex布局参数功能 官方示例小程序源代码下载地址:https://github.com/wechat-miniprogram/miniprogram-demo 通过调试 ...

  5. 微信公众平台开发(二) 微信公众平台示例代码分析

    http://www.cnblogs.com/mchina/archive/2013/06/07/3120592.html 微信公众平台开发(二) 微信公众平台示例代码分析 一.摘要 微信公众平台提供 ...

  6. 【uni-app】UniApp实现微信小程序中拨打手机电话和长按加微信客服好友(完整代码示例)

    UniApp实现微信小程序中拨打手机电话和长按加微信客服好友(完整代码示例) 一.service.Vue <template><view><!-- 标题栏 -->& ...

  7. 手机浏览器上传图片代码php,移动端图片上传,使用微信浏览器后端接受到的文件类型是application/octet-stream...

    仅在部分安卓机的微信和qq浏览器上发现此问题(用的是华为荣耀v8)后端语言是php 苹果正常,uc 手机自带等浏览器均正常,都能正确识别文件类型(image/jpeg) 提交方式是formData,代 ...

  8. 如何使用腾讯微信公众平台示例代码…

    下面教大家,如何使用腾讯微信公众平台示例代码. 微信平台已经全面改版, 新版的帮助直接看帮助即可: http://mp.weixin.qq.com/wiki/index.php?title=消息接口指 ...

  9. php 盗用微信文章,基于PHP的微信文章精选示例代码-六派数据

    示例代码 本代码示例是基于PHP的六派数据接口进行数据请求API服务请求的代码示例,使用前你需要: 以下是完整代码示例: require_once("curl.func.php") ...

  10. 微信小程序示例 - 小相册

    小相册是结合腾讯云对象存储服务(Cloud Object Service,简称COS)制作的一个微信小程序示例.在代码结构上包含如下两部分: https://github.com/CFETeam/we ...

最新文章

  1. socket编程:多路复用I/O服务端客户端之poll
  2. 基于Hadoop的产品大数据分布式存储优化
  3. 【计算机组成原理】CISC和RISC
  4. Metro 应用无法打开解决办法
  5. oracle表空间的创建、修改、删除及一些参数解释
  6. Redis配置文件详解(redis.conf)
  7. Ubuntu里面vi编辑器在编辑文本时 如何在所有行行首或行尾插入字符
  8. 工具的使用——vs2013
  9. [转载] 5.2 calendar--通用日期的相关函数(4)
  10. 深度学习自学(三十九):基于对抗网络判别能力正则化的半监督生成方法
  11. android8.0 苹果,外媒:看完Android8.0 这次是谷歌抄苹果
  12. .NET开发必看资料53个+经典源码77个(转)
  13. ArcGIS操作实例视频教程38讲全集(转)
  14. StartUp.xls宏病毒清除方法(excel宏病毒)
  15. 代码质量检查规则中的 is provided externally to the method and not sanitized b.
  16. git merge 单个文件
  17. 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。
  18. 红外遥控器添加遥控支持方法
  19. mysql错误合集_mysql错误合集
  20. 西邮校园网路由器教程

热门文章

  1. Google高级技巧—google Hack
  2. 神七飞行28日看点:穿越“黑障”返回地面
  3. 入手评测 惠普暗影精灵 7怎么样
  4. 【opencv-python】 cv2.putText(...)绘制文本字符串
  5. .Net Core使用google authenticator打造用户登录动态口令
  6. Python之Bs4模块安装教程
  7. 计算机考试簇状图,电大计算机网考电子表格(簇状统计图).doc
  8. 进来学习,这个拿墨刀产品素材设计大赛万元大奖的原型设计超强
  9. 三轮全向底盘小车制作 STM32主控 串口无线遥控器
  10. 详细完整——XP系统硬盘安装Ubuntu14.04