微信SDK图片上传功能

document.querySelector('.photobtn').onclick = function () {
    wx.chooseImage({
      sizeType: ['compressed'],
      count: 1, 
      success: function (res) {
        localid = res.localIds.toString();
        ajaxupload(localid);
      },
      fail: function (res) {
          alert(JSON.stringify(res));
        }
    });
  };

function ajaxupload(localIds) {
      $('#loadingToast').show();
      wx.uploadImage({
        localId: localIds,
        isShowProgressTips: 0,
        success: function (res) {
          $.ajax({
                type: 'POST',
                url: "{pigcms::U('Wall/AjaxdownloadMedia')}",
                data:{    
                         serverId : res.serverId,                                
                },  
                success: function (retuendata) {
                    var data = JSON.parse(retuendata); 
                    //$('#loadingToast').hide();
                    if(data.status == 1){
                        $('#loadingToast').hide();
                        showTip('上传成功!');
                    }else{
                        $('#loadingToast').hide();
                        showTip('上传失败!');
                    }
                }, 
            });
        },
        fail: function (res) {
            $.ajax({
                type: 'POST',
                url: "{pigcms::U('Wall/AjaxWriteLogo')}",
                data:{    
                         data : res,                                
                },  
                success: function (res) { 
                    
                }, 
            });
          alert(JSON.stringify(res));
        }
      });
    };

/*
    @下载微信素材图片
    @接收参数素材id $media_id 
    */
    function downloadMedia($media_id){
        //$media_id = $_GET['media_id'];
        //$access_token = $_GET['access_token'];
        import("@.ORG.wall.WechatShares");
        $share     = new WechatShares($this->appId,$this->appSecret,$this->wecha_id);
        $tokendata = $share->readtext('access_token');
        $tokendata = json_decode($tokendata,true); 
        if(!empty($tokendata['access_token']) && $tokendata['access_token_expires_in'] > time()){
            $access_token = $tokendata['access_token'];
        }else{
            $urls = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
            $rt=$this->curlGet($urls);
            $jsonrt=json_decode($rt,1);
            $tokendata['access_token'] = $access_token = isset( $jsonrt['access_token'] ) ? $jsonrt['access_token'] : "" ;
            $tokendata['access_token_expires_in'] = time()+$jsonrt['expires_in'];
            $share->writetext('access_token',$tokendata);
        }
        $url ="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
        $img = $this->curlGet($url);
        $fileurl =     'uploads/wall/images/'.date('Y-m-d').'/'.$this->token.'/';
        //$fileurl =     'uploads/wall/images/';
        $filetype = "jpg";//文件类型,后缀
        $randname = rand(1,9).time();//生成的随机名
        if(!file_exists($fileurl)){
            mkdir($fileurl,0777,true);//生成文件夹
        }
        $imgurl = $fileurl.$randname.'.'.$filetype;
        $filesize = file_put_contents($imgurl,$img);//保存文件,返回图片大小
        if($filesize){
            $data['imgurl'] = 'http://'.$_SERVER['SERVER_NAME'].'/'.$imgurl;
            $data['status'] = 1;
        }else{
            $data['status'] = 2;
        }
        return $data;
    }

<?php 
class WechatShares 
{
    private $appId        = '';
    private $appSecret    = '';
    public $error         = array();
    public $token         = '';  
    public $wecha_id         = '';
    
    
    //构造函数获取access_token
    function __construct($appId,$appSecret,$wecha_id){
        $this->appId        = $appId;
        $this->appSecret    = $appSecret;
        $this->wecha_id        = $wecha_id;
    }
    
    public function writetext($file,$conten,$filePath = ''){ 
        if(empty($filePath)){
            $filePath = "uploads/wall/WechatConfig/";
        }
        if (!file_exists($filePath)){ 
            mkdir($filePath);
        } 
        if(!file_exists($filePath)){
            mkdir($filePath,0777);
        }
        $filename = $filePath.'/'.$file;
        $json_string = json_encode($conten); 
        file_put_contents($filename, $json_string);
    }
    /*
    @读取消息
    @接收参数文件名称 $filename 
    @返回json格式的消息内容 $json 
    @判断当前文件是否存在,存在返回文件内容,不存在则返回文件不存在
    */
    public function readtext($file,$filePath = ''){ 
        if(empty($filePath)){
            $filePath = "uploads/wall/WechatConfig/";
        }
        $filename = $filePath.'/'.$file;
        if(file_exists($filename)){
            $content = file_get_contents($filename);
            $json = $content;            
        }else{
            $json = '{"msg":"The file does not exist."}'; 
        }
        return $json;
    }
    
