<?php
/**
 *
 * ============================================================================
 * * 版权所有 蜘蛛出行 * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm WeChatService.php
 * Create By 2017/3/2 11:09 $
 */


namespace common\util;

use yii\base\Exception;

class WeChatService
{
    //配置参数
    private $request = array();
    private $response = false;
    private $logMsg = '';
    private $token = '';
    private $appid = '';
    private $appsecret = '';

    public function __construct()
    {
        $wxConfig = WeChatPay::getAuthWeChatConfig();
        $this->token = $wxConfig['token'];
        $this->appid = $wxConfig['appid'];
        $this->appsecret = $wxConfig['appsecret'];
        $this->setLog(date('Y-m-d H:i:s'));
    }

    /**
     * Des:接收参数并处理返回值
     * Name: exec
     * @return string
     * @author 倪宗锋
     */
    public function exec()
    {
        $content = $this->getContent();//获取参数并解析

        if ($content['MsgType'] == 'text') {
            $this->response = $this->textMsg($content);
        } elseif ($content['MsgType'] == 'event') {
            $this->response = $this->eventMsg($content);
        }
        return $this->response;
    }

    /**
     * Des:用户输入内容处理
     * Name: textMsg
     * @param $content
     * @return bool|string
     * @author 倪宗锋
     */
    public function textMsg($content)
    {
        $textTpl = '' . "
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
        $resultStr = sprintf($textTpl, $content['FromUserName'], $content['ToUserName'], time());
        return $resultStr;
        $word = $content['Content'];
        return $this->send($word, $content, 'text');
    }

    /**
     * Des:推送事件处理
     * Name: eventMsg
     * @param $content
     * @return string
     * @author 倪宗锋
     */
    public function eventMsg($content)
    {
        if ($content['Event'] == 'subscribe') {//微信关注事件 发送欢迎语
            $word = 'subscribe';
        } elseif ($content['Event'] == 'unsubscribe') {//微信关注事件 发送欢迎语
            $word = 'unsubscribe';
        } else if (empty($content['EventKey'])) {
            return false;
        } else {
            $word = $content['EventKey'];
        }
        return $this->send($word, $content, 'event');

    }

    /**
     * Des: 发送处理
     * Name: send
     * @param $word
     * @param $content
     * @param string $type 触发类型：text用户输入 event推送事件
     * @return string
     * @author 倪宗锋
     */
    public function send($word, $content, $type = 'text')
    {
        $weChatPayConfig = WeChatPay::getAuthWeChatConfig();
        $textConfig = require ROOT_PATH . '/common/config/wechatConfig/wxInterface/' . $weChatPayConfig['mch_id'] . '/Wx.' . $type . '.config.php';
        if (empty($textConfig[$word]) == false) {
            $msgSend = $textConfig[$word];
        } else if ($type == 'text') {
            $msgSend = $textConfig['default'];
        } else {
            return false;
        }
        $this->setLog('sendMsg:' . print_r($msgSend, 1));
//        if (is_array($msgSend) && empty($msgSend['function']) == false) {//当推送事件有方法指定时，则调用该方法
//            $wxDoFunction = new WxDoFunction();
//            $function = $msgSend['function'];
//            $wxDoFunction->$function($content);
//        }
        if (isset($msgSend['type']) && $msgSend['type'] == 'news') {//如果是图文类型
            return $this->sendNews($content, $msgSend['id']);
        } elseif (isset($msgSend['type']) && $msgSend['type'] == 'img') {//如果是图片类型
            return $this->sendImage($content, $msgSend['id']);
        } elseif (isset($msgSend['type']) && $msgSend['type'] == 'voice') {//如果是语音类型
            return $this->sendVoice($content, $msgSend['id']);
        } elseif (isset($msgSend['type']) && $msgSend['type'] == 'video') {//如果是视频类型
            return $this->sendVideo($content, $msgSend);
        } else {//否则是文字信息
            return $this->sendText($content, $msgSend);
        }
    }

    /**
     * Des:发送文字
     * Name: sendText
     * @param $content
     * @param $msgSend
     * @return string
     * @author 倪宗锋
     */
    private function sendText($content, $msgSend)
    {
        $textTpl = '' . "
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $msgType = "text";
        if (is_array($msgSend)) {
            $msgSend = $msgSend['text'];
        }
        $resultStr = sprintf($textTpl, $content['FromUserName'], $content['ToUserName'], time(), $msgType, $msgSend);
        return $resultStr;
    }

