WeChatCommon.php 9.7 KB
<?php

class WeChatCommon {

    /**
     * 判断是否已关注公众号
     */
    public function isAuth($openid) {
        $access_token = $this->getAccessToken();
        $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid;
        $subscribe = json_decode(file_get_contents($subscribe_msg));
        $gzxx = $subscribe->subscribe;
        if($gzxx === 1){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 获取code
     */
    public function code(){
        $return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('AppID')."&redirect_uri=$return_url&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        header('location:'.$url);
    }

    /**
     * 获取openid
     * @param $code
     * @return mixed
     */
    public function getOpenId($code){
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('AppID').'&secret='.config('AppSecret').'&code='.$code .'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $get_token_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        if(!$res) {
            $res = curl_errno($ch);
        }
        curl_close($ch);
        $json_obj = json_decode($res, true);
//        if(empty($json_obj['openid'])) {
//            return $json_obj;
//        }
        $openid = $json_obj['openid'];
        return $openid;
    }

    /**
     * 获取access_token,全局缓存7200s
     * @return mixed
     */
    public function getAccessToken(){
        $data=cache('Vendor/access_token');
        if(!empty($data) && time() < $data['time']) {
            return $data['access_token'];
        }
        else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config('AppID')."&secret=".config('AppSecret')."";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            $jsoninfo = json_decode($output, true);
            $access_token = $jsoninfo["access_token"];
            $time=time();
            $data=array(
                'access_token'  =>  $access_token,
                'time'          =>  $time + 7000
            );
            cache('Vendor/access_token', $data);
            return $access_token;
        }
    }

    /**
     * 获取用户信息(头像、昵称等)
     * @return array
     */
    public function getUserInfo($openid){
        $url='https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->getAccessToken().'&openid='.$openid;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($output, true);
        return $data;
    }

    /**
     * 下载网址内容,配合getUserInfo使用
     * @param $url
     * @param $filename
     * @return mixed
     */
    public function curl_file_get_contents($url,$filename){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        //curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
        //curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $r = curl_exec($ch);
        curl_close($ch);
        file_put_contents('thumb/'.$filename, $r);
        return $filename;
    }

    /**
     * 获取js-sdkp票据,全局缓存7200s
     * @return mixed
     */
    public function get_jsapi_ticket(){
        $ticket=cache('Vendor/ticket');
        if(!empty($ticket) && ((time()-$ticket['time']) < 7000)) {
            return $ticket['ticket'];
        }else {
            $url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$this->getAccessToken().'&type=jsapi';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
            $res = curl_exec($ch);
            curl_close($ch);
            $json_obj = json_decode($res, true);
            $jsapi_ticket = $json_obj['ticket'];
            $time=time();
            $data=array(
                'ticket'    =>  $jsapi_ticket,
                'time'      =>  $time
            );
            cache('Vendor/ticket', $data);
            return $jsapi_ticket;
        }
    }

    /**
     * JS_SDK
     * @return array
     */
    public function js_sdk(){
        $timestamp=time();
        $string='jsapi_ticket='.$this->get_jsapi_ticket().'&noncestr='.config('nonceStr').'&timestamp='.$timestamp.'&url='.'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $signature=sha1($string);
        return array(
            'appId' 	=> config('AppID'),
            'timestamp' => $timestamp,
            'nonceStr' 	=> config('nonceStr'),
            'signature' => $signature,
        );
    }

    /**
     * 创建菜单
     * @return mixed|string
     */
    public function createMenu(){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->getAccessToken());
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        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, $this->menuItem());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        curl_close($ch);
        return $tmpInfo;
    }

    /**
     * 菜单内容JSON
     * @return string
     */
    public function menuItem(){
        $data = '{
			"button":[{	
         		"type":"view",
          		"name":"易驾行",
          		"url":"http://yjxjpl.com/index.php/portal/Index/index"
			}],
			"button":[{	
         		"type":"view",
          		"name":"学车游戏",
          		"url":"http://www.973.com/xueche"
			}],
			"button":[{	
         		"type":"view",
          		"name":"关于我们",
          		"url":"http://yjxjpl.com/index.php/portal/Subscribe/about"
			}],
		}';
        return $data;
    }

    /**
     * 上传永久素材
     */
    public function eternalMaterial(){
        $file_info = array('filename' => '/public/images/soul_of_cinder.png', //国片相对于网站根目录的路径
            'content-type' => 'image/jpg/png', //文件类型
            'filelength' => '71' //图文大小
        );
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$this->getAccessToken()."&type=png";
        $ch1 = curl_init();
        $timeout = 5;
        $real_path = "{$_SERVER['DOCUMENT_ROOT']}{$file_info['filename']}";
        //$real_path=str_replace("/", "//", $real_path);
        $data = array("media" => "@{$real_path}", 'form-data' => $file_info);
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch1);
        curl_close($ch1);
        if (curl_errno() == 0) {
            $result = json_decode($result, true);
            var_dump($result);
            return $result['media_id'];
        } else {
            return false;
        }
    }

    /**
     * 场景二维码
     */
    public function qrScene() {
        $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->getAccessToken();
        $param=[
            'expire_seconds'    =>  2592000,
            'action_name'       =>  'QR_STR_SCENE',
            'action_info'       =>  ['scene'=>['scene_str'=>session('user.openid')]]
        ];
        $result=$this->do_post_request($url, json_encode($param));
        $data=json_decode($result, true);
        $ticket=urlencode($data['ticket']);
        $qr_url='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;
        //var_dump($qr_url);
        return $qr_url;
    }

    protected function do_post_request($url, $data, $optional_headers = null) {
        $params = array('http' => array(
            'method' => 'POST',
            'content' => $data
        ));
        if ($optional_headers !== null) {
            $params['http']['header'] = $optional_headers;
        }
        $ctx = stream_context_create($params);
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp) {
            throw new Exception("Problem with $url, $php_errormsg");
        }
        $response = @stream_get_contents($fp);
        if ($response === false) {
            throw new Exception("Problem reading data from $url, $php_errormsg");
        }
        return $response;
    }

}