微信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

智能推荐

公司百度百科词条内容应该怎么写,有哪些要避免和注意的_公司百度百科词条怎么写-程序员宅基地

文章浏览阅读67次。百度百科可以说对参考资料这块的要求很苛刻,有些时候即使你使用门户平台主站的新闻也未必能够通过。而这也是许多词条创建不通过的重大原因,因为百度对参考资料的可靠性还是非常严格的。_公司百度百科词条怎么写

Tomcat异常Serveral ports(8005,8080,8009) required by Tomcat v8.0 Server at localhost are already in_several ports (8005, 8080, 8009) required by tomca-程序员宅基地

文章浏览阅读2.2k次。在开始菜单->运行->cmd->输入netstat -ano命令,可以查看哪个进程占用了8080和8009端口,找到占用端口软件的PID,然后在任务管理器找到对应PID的软件,关闭结束该进程即可。可能是在打开Tomcat的情况下关闭了Eclipse/其他IDE,或是Eclipse/其他IDE非正常关闭,导致先前的Tomcat没有被关闭,端口占用。Connector 节点,将port="8080"中的端口改为一个没有被占用的端口,如10080。方法2:修改tomcat默认端口号。方法1:杀掉占用端口的软件。._several ports (8005, 8080, 8009) required by tomcat v8.0 server at localhost

饮料售卖机FSM_设计一个自动饮料售卖机画出fsm-程序员宅基地

文章浏览阅读452次。同步状态机状态机的类型mealymoore状态编码要求状态图代码仿真结果总结状态机的类型mealy输出与当前状态及输入有关本状态机应该就属于mealy状态机moore输出只与当前状态有关目前还没遇到这种状态机,我认为应该就是只有状态的转换吧,不考虑输入。状态编码我们知道有三种编吗方式;1.binary编码:状态描述简洁,占用较少寄存器资源,是比较常用的状态机编码方式;2.gr..._设计一个自动饮料售卖机画出fsm

291 蒙德里安的梦想(状态压缩dp)_291. 蒙德里安的梦想-程序员宅基地

文章浏览阅读246次。1. 问题描述:求把 N×M 的棋盘分割成若干个 1×2 的的长方形,有多少种方案。例如当 N=2,M=4 时,共有 5 种方案。当 N=2,M=3 时,共有 3 种方案。如下图所示:输入格式输入包含多组测试用例。每组测试用例占一行,包含两个整数 N 和 M。当输入用例 N=0,M=0 时,表示输入终止,且该用例无需处理。输出格式每个测试用例输出一个结果,每个结果占一行。数据范围1 ≤ N,M ≤ 11输入样例:1 21 31 42 22 32 42 11_291. 蒙德里安的梦想

MapReduce设计模式学习笔记_mapreduce四个阶段的任务-程序员宅基地

文章浏览阅读1.9k次。MapReduce_mapreduce四个阶段的任务

Linux 常见特殊符号-程序员宅基地

文章浏览阅读78次。[size=large][b]1,> 重定向输出符号 用法:命令 >文件名 特性:覆盖(当输入文件和输出文件是同一文件,文 件内容被清空;不适合连续重定向) 典型应用:合并文件(cat a b >c);清空文件(cat /dev/null);文件打印2,>> 重定向输出符号 用法:命令 >>文..._linux不同字体下的¥

随便推点

C中结构体使用_c 结构体中使用结构体-程序员宅基地

文章浏览阅读147次。#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <string.h>/*1、结构体类型定义2、结构体变量定义3、结构体变量的初始化4、typedef改类型名5、点运算符和指针法操作结构体6、结构体也是一种数据类型,复合类型,自定义类型*///1、结构体类型定义//struct关键字//struct Teacher合一起才是类型//{}_c 结构体中使用结构体

C++中char转换short(或者int)要注意的现象_char数组转unsigned short-程序员宅基地

文章浏览阅读2.2k次。char temp = 0x80;cout << "unsigned short of 0x80=" << dec << (unsigned short)temp <<endl; //输出:unsigned short of 0x80=65408cout << "short of 0x80=" << dec << (short)temp <<endl; //输出:short of 0x80=-128un_char数组转unsigned short

AD学习笔记-程序员宅基地

文章浏览阅读106次。1、12345678设置为对齐快捷键(ctrl+左键可设置)2、尺寸要合适,不然在原理图中大小不一3、空格转向4、T+c可以快速加入新的元器件。

CSS3淡入淡出滑块-程序员宅基地

文章浏览阅读646次。CSS3 Fade slider Today I would like to show you how to create nice and smooth css3 slider. It uses fade effect to switch between slides. Plus, you can use custom promo text for each slide. We will use...

adb shell 命令行模拟发送开机广播android.intent.action.BOOT_COMPLETED测试开机自启动_am broadcast -a android.intent.action.boot_complet-程序员宅基地

文章浏览阅读1.2w次。开发中需求需要监听开机广播android.intent.action.BOOT_COMPLETED,然后让应用开机自启动。以前测试总是傻傻的关机然后再开机再验证有没自启动,很浪费时间,现在发现原来可以通过adb shell命令模拟开机广播,记录下模拟开机广播adb shell am broadcast -a android.intent.action.BOOT_COMPLETED当然..._am broadcast -a android.intent.action.boot_completed

windows环境Elasticsearch安装启动,配置ik分词器及安装head插件_es,ik,head启动-程序员宅基地

文章浏览阅读642次。整理一下windows版ES的简单部署过程1:安装ES官网下载ES的zip包,https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.4.2-windows-x86_64.zip下载好之后直接解压,然后在/bin下直接点击elasticsearch.bat启动这个就是成功跑起来了,接下来去浏览器访问,..._es,ik,head启动

推荐文章

热门文章

相关标签