    /**
     * Des:发送图文
     * Name: sendNews
     * @param $content array
     * @param $mediaId string 素材图文 ID
     * @return string
     * @author 倪宗锋
     */
    private function sendNews($content, $mediaId)
    {
        $news = $this->getNewsByMediaId($mediaId);
        return $this->transmitNews($content, $news);
    }

    /**
     * Des:发送图片
     * Name: sendImage
     * @param $content
     * @param $mediaId
     * @return string
     * @author 倪宗锋
     */
    private function sendImage($content, $mediaId)
    {
        $xmlTpl = '' . "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
 </xml>";
        $result = sprintf($xmlTpl, $content['FromUserName'], $content['ToUserName'], time(), $mediaId);
        return $result;
    }

    /**
     * Des:发送语音
     * Name: sendVoice
     * @param $content
     * @param $mediaId
     * @return string
     * @author 倪宗锋
     */
    private function sendVoice($content, $mediaId)
    {
        $xmlTpl = '' . "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>
</xml>";
        $result = sprintf($xmlTpl, $content['FromUserName'], $content['ToUserName'], time(), $mediaId);
        return $result;
    }

    /**
     * Des:发送视频
     * Name: sendVideo
     * @param $content
     * @param $sendMsg
     * @return string
     * @author 倪宗锋
     */
    private function sendVideo($content, $sendMsg)
    {
        $xmlTpl = '' . "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
<Video>
<MediaId><![CDATA[%s]]></MediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>
</xml>";
        $result = sprintf($xmlTpl, $content['FromUserName'], $content['ToUserName'], time(), $sendMsg['id'], $sendMsg["title"], $sendMsg["des"]);
        return $result;
    }

    /**
     * Des:根据ID获取图文信息
     * Name: getNewsByMediaId
     * @param $data_media_id
     * @return array
     * @author 倪宗锋
     */
    public function getNewsByMediaId($data_media_id)
    {
        $data_media_id = '{"media_id":"' . $data_media_id . '"}';
        $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->getAccessToken();
        $response = $this->_requestPost($url, $data_media_id);
        $media = json_decode($response, true);
        $mediaArray = $media['news_item'];
        $content = array();
        foreach ($mediaArray as $k => $v) {
            if ($k == 0 || $k == 1)
                $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
            elseif ($k == 2) {
                $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
            } else
                $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
        }
        return $content;
    }