    public function config(){
        $now     = time();

        $share_data = $this->readtext('share_ticket');
        $share_data = json_decode($share_data,true);
        if( (empty($share_data['share_ticket']) || empty($share_data['share_dated']) ) || ($share_data['share_ticket']!='' && $share_data['share_dated']!='' && $share_data['share_dated'] < $now ) ){
            $tokenData     = $this->getToken();
            if($tokenData['errcode']){
                $this->error['token_error']     = array('errcode'=>$tokenData['errcode'],'errmsg'=>$tokenData['errmsg']);
            }else{
                $access_token     = $tokenData['access_token'];
                $ticketData     = $this->getTicket($access_token);
                if($ticketData['errcode']>0){
                    $this->error['ticket_error']     = array('errcode'=>$ticketData['errcode'],'errmsg'=>$ticketData['errmsg']);
                }else{
                    $ticketdata = array(
                        'share_ticket'=>$ticketData['ticket'],
                        'share_dated'=>$now+$ticketData['expires_in'],
                    );
                    $this->writetext('share_ticket',$ticketdata);
                    $ticket     = $ticketData['ticket'];
                }
            }
        }else{
            $ticket         = $share_data['share_ticket'];
        }

        //$url         = $this->getUrl();
        $url         = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        $sign_data     = $this->addSign($ticket,$url);
        $html     = <<<EOM
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js "></script>
    <script type="text/javascript">
        wx.config({
          debug: false,
          appId:     '{$sign_data['appId']}',
          timestamp: {$sign_data['timestamp']},
          nonceStr: '{$sign_data['nonceStr']}',
          signature: '{$sign_data['signature']}',
          jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onVoiceRecordEnd',
        'playVoice',
        'onVoicePlayEnd',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
      ]
        });
    </script>
EOM;
    return $html;
    }
    
    public function getError(){
        dump($this->error);
    }
    
    public function addSign($ticket,$url){
        $timestamp = time();
        $nonceStr  = rand(100000,999999);
        $array     = array(
            "noncestr"        => $nonceStr,        
            "jsapi_ticket"    => $ticket,
            "timestamp"        => $timestamp,
            "url"            => $url,
        );
        
        ksort($array);
        $signPars    = '';
    
        foreach($array as $k => $v) {
            if("" != $v && "sign" != $k) {
                if($signPars == ''){
                    $signPars .= $k . "=" . $v;
                }else{
                    $signPars .=  "&". $k . "=" . $v;
                }
            }
        }
        
        $result = array(
            'appId'     => $this->appId,
            'timestamp' => $timestamp,
            'nonceStr'  => $nonceStr,
            'url'         => $url,
            'signature'  => SHA1($signPars),
        );
        
        return $result;
    }

    public function getUrl(){
         $url     = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        if(isset($_GET['code']) && isset($_GET['state']) && ($_GET['state'] == 'oauth')){
            $url         = $this->clearUrl($url);
            if(isset($_GET['wecha_id'])){
                $url .= '&wecha_id='.$this->wecha_id;
            }
            return $url;
        }else{
            return $url;
        }

    }
    
    public function clearUrl($url){
        $param     = explode('&', $url);
        for ($i=0,$count=count($param); $i < $count; $i++) {
            if(preg_match('/^(code=|state=|wecha_id=).*/', $param[$i])){
                unset($param[$i]);
            }
        }
        return join('&',$param);
    }
    
    //获取token
    public function  getToken(){
        $url     = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
        return $this->https_request($url);
    }

    public function getTicket($token){
        $url     = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi";
        return $this->https_request($url);
    }

  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
    );
    $share_html = $this->createHtml($signPackage);

    return $share_html;
    //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() {
    $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;
    return $ticket;
  }

  private function getAccessToken() {
    $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;
    return $access_token;
  }

  private function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT,30);
    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;
  }
    /*创建分享html*/
    public function createHtml($sign_data){

    $html     = <<<EOM
    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script type="text/javascript">
        wx.config({
          debug: false,
          appId:     '{$sign_data['appId']}',
          timestamp: {$sign_data['timestamp']},
          nonceStr: '{$sign_data['nonceStr']}',
          signature: '{$sign_data['signature']}',
          jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onVoiceRecordEnd',
        'playVoice',
        'onVoicePlayEnd',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
      ]
        });
    </script>
    <script type="text/javascript">
    wx.ready(function () {
        // 2.2 监听“分享给朋友”按钮点击、自定义分享内容及分享结果接口
        if(window.shareData.tContent){
            window.shareData.tContent = window.shareData.tContent;
        }else{
            window.shareData.tContent = window.shareData.tTitle;
        }
        wx.onMenuShareAppMessage({
            title: window.shareData.tTitle,
            desc: window.shareData.tContent,
            link: window.shareData.sendFriendLink,
            imgUrl: window.shareData.imgUrl,
            type: '', 
            dataUrl: '', 
            success: function () { 
                shareHandle('frined');
            },
            cancel: function () { 
                //alert('用户取消分享后执行的回调函数');
            }
        });
        
        // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
        wx.onMenuShareTimeline({
            title: window.shareData.tTitle,
            link: window.shareData.sendFriendLink,
            imgUrl: window.shareData.imgUrl,
            success: function () { 
                shareHandle('frineds');
                //alert('分享朋友圈成功');
            },
            cancel: function () { 
                //alert('分享朋友圈失败');
            }
        });    

        // 2.4 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口
        wx.onMenuShareWeibo({
            title: window.shareData.tTitle,
            desc: window.shareData.tContent,
            link: window.shareData.sendFriendLink,
            imgUrl: window.shareData.imgUrl,
            success: function () { 
                shareHandle('weibo');
                   //alert('分享微博成功');
            },
            cancel: function () { 
                //alert('分享微博失败');
            }
        });
        document.querySelector('#closeWindow').onclick = function () {
            wx.closeWindow();
        };

    });
    function shareHandle(to) {
        var submitData = {
            module: window.shareData.moduleName,
            moduleid: window.shareData.moduleID,
            token:'{$this->token}',
            wecha_id:'{$this->wecha_id}',
            url: window.shareData.sendFriendLink,
            to:to
        };
        $.post('index.php?g=Wap&m=Share&a=shareData&token={$this->token}&wecha_id={$this->wecha_id}',submitData,function (data) {},'json')
    }
