WeChatCommon.php 8.3 KB
<?php

class WeChatCommon
{

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

    /**
     * 获取code
     */
    public function code()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . config('AppID') . "&redirect_uri=http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "&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);
        curl_close($ch);
        $json_obj = json_decode($res, true);
        return $json_obj;
    }

    /**
     * 获取access_token,全局缓存7200s
     * @return mixed
     */
    public function getAccessToken()
    {
        $data = cache('Vendor/access_token');
        if (!empty($data) && ((time() - $data['time']) < 7000)) {
            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
            );
            cache('Vendor/access_token', $data);
            return $access_token;
        }
    }

    /**
     * 获取用户信息(头像、昵称等)
     * @return array
     */
    public function getUserInfo($info)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $info['access_token'] . '&openid=' . $info['openid'] . '&lang=zh_CN';
        $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);
        return $jsoninfo;
    }

    /**
     * 下载网址内容,配合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('data/upload/headimg/' . $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=je9omv03bc5ryqz1&timestamp=' . $timestamp . '&url=' . 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $signature = sha1($string);
        return array(
            'appId' => config('AppId'),
            'timestamp' => $timestamp,
            'nonceStr' => 'je9omv03bc5ryqz1',
            'signature' => $signature,
        );
    }

    /**
     * 创建菜单
     * @return mixed|string
     */
    public function creatMenu()
    {
        $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://hospital.wx.bronet.cn/index.php/UserCenter/login"
			}],
			"button":[{	
         		"type":"view",
          		"name":"医生预约",
          		"url":"http://hospital.wx.bronet.cn/index.php/DoctorAppointment/index"
			}],
			"button":[{	
         		"type":"view",
          		"name":"个人中心",
          		"url":"http://hospital.wx.bronet.cn/index.php/UserCenter/index"
			}]
		}';
        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;
        }
    }

}