    /**
     * Des:图文推送数据处理
     * Name: transmitNews
     * @param $content
     * @param $newsArray
     * @return string
     * @author 倪宗锋
     */
    private function transmitNews($content, $newsArray)
    {
        if (!is_array($newsArray)) {
            return '';
        }
        $itemTpl = '' . "<item><Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url></item>";
        $item_str = "";
        foreach ($newsArray as $item) {
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = '' . "<xml>
<ToUserName><![CDATA[{$content['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$content['ToUserName']}]]></FromUserName>
<CreateTime>" . time() . "</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>" . count($newsArray) . "</ArticleCount>
<Articles>$item_str</Articles>
</xml>";
//        $result = sprintf($xmlTpl, $content['FromUserName'], $content['ToUserName'], time(), count($newsArray));
        return $xmlTpl;
    }

    /*************************=========第一次请求校验==========***********************************/
    /**
     * Des:第一次校验
     * Name: valid
     * @return bool
     * @author 倪宗锋
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            $this->response = $echoStr;
        }
        return $this->response;
    }

    /***********************************通用函数*******************************************************/
    /**
     * Des:根据openid获取用户信息
     * Name: getUserInfoByOpenid
     * @param $openid
     * @return array
     * @author 倪宗锋
     */
    public static function getUserInfoByOpenid($openid)
    {
        $token = static::getAccessToken();
        $userInfo = static::getWeChatInfo($openid, $token);
        return $userInfo;
    }

    /**
     * Des:获取微信用户信息
     * Name: getWeChatInfo
     * @param $openid
     * @param $accessToken string  基础公共access_token
     * @return array
     * @author 倪宗锋
     */
    public static function getWeChatInfo($openid, $accessToken)
    {
        $query = array(
            'access_token' => $accessToken,
            'openid' => $openid,
            'lang' => 'zh_CN'
        );
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?";
        $url .= http_build_query($query);
        $curl = new CurlInterface('', 4);
        $arr = $curl->execute($url);
        $return = [
            'nickname' => $arr['nickname'],
            'headimgurl' => $arr['headimgurl'],
            'sex' => $arr['sex'],
            'country' => $arr['country'],
            'city' => $arr['city'],
            'province' => $arr['province']
        ];
        return $return;
    }

    /**
     * Des:
     * Name: getAuthWeChatInfo
     * @param $openid
     * @param $accessToken string 授权获取的accessToken
     * @return array
     * @author 倪宗锋
     */
    public static function getAuthWeChatInfo($openid, $accessToken)
    {
        $query = array(
            'access_token' => $accessToken,
            'openid' => $openid,
            'lang' => 'zh_CN'
        );
        $url = "https://api.weixin.qq.com/sns/userinfo?";
        $url .= http_build_query($query);
        $curl = new CurlInterface('', 4);
        $arr = $curl->execute($url);
        $return = [
            'nickname' => $arr['nickname'],
            'headimgurl' => $arr['headimgurl'],
            'sex' => $arr['sex'],
            'country' => $arr['country'],
            'city' => $arr['city'],
            'province' => $arr['province']
        ];
        return $return;
    }

    /**
     * Des:数据校验
     * Name: checkSignature
     * @return bool
     * @author 倪宗锋
     */
    private function checkSignature()
    {
        $token = $this->token;
        $signature = isset($_GET["signature"]) ? $_GET["signature"] : "";
        $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : "";
        $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : "";
        $tmpArr = array($token, $timestamp, $nonce);
        $this->setLog('param:' . print_r($tmpArr, 1));
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Des:参数解析
     * Name: getContent
     * @author 倪宗锋
     */
    private function getContent()
    {
        $content = file_get_contents("php://input");
        $this->setLog('content: ' . print_r($content, 1));
        libxml_disable_entity_loader(true);
        $this->request = (array)simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
        return $this->request;
    }

    /**
     * Des:获取token
     * Name: getAccessToken
     * @return string
     * @author 倪宗锋
     */
    public static function getAccessToken()
    {
        $wxConfig = WeChatPay::getAuthWeChatConfig();
        $appid = $wxConfig['appid'];
        $appsecret = $wxConfig['appsecret'];
        $time = time();
        $data['appid'] = $appid;
        $data['appsecret'] = $appsecret;
        $data['time'] = $time;
        $param = [
            'code' => Util::authCode(http_build_query($data), 'ENCODE'),
            'time' => $time
        ];
        $curl = new CurlInterface($param, 4);
        $siteConfig = Util::getSiteConfig();
        $return = $curl->execute($siteConfig['wx_get_token'] . '/zzcx/interfaces/fx/get-wx-token', 'POST');
        return $return;

    }

    /**
     * Function Description:根据code获取token
     * Function Name: getToken
     * @param $code
     *
     * @return array
     *
     * @author 倪宗锋
     */
    public static function getToken($code)
    {
        $WxPayConfig = WeChatPay::getAuthWeChatConfig();
        $siteConfig = Util::getSiteConfig();
        $urlObj["appid"] = $WxPayConfig['appid'];
        $urlObj["secret"] = $WxPayConfig['appsecret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = http_build_query($urlObj);
        $url = $siteConfig['authTokenUrl'] . $bizString;
        $curlInterface = new CurlInterface('', 4);
        $curlInterface->setBaseUrl($url);
        $getToken = $curlInterface->execute('', 'GET');
        if (empty($getToken['openid'])) {
            return Util::returnArrEr('参数无效！');
        }
        return Util::returnArrSu('', $getToken);
    }

    /**
     * Des:发起get请求
     * Name: _requestGet
     * @param $url string
     * @param bool|true $ssl
     * @return bool|mixed
     * @author 倪宗锋
     */
    public static function _requestGet($url, $ssl = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        if ($ssl) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        }
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        if ($response === false) {
            return false;
        }
        return $response;
    }

    /**
     * Des:发起post请求
     * Name: _requestPost
     * @param $url
     * @param $data
     * @param bool|true $ssl
     * @return bool|mixed
     * @author 倪宗锋
     */
    public static function _requestPost($url, $data, $ssl = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        if ($ssl) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
        }
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        if ($response === false) {
            return false;
        }
        return $response;
    }

    /**
     * Des:获取
     * Name: httpRequest
     * @param $url
     * @param null $data
     * @return mixed
     * @author 倪宗锋
     */
    static function httpRequest($url, $data = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    public function setLog($logMsg)
    {
        $logMsg = str_replace(PHP_EOL, '', $logMsg);
        $logMsg = preg_replace("/\s(?=\s)/", "\\1", $logMsg);
        $this->logMsg .= $logMsg . PHP_EOL;
    }

    /**
     * 项目关闭 写入日志
     */
    public function __destruct()
    {
        $this->setLog(print_r($this->response, 1));//写入返回值
        $fileName = APP_PATH . '/log/WXLog/wxinterface' . date('Y-m-d') . '.log';
        file_put_contents($fileName, $this->logMsg . PHP_EOL, FILE_APPEND);
    }

    /**
     * Des:获取 扫一扫二维码地址
     * Name: getSaoCode
     * @param $fxUid
     * @return string
     * @author 倪宗锋
     */
    public static function getSaoCode($fxUid)
    {
        $siteConfig = Util::getSiteConfig();
        Util::setSiteConfig(['entryAuthWeChat' => $siteConfig['wxWeChat']]);
        if (empty($fxUid)) {
            return 'id不能为空！';
        }
        $token = static::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $token;
        $data = array(
            'action_name' => 'QR_LIMIT_SCENE',
            'action_info' => array(
                'scene' => array(
                    'scene_id' => $fxUid
                )
            )
        );
        $inface = new CurlInterface($data);
        $inface->setBaseUrl($url);
        $return = $inface->execute('', 'POST');
        if (empty($return['ticket']) == false) {
            $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $return['ticket'];
        } else {
            $url = '';
        }
        return $url;
    }

    /**
     * Des:获取分销二维码
     * Name: getFxQrCode
     * @param $fx_uid
     * @return array
     * @author 倪宗锋
     */
    public static function getFxQrCode($fx_uid)
    {
        try {
            $config = Util::getSiteConfig();
            $imgUrl = ROOT_PATH . '/web/fx/images/FxQrCode/' . $fx_uid . '.jpg';
            $showUrl = $config['host_name'] . '/web/fx/images/FxQrCode/' . $fx_uid . '.jpg';
            if (file_exists($imgUrl)) {
                return Util::returnArrSu('', array('url' => $showUrl));
            }
            $codeId = intval($fx_uid) + 50000;
            $wxCodeUrl = static::getSaoCode($codeId);
            $getCodeInfo = static::getWxImgInfo($wxCodeUrl);
            $local = fopen($imgUrl, 'w');
            if (false !== $local) {
                if (false !== fwrite($local, $getCodeInfo['body'])) {
                    fclose($local);
                }
            }
            if (file_exists($imgUrl)) {
                return Util::returnArrSu('', array('url' => $showUrl));
            }
        } catch (Exception $e) {
        }
        return Util::returnArrEr('生成二维码失败！');
    }

    public static function getFxNewQrCode($fx_uid)
    {
        try {
            $config = Util::getSiteConfig();
            include ROOT_PATH . '/common/util/phpqrcode/phpqrcode.php';
            $QRFile = ROOT_PATH . '/web/fx/images/FxQrCode/' . $fx_uid . 'new.png';
            $showUrl = $config['host_name'] . '/web/fx/images/FxQrCode/' . $fx_uid . 'new.png';
            if (file_exists($QRFile)) {
                return Util::returnArrSu('', array('url' => $showUrl));
            }
            $value = $config['zzcx_host'].$config['wx_home']."&fx_uid=".$fx_uid;//二维码内容
            $errorCorrectionLevel = 'H';//容错级别
            $matrixPointSize = 6;//生成图片大小
            //生成二维码图片
            $logo = false;
            \QRcode::png($value, $QRFile, $errorCorrectionLevel, $matrixPointSize, 2);
            $QR = imagecreatefromstring(file_get_contents($QRFile));
            if ($logo !== FALSE) {
                $logo = imagecreatefromstring(file_get_contents($logo));
                $QR_width = imagesx($QR);//二维码图片宽度
                $logo_width = imagesx($logo);//logo图片宽度
                $logo_height = imagesy($logo);//logo图片高度
                $logo_qr_width = $QR_width / 5;
                $scale = $logo_width / $logo_qr_width;
                $logo_qr_height = $logo_height / $scale;
                $from_width = ($QR_width - $logo_qr_width) / 2;
                //重新组合图片并调整大小
                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                    $logo_qr_height, $logo_width, $logo_height);
            }
            if (file_exists($QRFile)) {
                return Util::returnArrSu('', array('url' => $showUrl));
            }
        } catch (Exception $e) {
            print_r($e->getMessage());die;
        }
        return Util::returnArrEr('生成二维码失败！');
    }
    /**
     * Des:获取微信二维码数据流
     * Name: getWxImgInfo
     * @param $wxCodeUrl
     * @return array
     * @author 倪宗锋
     */
    public static function getWxImgInfo($wxCodeUrl)
    {
        $ch = curl_init($wxCodeUrl);
        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);
        $httpInfo = curl_getinfo($ch);
        curl_close($ch);
        return array_merge(['body' => $package], ['header' => $httpInfo]);
    }

}