博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
微信开发经常会用到的一些方法
阅读量:5136 次
发布时间:2019-06-13

本文共 6869 字,大约阅读时间需要 22 分钟。

 public $config = array(

            "AppID"         =>  "wxde30b2bd1ce49e47",               //应用ID
            "AppSecret"     =>  "07d26f5fdb30a6cf4a14ee18b7017eb7",//应用密钥
        );
    /**
     *  获取登陆url
     *  $redirect_uri           回调地址
     *  $scope                  是否授权(snsapi_userinfo:授权,snsapi_base:不授权)
    */
    public function LoginUri($redirect_uri = "",$scope = "snsapi_base",$state = "123"){
        if(!$redirect_uri){
            die("请填写回掉地址!");
        }
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->config['AppID']}&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
    }
    /**
     *  获取用户信息
     */
    function UsInfo(){
        $str = $this->get_curl("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->config['AppID']}&secret={$this->config['AppSecret']}&code={$_GET['code']}&grant_type=authorization_code");
        $arr = json_decode($str,true);
        $message = $this->get_curl("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->config['AppID']}&grant_type=refresh_token&refresh_token={$arr['refresh_token']}");
        $arr1 = json_decode($message,true);
        $us_info = $this->get_curl("https://api.weixin.qq.com/sns/userinfo?access_token={$arr1['access_token']}&openid={$arr1['openid']}&lang=zh_CN");
        return json_decode($us_info,true);
    }
    /**
     *    获取access_token
     */
    function get_access_token(){
        $path = $_SERVER['DOCUMENT_ROOT']."/volunteer_hatosy/access_token.txt";
        $arr = json_decode(file_get_contents($path),true);
        if($arr){
            $expires_in = $arr['expires_in'];
        }else{
            $expires_in = 0;
        }
        if(!$arr || time() >= $expires_in){
            $str = $this->get_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->config['AppID']}&secret={$this->config['AppSecret']}");
            $info = json_decode($str,true);
            $info['expires_in'] = time() + 7000;
            $access_token = $info['access_token'];
            $this->fwrite_txt($path,json_encode($info));
        }else{
            $access_token = $arr['access_token'];
        }
        return $access_token;
    }
    /**
     *  获取随机数
     */
    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;
     }
    /**
     *  获取ticket
     */
    function get_ticket(){
        $path = $_SERVER['DOCUMENT_ROOT']."/volunteer_hatosy/tocket.txt";
        $arr = json_decode(file_get_contents($path),true);
        if(!$arr || time() >= $arr['expires_in']){
            $access_token = $this->get_access_token();
            $ticket = $this->get_curl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi");
            $info = json_decode($ticket,true);
            $info['expires_in'] = time() + 7000;
            $this->fwrite_txt($path,json_encode($info));
            return $info['ticket'];
        }else{
            return $arr['ticket'];
        }
    }
    /**
     *  获取signature
     */
    function signature(){
        $ticket = $this->get_ticket();
        $timestamp = time();
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $noncestr = $this->createNonceStr(10);
        $string = "jsapi_ticket={$ticket}&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        return array(
            'timestamp' => $timestamp,
            'noncestr' => $noncestr,
            'signature' => $signature
        );
    }
    /**
     *    获取二维码
     */
    function get_ercode($us_id = 0){
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
        $param = array(
                "action_name"=>"QR_LIMIT_SCENE",
                "action_info"=>array("scene"=>array("scene_id"=>intval($us_id)))
            );
        $xml = $this->post_curl($url,json_encode($param));
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode(json_decode($xml)->ticket);
    }
    function post_curl($url,$data,$agreement = 0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if($agreement == 0){//0 https   1   http
            unset($_REQUEST['agreement']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    function get_curl($url,$agreement = 0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if($agreement == 0){//0 https   1   http
            unset($_REQUEST['agreement']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    function uploadMedia(){
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=voice";
        $file = realpath('1482826121.amr'); //要上传的文件
        $fields['media'] = '@'.$file;
        $ch = curl_init($url) ;
        curl_setopt($ch, CURLOPT_POST, 1);
        if($agreement == 0){//0 https   1   http
            unset($_REQUEST['agreement']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch) ;
        if (curl_errno($ch)) {
            dump(curl_errno($ch));
        }
        curl_close($ch);
        dump($result);
    }
    /**
     *    获取语音
     */
    public function getVoice(){
        $media_id = '_pnBKlv6Xp7VzI28UEpxYQaEknMI7mWZ4tROP9Bvpc7QjkC9GbDUy3Yuma4J7TgT';
        $access_token = $this->get_access_token();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
        $fileInfo = $this->downloadWeixinFile($url);
        $fileName = time().".amr";
        $this->saveWeixinFile($fileName,$fileInfo['body']);
    }
    function downloadWeixinFile($url){
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_NOBODY,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $package = curl_exec($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header'=>$httpinfo),array('body'=>$package));
        return $imageAll;
    }
    function saveWeixinFile($filename,$filecontent){
        $local_file = fopen($filename,'w');
        if(local_file !== false){
            if(fwrite($local_file,$filecontent) !== false){
                fclose($local_file);
            }
        }
    }
    
    /*文件写入*/
    function fwrite_txt($path,$txt){
        $myfile = fopen($path,"w") or die("Unable to open file!");
        fwrite($myfile,$txt);
        fclose($myfile);
    }
    /*文件读取*/
    function fread_txt($path){
        $txt = file_get_contents($path);
        return $txt;
    }

转载自:https://blog.csdn.net/qq_34629975/article/details/53906144 

转载于:https://www.cnblogs.com/myJuly/p/10077800.html

你可能感兴趣的文章
前端性能优化之重排和重绘
查看>>
Assets和Raw区别
查看>>
【luogu4185】 [USACO18JAN]MooTube [并查集]
查看>>
手机号脱敏处理
查看>>
CI控制器调用内部方法并载入相应模板的做法
查看>>
Hdu - 1002 - A + B Problem II
查看>>
HDU - 2609 - How many
查看>>
每天CookBook之Python-003
查看>>
每天CookBook之Python-004
查看>>
Android设置Gmail邮箱
查看>>
StringBuffer的用法
查看>>
js编写时间选择框
查看>>
PHP压缩文件操作
查看>>
4.你认为一些军事方面的软件系统采用什么样的开发模型比较合适?
查看>>
日常开发需要掌握的Maven知识
查看>>
Java数据结构和算法(四)--链表
查看>>
JIRA
查看>>
ssl介绍以及双向认证和单向认证原理
查看>>
【BZOJ2441】【中山市选2011】小W的问题(树状数组+权值线段树)
查看>>
小技巧——直接在目录中输入cmd然后就打开cmd命令窗口
查看>>