微信SDK图片上传功能-程序员宅基地

技术标签: ViewUI  json  php  javascript  

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34214500/article/details/91914402

智能推荐

攻防世界_难度8_happy_puzzle_攻防世界困难模式攻略图文-程序员宅基地

文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文

达梦数据库的导出(备份)、导入_达梦数据库导入导出-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作  导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释:   cwy_init/init_123..._达梦数据库导入导出

js引入kindeditor富文本编辑器的使用_kindeditor.js-程序员宅基地

文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js

STM32学习过程记录11——基于STM32G431CBU6硬件SPI+DMA的高效WS2812B控制方法-程序员宅基地

文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6

计算机网络-数据链路层_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输-程序员宅基地

文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输

软件测试工程师移民加拿大_无证移民,未受过软件工程师的教育(第1部分)-程序员宅基地

文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...

随便推点

Thinkpad X250 secure boot failed 启动失败问题解决_安装完系统提示secureboot failure-程序员宅基地

文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure

C++如何做字符串分割(5种方法)_c++ 字符串分割-程序员宅基地

文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割

2013第四届蓝桥杯 C/C++本科A组 真题答案解析_2013年第四届c a组蓝桥杯省赛真题解答-程序员宅基地

文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答

基于供需算法优化的核极限学习机(KELM)分类算法-程序员宅基地

文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。

metasploitable2渗透测试_metasploitable2怎么进入-程序员宅基地

文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入

Python学习之路:从入门到精通的指南_python人工智能开发从入门到精通pdf-程序员宅基地

文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf

推荐文章

热门文章

相关标签