</script>
EOM;
        return $html;
    }
    
    //https请求(支持GET和POST)
    protected function https_request($url, $data = null)
    {
        $curl = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //curl_setopt($curl, CURLOPT_SSLVERSION, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $errorno= curl_errno($curl);
        if ($errorno) {
            return array('curl'=>false,'errorno'=>$errorno);
        }else{
            $res = json_decode($output,1);

            if ($res['errcode']){
                return array('errcode'=>$res['errcode'],'errmsg'=>$res['errmsg']);
            }else{
                return $res;
            }
        }
        curl_close($curl);
    }
}

?>

转载于:https://my.oschina.net/rusheng/blog/911636

Entities/Request*.cs 用于接收微信平台自动发送到服务器的实体(发送过来的是XML),包括文本、位置、图片三类 Entities/Response*.cs 用于反馈给发送人的信息实体(最终会转成XML),包括文本、新闻(图文)两类 Helpers/EntityHelper.cs 用于实体和XML之间的转换(由于其中有许多需要特殊处理的字段和类型,这里不能简单用XML序列化) Helpers/MsgTypeHelper.cs 用于获取消息类型 CheckSignature.cs 验证请求合法性类 Enums.cs 各种枚举 RequestMessageFactory.cs 用于自动生成不同Request类型的实体,并作必要的数据填充 Senparc.Weixin.MP几个关键类及重要方法(按一般使用过程排序) 生成验证字符串:Senparc.Weixin.MP.CheckSignature.GetSignature(string timestamp, string nonce, string token = null),返回根据微信平台提供的数据,SHA1加密后的验证字符串(注意token必须跟公众平台的设置一直) 验证请求:Senparc.Weixin.MP.CheckSignature.Check(string signature, string timestamp, string nonce, string token = null),验证请求是否合法 获取请求实体:var requestMessage = Senparc.Weixin.MP.RequestMessageFactory.GetRequestEntity(XDocument doc); 根据不同请求的类型,自动生成可用于操作的实体(doc只需要用XDocument.Parse(xmlString)就能生成),requestMessage.MsgType就是请求枚举类型。 进行判断及各类操作。 根据需要,创建响应类型的实体,如:var responseMessage = ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.Text) as ResponseMessageText; 即可返回文本类型信息。 由于目前微信只接受XML的返回数据,所以在返回之前还需要做一次转换:XDocument responseDoc = Senparc.Weixin.MP.Helpers.EntityHelper.ConvertEntityToXml(responseMessage); var xmlString =responseDoc.ToString(); 至此整个微信公众账号的自动响应过程结束。 下面可以直接下载源代码及示例(示例是ASP.NET MVC 4,.NET 4.0,为了提高兼容性,Senparc.Weixin.MP源代码使用.NET 3.5): 压缩包中包含三个文件夹:Senparc.Weixin.MP、Senparc.Weixin.MP.BuildOutPut、Senparc.Weixin.MP.Sample,分别对应Senparc.Weixin.MP.dll源代码项目、Senparc.Weixin.MP.dll输出目录、Web示例,Web示例建议放到公网测试,让公众平台自动发送
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值