1. 程式人生 > >一個處理微信授權和獲取使用者資訊的工具類

一個處理微信授權和獲取使用者資訊的工具類

<?php

/**
 * ECTouch Open Source Project
 * ============================================================================
 * Copyright (c) 2012-2014 http://ectouch.cn All rights reserved.
 * ----------------------------------------------------------------------------
 * 檔名稱:WechatControoller.class.php
 * ----------------------------------------------------------------------------
 * 功能描述:微信公眾平臺API
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.ectouch.cn/docs/license.txt )
 * ----------------------------------------------------------------------------
 */
/* 訪問控制 */
defined('IN_ECTOUCH') or die('Deny Access');

class WechatController extends CommonController
{

    private $weObj = '';

    private $orgid = '';

    private $wechat_id = '';

    /**
     * 建構函式
     */
    public function __construct()
    {
        parent::__construct();
        
        // 獲取公眾號配置
        $this->orgid = I('get.orgid');
        if (! empty($this->orgid)) {
            $wxinfo = $this->get_config($this->orgid);
            
            $config['token'] = $wxinfo['token'];
            $config['appid'] = $wxinfo['appid'];
            $config['appsecret'] = $wxinfo['appsecret'];
            $this->weObj = new Wechat($config);
            $this->weObj->valid();
            $this->wechat_id = $wxinfo['id'];
        }
    }

    /**
     * 執行方法
     */
    public function index()
    {
        // 事件型別
        $type = $this->weObj->getRev()->getRevType();
        $wedata = $this->weObj->getRev()->getRevData();
        $keywords = '';
        if ($type == Wechat::MSGTYPE_TEXT) {
            $keywords = $wedata['Content'];
        } elseif ($type == Wechat::MSGTYPE_EVENT) {
            if ('subscribe' == $wedata['Event']) {
                // 使用者掃描帶引數二維碼(未關注)
                if (isset($wedata['Ticket']) && ! empty($wedata['Ticket'])) {
                    $scene_id = $this->weObj->getRevSceneId();
                    $flag = true;
                    // 關注
                    $this->subscribe($wedata['FromUserName'], $scene_id);
                }  
                else{
                    // 關注
                    $this->subscribe($wedata['FromUserName']);
                    // 關注時回覆資訊
                    $this->msg_reply('subscribe');
                    exit;
                }                
            } elseif ('unsubscribe' == $wedata['Event']) {
                // 取消關注
                $this->unsubscribe($wedata['FromUserName']);
                exit();
            } elseif ('MASSSENDJOBFINISH' == $wedata['Event']) {
                // 群髮結果
                $data['status'] = $wedata['Status'];
                $data['totalcount'] = $wedata['TotalCount'];
                $data['filtercount'] = $wedata['FilterCount'];
                $data['sentcount'] = $wedata['SentCount'];
                $data['errorcount'] = $wedata['ErrorCount'];
                // 更新群髮結果
                $this->model->table('wechat_mass_history')
                    ->data($data)
                    ->where('msg_id = "' . $wedata['MsgID'] . '"')
                    ->update();
                exit();
            } elseif ('CLICK' == $wedata['Event']) {
                // 點選選單
                $keywords = $wedata['EventKey'];
            } elseif ('VIEW' == $wedata['Event']) {
                $this->redirect($wedata['EventKey']);
            } elseif ('SCAN' == $wedata['Event']) {
                $scene_id = $this->weObj->getRevSceneId();
            }
        } else {
            $this->msg_reply('msg');
            exit();
        }
        //掃描二維碼
        if(!empty($scene_id)){
            $qrcode_fun = $this->model->table('wechat_qrcode')->field('function')->where('scene_id = "'.$scene_id.'"')->getOne();
            //掃碼引薦
            if(!empty($qrcode_fun) && isset($flag)){
                //增加掃描量
                $this->model->table('wechat_qrcode')->data('scan_num = scan_num + 1')->where('scene_id = "'.$scene_id.'"')->update();
            }
            $keywords = $qrcode_fun;
        }
        // 回覆
        if (! empty($keywords)) {
            $keywords = html_in($keywords);
            //記錄使用者操作資訊
            $this->record_msg($wedata['FromUserName'], $keywords);
            // 多客服
            $rs = $this->customer_service($wedata['FromUserName'], $keywords);
            if (empty($rs) && $keywords != 'kefu') {
                // 功能外掛
                $rs1 = $this->get_function($wedata['FromUserName'], $keywords);
                if (empty($rs1)) {
                    // 關鍵詞回覆
                    $rs2 = $this->keywords_reply($keywords);
                    if (empty($rs2)) {
                        //推薦商品
                        $rs_rec = $this->recommend_goods($wedata['FromUserName'], $keywords);
                        if(empty($rs_rec)){
                            // 訊息自動回覆
                            $this->msg_reply('msg');    
                        }
                    }
                }
            }
        }
    }

    /**
     * 關注處理
     *
     * @param array $info            
     */
    private function subscribe($openid = '', $scene_id = 0)
    {
        if(!empty($openid)){
            // 使用者資訊
            $info = $this->weObj->getUserInfo($openid);
            if (empty($info)) {
                $info = array();
            }
            // 查詢使用者是否存在
            $where['openid'] = $openid;
            $rs = $this->model->table('wechat_user')
                ->field('ect_uid, subscribe')
                ->where($where)
                ->find();
            // 未關注
            if (empty($rs)) {
                $ect_uid = 0;
                //檢視公眾號是否繫結
                if(isset($info['unionid'])){
                    $ect_uid = $this->model->table('wechat_user')->field('ect_uid')->where(array('unionid'=>$info['unionid']))->getOne();
                }
                //使用者未繫結
                if(empty($ect_uid)){
                    // 設定的使用者註冊資訊
                    $register = $this->model->table('wechat_extend')
                        ->field('config')
                        ->where('enable = 1 and command = "register_remind" and wechat_id = '.$this->wechat_id)
                        ->find();
                    if (! empty($register)) {
                        $reg_config = unserialize($register['config']);
                        $username = msubstr($reg_config['user_pre'], 3, 0, 'utf-8', false) . time().mt_rand(1, 99);
                        // 密碼隨機數
                        $rs = array();
                        $arr = range(0, 9);
                        $reg_config['pwd_rand'] = $reg_config['pwd_rand'] ? $reg_config['pwd_rand'] : 5;
                        for ($i = 0; $i < $reg_config['pwd_rand']; $i ++) {
                            $rs[] = array_rand($arr);
                        }
                        $pwd_rand = implode('', $rs);
                        // 密碼
                        $password = $reg_config['pwd_pre'] . $pwd_rand;
                        // 通知模版
                        $template = str_replace(array(
                            '[$username]',
                            '[$password]'
                        ), array(
                            $username,
                            $password
                        ), $reg_config['template']);
                    } else {
                        $username = 'wx_' . time().mt_rand(1, 99);
                        $password = 'ecmoban';
                        // 通知模版
                        $template = '預設使用者名稱:' . $username . "\r\n" . '預設密碼:' . $password;
                    }
                    // 使用者註冊
                    $scene_id = empty($scene_id) ? 0 : $scene_id;
                    $scene_user_id = $this->model->table("users")->field('user_id')->where(array('user_id'=>$scene_id))->getOne();
                    $scene_user_id = empty($scene_user_id) ? 0 : $scene_user_id;
                    $domain = get_top_domain();
                    if (model('Users')->register($username, $password, $username . '@' . $domain, array('parent_id'=>$scene_user_id)) !== false) {
                        model('Users')->update_user_info();
                    } else {
                        die('');
                    }
                    $data['ect_uid'] = $_SESSION['user_id'];
                }
                else{
                    //微信使用者已繫結
                    $username = model('Base')->model->table('users')->field('user_name')->where(array('user_id'=>$ect_uid))->getOne();
                    $template = '您已擁有帳號,使用者名稱為'.$username;
                    $data['ect_uid'] = $ect_uid;
                }
                // 獲取使用者所在分組ID
                //$group_id = $this->weObj->getUserGroup($openid);
                $data['group_id'] = isset($info['groupid']) ? $info['groupid'] : $this->weObj->getUserGroup($openid);
                // 獲取被關注公眾號資訊
                $data['wechat_id'] = $this->wechat_id;
                $data['subscribe'] = $info['subscribe'];
                $data['openid'] = $info['openid'];
                $data['nickname'] = $info['nickname'];
                $data['sex'] = $info['sex'];
                $data['city'] = $info['city'];
                $data['country'] = $info['country'];
                $data['province'] = $info['province'];
                $data['language'] = $info['country'];
                $data['headimgurl'] = $info['headimgurl'];
                $data['subscribe_time'] = $info['subscribe_time'];
                $data['remark'] = $info['remark'];
                $data['unionid'] = isset($info['unionid']) ? $info['unionid'] : '';
                $this->model->table('wechat_user')->data($data)->insert();
                // 紅包資訊
                $content = $this->send_message($openid, 'bonus', $this->weObj, 1);
                $bonus_msg = '';
                if (! empty($content)) {
                    $bonus_msg = $content['content'];
                }
                if(!empty($template) || !empty($bonus_msg)){
                    // 微信端傳送訊息
                    $msg = array(
                        'touser' => $openid,
                        'msgtype' => 'text',
                        'text' => array(
                            'content' => $template . "\r\n" . $bonus_msg
                        )
                    );
                    $this->weObj->sendCustomMessage($msg);

                    //記錄使用者操作資訊
                    $this->record_msg($openid, $template . $bonus_msg, 1);
                }
            } else {
                //授權使用者送紅包
                $uid = model('Base')->model->table('wechat_user')->field('ect_uid')->where('openid = "'.$openid.'"')->getOne();
                if(!empty($uid)){
                    $bonus_num = model('Base')->model->table('user_bonus')->where('user_id = "'.$uid.'"')->count();
                    if($bonus_num <= 0){
                        // 紅包資訊
                        $content = $this->send_message($openid, 'bonus', $this->weObj, 1);
                        $bonus_msg = '';
                        if (! empty($content)) {
                            $bonus_msg = $content['content'];
                        }
                        if(!empty($bonus_msg)){
                            // 微信端傳送訊息
                            $msg = array(
                                'touser' => $openid,
                                'msgtype' => 'text',
                                'text' => array(
                                    'content' => $bonus_msg
                                )
                            );
                            $this->weObj->sendCustomMessage($msg);
                            //記錄使用者操作資訊
                            $this->record_msg($openid, $bonus_msg, 1);
                        }
                    }
                }

                // 獲取使用者所在分組ID
                $data['group_id'] = isset($info['groupid']) ? $info['groupid'] : $this->weObj->getUserGroup($openid);
                // 獲取被關注公眾號資訊
                $data['wechat_id'] = $this->wechat_id;
                $data['subscribe'] = $info['subscribe'];
                $data['openid'] = $info['openid'];
                $data['nickname'] = $info['nickname'];
                $data['sex'] = $info['sex'];
                $data['city'] = $info['city'];
                $data['country'] = $info['country'];
                $data['province'] = $info['province'];
                $data['language'] = $info['country'];
                $data['headimgurl'] = $info['headimgurl'];
                $data['subscribe_time'] = $info['subscribe_time'];
                $data['remark'] = $info['remark'];
                $data['unionid'] = isset($info['unionid']) ? $info['unionid'] : '';
                $this->model->table('wechat_user')->data($data)->where($where)->update();
            }
        }
    }

    /**
     * 取消關注
     *
     * @param string $openid            
     */
    public function unsubscribe($openid = '')
    {
        // 未關注
        $where['openid'] = $openid;
        $rs = $this->model->table('wechat_user')
            ->where($where)
            ->count();
        // 修改關注狀態
        if ($rs > 0) {
            $data['subscribe'] = 0;
            $this->model->table('wechat_user')
                ->data($data)
                ->where($where)
                ->update();
        }
    }

    /**
     * 被動關注,訊息回覆
     *
     * @param string $type            
     * @param string $return            
     */
    private function msg_reply($type, $return = 0)
    {
        $replyInfo = $this->model->table('wechat_reply')
            ->field('content, media_id')
            ->where('type = "' . $type . '" and wechat_id = ' . $this->wechat_id)
            ->find();
        if (! empty($replyInfo)) {
            if (! empty($replyInfo['media_id'])) {
                $replyInfo['media'] = $this->model->table('wechat_media')
                    ->field('title, content, file, type, file_name')
                    ->where('id = ' . $replyInfo['media_id'])
                    ->find();
                if ($replyInfo['media']['type'] == 'news') {
                    $replyInfo['media']['type'] = 'image';
                }
                // 上傳多媒體檔案
                $rs = $this->weObj->uploadMedia(array(
                    'media' => '@' . ROOT_PATH . $replyInfo['media']['file']
                ), $replyInfo['media']['type']);
                
                // 回覆資料重組
                if ($rs['type'] == 'image' || $rs['type'] == 'voice') {
                    $replyData = array(
                        'ToUserName' => $this->weObj->getRev()->getRevFrom(),
                        'FromUserName' => $this->weObj->getRev()->getRevTo(),
                        'CreateTime' => time(),
                        'MsgType' => $rs['type'],
                        ucfirst($rs['type']) => array(
                            'MediaId' => $rs['media_id']
                        )
                    );
                } elseif ('video' == $rs['type']) {
                    $replyData = array(
                        'ToUserName' => $this->weObj->getRev()->getRevFrom(),
                        'FromUserName' => $this->weObj->getRev()->getRevTo(),
                        'CreateTime' => time(),
                        'MsgType' => $rs['type'],
                        ucfirst($rs['type']) => array(
                            'MediaId' => $rs['media_id'],
                            'Title' => $replyInfo['media']['title'],
                            'Description' => strip_tags($replyInfo['media']['content'])
                        )
                    );
                }
                $this->weObj->reply($replyData);
                //記錄使用者操作資訊
                $this->record_msg($this->weObj->getRev()->getRevTo(), '圖文資訊', 1);
            } else {
                // 文本回復
                $replyInfo['content'] = html_out($replyInfo['content']);
                if($replyInfo['content']){
                    $this->weObj->text($replyInfo['content'])->reply();
                    //記錄使用者操作資訊
                    $this->record_msg($this->weObj->getRev()->getRevTo(), $replyInfo['content'], 1);
                }
            }
        }
    }

    /**
     * 關鍵詞回覆
     *
     * @param string $keywords            
     * @return boolean
     */
    private function keywords_reply($keywords)
    {
        $endrs = false;
        $sql = 'SELECT r.content, r.media_id, r.reply_type FROM ' . $this->model->pre . 'wechat_reply r LEFT JOIN ' . $this->model->pre . 'wechat_rule_keywords k ON r.id = k.rid WHERE k.rule_keywords = "' . $keywords . '" and r.wechat_id = ' . $this->wechat_id . ' order by r.add_time desc LIMIT 1';
        $result = $this->model->query($sql);
        if (! empty($result)) {
            // 素材回覆
            if (! empty($result[0]['media_id'])) {
                $mediaInfo = $this->model->table('wechat_media')
                    ->field('id, title, content, digest, file, type, file_name, article_id, link')
                    ->where('id = ' . $result[0]['media_id'])
                    ->find();
                
                // 回覆資料重組
                if ($result[0]['reply_type'] == 'image' || $result[0]['reply_type'] == 'voice') {
                    // 上傳多媒體檔案
                    $rs = $this->weObj->uploadMedia(array(
                        'media' => '@' . ROOT_PATH . $mediaInfo['file']
                    ), $result[0]['reply_type']);
                    
                    $replyData = array(
                        'ToUserName' => $this->weObj->getRev()->getRevFrom(),
                        'FromUserName' => $this->weObj->getRev()->getRevTo(),
                        'CreateTime' => time(),
                        'MsgType' => $rs['type'],
                        ucfirst($rs['type']) => array(
                            'MediaId' => $rs['media_id']
                        )
                    );
                    // 回覆
                    $this->weObj->reply($replyData);
                    $endrs = true;
                } elseif ('video' == $result[0]['reply_type']) {
                    // 上傳多媒體檔案
                    $rs = $this->weObj->uploadMedia(array(
                        'media' => '@' . ROOT_PATH . $mediaInfo['file']
                    ), $result[0]['reply_type']);
                    
                    $replyData = array(
                        'ToUserName' => $this->weObj->getRev()->getRevFrom(),
                        'FromUserName' => $this->weObj->getRev()->getRevTo(),
                        'CreateTime' => time(),
                        'MsgType' => $rs['type'],
                        ucfirst($rs['type']) => array(
                            'MediaId' => $rs['media_id'],
                            'Title' => $replyInfo['media']['title'],
                            'Description' => strip_tags($replyInfo['media']['content'])
                        )
                    );
                    // 回覆
                    $this->weObj->reply($replyData);
                    $endrs = true;
                } elseif ('news' == $result[0]['reply_type']) {
                    // 圖文素材
                    $articles = array();
                    if (! empty($mediaInfo['article_id'])) {
                        $artids = explode(',', $mediaInfo['article_id']);
                        foreach ($artids as $key => $val) {
                            $artinfo = $this->model->table('wechat_media')
                                ->field('id, title, digest, file, content, link')
                                ->where('id = ' . $val)
                                ->find();
                            //$artinfo['content'] = strip_tags(html_out($artinfo['content']));
                            $articles[$key]['Title'] = $artinfo['title'];
                            $articles[$key]['Description'] = $artinfo['digest'];
                            $articles[$key]['PicUrl'] = __URL__ . '/' . $artinfo['file'];
                            $articles[$key]['Url'] = empty($artinfo['link']) ? __HOST__ . url('article/wechat_news_info', array('id'=>$artinfo['id'])) : strip_tags(html_out($artinfo['link']));
                        }
                    } else {
                        $articles[0]['Title'] = $mediaInfo['title'];
                        //$articles[0]['Description'] = strip_tags(html_out($mediaInfo['content']));
                        $articles[0]['Description'] = $mediaInfo['digest'];
                        $articles[0]['PicUrl'] = __URL__ . '/' . $mediaInfo['file'];
                        $articles[0]['Url'] = empty($mediaInfo['link']) ? __HOST__ . url('article/wechat_news_info', array('id'=>$mediaInfo['id'])) : strip_tags(html_out($mediaInfo['link']));
                    }
                    // 回覆
                    $this->weObj->news($articles)->reply();
                    //記錄使用者操作資訊
                    $this->record_msg($this->weObj->getRev()->getRevTo(), '圖文資訊', 1);
                    $endrs = true;
                }
            } else {
                // 文本回復
                $result[0]['content'] = html_out($result[0]['content']);
                $this->weObj->text($result[0]['content'])->reply();
                //記錄使用者操作資訊
                $this->record_msg($this->weObj->getRev()->getRevTo(), $result[0]['content'], 1);
                $endrs = true;
            }
        }
        return $endrs;
    }

    /**
     * 功能變數查詢
     *
     * @param unknown $tousername            
     * @param unknown $fromusername            
     * @param unknown $keywords            
     * @return boolean
     */
    public function get_function($fromusername, $keywords)
    {
        $return = false;
        $rs = $this->model->table('wechat_extend')
            ->field('name, command, config')
            ->where('keywords like "%' . $keywords . '%" and enable = 1 and wechat_id = ' . $this->wechat_id)
            ->order('id asc')
            ->find();
        $file = ROOT_PATH . 'plugins/wechat/' . $rs['command'] . '/' . $rs['command'] . '.class.php';
        if (file_exists($file)) {
            require_once ($file);
            $wechat = new $rs['command']();
            $data = $wechat->show($fromusername, $rs);
            if (! empty($data)) {
                // 資料回覆型別
                if ($data['type'] == 'text') {
                    $this->weObj->text($data['content'])->reply();
                    //記錄使用者操作資訊
                    $this->record_msg($fromusername, $data['content'], 1);
                } elseif ($data['type'] == 'news') {
                    $this->weObj->news($data['content'])->reply();
                    //記錄使用者操作資訊
                    $this->record_msg($fromusername, '圖文訊息', 1);
                }
                $return = true;
            }
        }
        return $return;
    }

    /**
     * 商品推薦查詢
     *
     * @param unknown $tousername            
     * @param unknown $fromusername            
     * @param unknown $keywords            
     * @return boolean
     */
    public function recommend_goods($fromusername, $keywords)
    {
        $return = false;
        $rs = $this->model->table('wechat_extend')
            ->field('name, keywords, command, config')
            ->where('command = "recommend" and enable = 1 and wechat_id = ' . $this->wechat_id)
            ->order('id asc')
            ->find();

        $file = ROOT_PATH . 'plugins/wechat/' . $rs['command'] . '/' . $rs['command'] . '.class.php';
        if (file_exists($file)) {
            require_once ($file);
            $wechat = new $rs['command']();
            $rs['user_keywords'] = $keywords;
            $data = $wechat->show($fromusername, $rs);
            if (! empty($data)) {
                // 資料回覆型別
                if ($data['type'] == 'text') {
                    $this->weObj->text($data['content'])->reply();
                    //記錄使用者操作資訊
                    $this->record_msg($fromusername, $data['content'], 1);
                } elseif ($data['type'] == 'news') {
                    $this->weObj->news($data['content'])->reply();
                    //記錄使用者操作資訊
                    $this->record_msg($fromusername, '圖文訊息', 1);
                }
                $return = true;
            }
        }
        return $return;
    }

    /**
     * 主動傳送資訊
     *
     * @param unknown $tousername            
     * @param unknown $fromusername            
     * @param unknown $keywords            
     * @param unknown $weObj            
     * @param unknown $return            
     * @return boolean
     */
    public function send_message($fromusername, $keywords, $weObj, $return = 0)
    {
        $result = false;
        $rs = $this->model->table('wechat_extend')
            ->field('name, command, config')
            ->where('keywords like "%' . $keywords . '%" and enable = 1 and wechat_id = ' . $this->wechat_id)
            ->order('id asc')
            ->find();
        $file = ROOT_PATH . 'plugins/wechat/' . $rs['command'] . '/' . $rs['command'] . '.class.php';
        if (file_exists($file)) {
            require_once ($file);
            $wechat = new $rs['command']();
            $data = $wechat->show($fromusername, $rs);
            if (! empty($data)) {
                if ($return) {
                    $result = $data;
                } else {
                    $weObj->sendCustomMessage($data['content']);
                    $result = true;
                }
            }
        }
        return $result;
    }

    /**
     * 多客服
     *
     * @param unknown $fromusername            
     * @param unknown $keywords            
     */
    public function customer_service($fromusername, $keywords)
    {
        /*$kfevent = $this->weObj->getRevKFClose();
        logResult(var_export($kfevent, true));*/
        $result = false;
        //是否超時
        $timeout = false;
        //查詢使用者
        $uid = $this->model->table('wechat_user')->field('uid')->where(array('openid'=>$fromusername))->getOne();
        if($uid){
            $time_list = $this->model->table('wechat_custom_message')->field('send_time')->where(array('uid'=>$uid))->order('send_time desc')->limit(2)->select();
            if($time_list[0]['send_time'] - $time_list[1]['send_time'] > 3600 * 2){
                $timeout = true;
            }

        }
        
        // 是否處在多客服流程
        $kefu = $this->model->table('wechat_user')
            ->field('openid')
            ->where('openid = "' . $fromusername . '"')
            ->getOne();
        if($kefu){
            if ($keywords == 'kefu') {
                $rs = $this->model->table('wechat_extend')
                    ->field('config')
                    ->where('command = "kefu" and enable = 1 and wechat_id = ' . $this->wechat_id)
                    ->getOne();
                if (! empty($rs)) {
                    $config = unserialize($rs);
                    $msg = array(
                        'touser' => $fromusername,
                        'msgtype' => 'text',
                        'text' => array(
                            'content' => '歡迎進入多客服系統'
                        )
                    );
                    $this->weObj->sendCustomMessage($msg);
                    //記錄使用者操作資訊
                    $this->record_msg($fromusername, $msg['text']['content'], 1);

                    // 線上客服列表
                    $online_list = $this->weObj->getCustomServiceOnlineKFlist();
                    if ($online_list['kf_online_list']) {
                        foreach ($online_list['kf_online_list'] as $key => $val) {
                            if ($config['customer'] == $val['kf_account'] && $val['status'] > 0 && $val['accepted_case'] < $val['auto_accept']) {
                                $customer = $config['customer'];
                            } else {
                                $customer = '';
                            }
                        }
                    }
                    // 轉發客服訊息
                    $this->weObj->transfer_customer_service($customer)->reply();
                    $result = true;
                }
            } 
        }
        
        return $result;
    }

    /**
     * 獲取使用者暱稱,頭像
     *
     * @param unknown $user_id            
     * @return multitype:
     */
    static function get_avatar($user_id)
    {
        $u_row = model('Base')->model->table('wechat_user')
            ->field('nickname, headimgurl')
            ->where('ect_uid = ' . $user_id)
            ->find();
        if (empty($u_row)) {
            $u_row = array();
        }
        return $u_row;
    }

    public static function snsapi_base(){
        if(is_wechat_browser() && ($_SESSION['user_id'] === 0 || empty($_SESSION['openid']))){
            $_SESSION['openid'] = isset($_COOKIE['openid']) ? addslashes($_COOKIE['openid']) : '';
            $wxinfo = model('Base')->model->table('wechat')->field('token, appid, appsecret, status')->find();
            if($wxinfo['status']){
                self::snsapi_userinfo();
            }else{
                $config = model('Base')->model->table('wechat')->field('token, appid, appsecret, status')->find();
                if($config['status']){
                    $obj = new Wechat($config);
                    // 用code換token
                    if(isset($_GET['code']) && $_GET['state'] == 'repeat'){
                        $token = $obj->getOauthAccessToken();
                        $_SESSION['openid'] = $token['openid'];
                        setcookie('openid', $token['openid'], gmtime() + 86400 * 7);
                    }
                    // 生成請求連結
                    if (! empty($wxinfo['oauth_redirecturi'])) {
                        $callback = rtrim($wxinfo['oauth_redirecturi'], '/')  .'/'. $_SERVER['REQUEST_URI'];
                    }
                    if (! isset($callback)) {
                        $callback = __HOST__ . $_SERVER['REQUEST_URI'];
                    }
                    $obj->getOauthRedirect($callback, 'repeat', 'snsapi_base');
                }
            }
        }
    }

    /**
     * 跳轉到第三方登入
     */
    public static function snsapi_userinfo(){
        if(is_wechat_browser() && ($_SESSION['user_id'] === 0 || empty($_SESSION['openid'])) && ACTION_NAME != 'third_login'){
            $wxinfo   = model('Base')->model->table('wechat')->field('token, appid, appsecret, status')->find();
            if(!$wxinfo['status']){return false;}
            $url = url('user/third_login', array('type'=>'weixin'));
            if (! empty($wxinfo['oauth_redirecturi'])) {
                $_SESSION['redirect_url'] = rtrim($wxinfo['oauth_redirecturi'], '/')  .'/'. $_SERVER['REQUEST_URI'];
            }
            if (! isset($_SESSION['redirect_url'])) {
                $_SESSION['redirect_url'] = __HOST__ . $_SERVER['REQUEST_URI'];
            }
            header("Location: ".$url);
            exit;
        }
    }
    
    /**
     * 記錄使用者操作資訊
     */
     public function record_msg($fromusername, $keywords, $iswechat = 0){
        $uid = $this->model->table('wechat_user')->field('uid')->where(array('openid'=>$fromusername))->getOne();
        if($uid){
            $data['uid'] = $uid;
            $data['msg'] = $keywords;
            $data['send_time'] = time();
            //是公眾號回覆
            if($iswechat){
                $data['iswechat'] = 1;
            }
            $this->model->table('wechat_custom_message')
                ->data($data)
                ->insert();
        }
     }

    /**
     * 檢查是否是微信瀏覽器訪問
     */
    static function is_wechat_browser()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 外掛頁面顯示方法
     *
     * @param string $plugin            
     */
    public function plugin_show()
    {
        $plugin = I('get.name');
        $file = ADDONS_PATH . 'wechat/' . $plugin . '/' . $plugin . '.class.php';
        if (file_exists($file)) {
            include_once ($file);
            $wechat = new $plugin();
            $wechat->html_show();
        }
    }

    /**
     * 外掛處理方法
     *
     * @param string $plugin            
     */
    public function plugin_action()
    {
        $plugin = I('get.name');
        $file = ADDONS_PATH . 'wechat/' . $plugin . '/' . $plugin . '.class.php';
        if (file_exists($file)) {
            include_once ($file);
            $wechat = new $plugin();
            $wechat->action();
        }
    }

    /**
     * 獲取公眾號配置
     *
     * @param string $orgid            
     * @return array
     */
    private function get_config($orgid)
    {
        $config = $this->model->table('wechat')
            ->field('id, token, appid, appsecret')
            ->where('orgid = "' . $orgid . '" and status = 1')
            ->find();
        if (empty($config)) {
            $config = array();
        }
        return $config;
    }

    /**
     * 獲取access_token的介面
     * @return [type] [description]
     */
    public function check_auth(){
        $appid = I('get.appid');
        $appsecret = I('get.appsecret');
        if(empty($appid) || empty($appsecret)){
            echo json_encode(array('errmsg'=>'資訊不完整,請提供完整資訊', 'errcode'=>1));   
            exit;
        }
        $config = $this->model->table('wechat')
            ->field('token, appid, appsecret')
            ->where('appid = "' . $appid . '" and appsecret = "'.$appsecret.'" and status = 1')
            ->find();
        if(empty($config)){
            echo json_encode(array('errmsg'=>'資訊錯誤,請檢查提供的資訊', 'errcode'=>1));
            exit;   
        }

        $obj = new Wechat($config);
        $access_token = $obj->checkAuth();
        if($access_token){
          echo json_encode(array('access_token'=>$access_token, 'errcode'=>0));
          exit; 
        }
        else{
          echo json_encode(array('errmsg'=>$obj->errmsg, 'errcode'=>$obj->errcode));    
          exit;
        }
    }

    /**
     * 推薦分成二維碼
     * @param  string  $user_name [description]
     * @param  integer $user_id   [description]
     * @param  integer $time      [description]
     * @param  string  $fun       [description]
     * @return [type]             [description]
     */
    static function rec_qrcode($user_name = '', $user_id = 0, $expire_seconds = 0, $fun = '', $force = false){
        if(empty($user_id)){
            return false;
        }
        // 預設公眾號資訊
        $wxinfo = model('Base')->model->table('wechat')->field('id, token, appid, appsecret, oauth_redirecturi, type, oauth_status')->where('default_wx = 1 and status = 1')->find();

        if (! empty($wxinfo) && $wxinfo['type'] == 2) {
            $config['token'] = $wxinfo['token'];
            $config['appid'] = $wxinfo['appid'];
            $config['appsecret'] = $wxinfo['appsecret'];
            // 微信通驗證
            $weObj = new Wechat($config);
            if($force){
                $weObj->clearCache();
                model('Base')->model->table('wechat_qrcode')->where(array('scene_id'=>$user_id, 'wechat_id'=>$wxinfo['id']))->delete();
            }

            $qrcode = model('Base')->model->table('wechat_qrcode')->field('id, scene_id, type, expire_seconds, qrcode_url')->where(array('scene_id'=>$user_id, 'wechat_id'=>$wxinfo['id']))->find();
            if($qrcode['id'] && !empty($qrcode['qrcode_url'])){

                return $qrcode['qrcode_url'];
            }
            elseif($qrcode['id'] && empty($qrcode['qrcode_url'])){
                $ticket = $weObj->getQRCode((int)$qrcode['scene_id'], $qrcode['type'], $qrcode['expire_seconds']);
                if (empty($ticket)) {
                    //$weObj->errCode, $weObj->errMsg
                    return false;
                }
                $data['ticket'] = $ticket['ticket'];
                $data['expire_seconds'] = $ticket['expire_seconds'];
                $data['endtime'] = time() + $ticket['expire_seconds'];
                // 二維碼地址
                $data['qrcode_url'] = $weObj->getQRUrl($ticket['ticket']);
                M()->table('wechat_qrcode')->data($data)->where(array('id'=>$qrcode['id']))->update();

                return $data['qrcode_url'];
            }
            else{
                $data['function'] = $fun;
                $data['scene_id'] = $user_id;
                $data['username'] = $user_name;
                $data['type'] = empty($expire_seconds) ? 1 : 0;
                $data['wechat_id'] = $wxinfo['id'];
                $data['status'] = 1;
                //生成二維碼
                $ticket = $weObj->getQRCode((int)$data['scene_id'], $data['type'], $expire_seconds);
                if (empty($ticket)) {
                    //$weObj->errCode, $weObj->errMsg
                    return false;
                }
                $data['ticket'] = $ticket['ticket'];
                $data['expire_seconds'] = $ticket['expire_seconds'];
                $data['endtime'] = time() + $ticket['expire_seconds'];
                // 二維碼地址
                $data['qrcode_url'] = $weObj->getQRUrl($ticket['ticket']);

                M()->table('wechat_qrcode')->data($data)->insert();

                return $data['qrcode_url'];
            }
        }
        return false;
    }

    /**
     * 傳送訊息詳情,傳入openid
     */
    public function sendTemplateMessage($data){


        $info = model('Base')->model->table('wechat_template')
            ->field('switch,template_id')
            ->where('open_id="'.$data['open_id'].'"')
            ->find();
        if($info['switch'] == 1 && $info['template_id']){
            //傳送
            $format = array(
                'touser' => $data['openid'],
                'template_id' => $info['template_id'],
                'url' => $data['url'],
                'topcolor' => '#FF0000',
                "topcolor"=>"#FF0000",
                'data' =>array(
                    'first' => array(
                        'value' =>$data['first'],
                        'color'=>'#173177'
                    ),
                    'keyword1'=>array(
                        'value'=>$data['keyword1'],
                        'color'=>'#FF0000'
                    ),
                    'keyword2'=>array(
                        'value'=>$data['keyword2'],
                        'color'=>'#FF0000'
                    ),
                    'keyword3'=>array(
                        'value'=>$data['keyword3'],
                        'color'=>'#FF0000'
                    ),
                    'keyword4'=>array(
                        'value'=>$data['keyword4'],
                        'color'=>'#FF0000'
                    ),
                    'keyword5'=>array(
                        'value'=>$data['keyword5'],
                        'color'=>'#FF0000'
                    ),
                    'remark'=>array(
                        'value'=>$data['remark'],
                        'color'=>'#FF0000'
                    )
                )
            );

            // 預設公眾號資訊
            $wxinfo = model('Base')->model->table('wechat')->field('id, token, appid, appsecret, oauth_redirecturi, type, oauth_status')->where('default_wx = 1 and status = 1')->find();

            if (! empty($wxinfo) && $wxinfo['type'] == 2) {
                $config['token'] = $wxinfo['token'];
                $config['appid'] = $wxinfo['appid'];
                $config['appsecret'] = $wxinfo['appsecret'];
                // 微信通驗證
                $weObj = new Wechat($config);
                $weObj->sendTemplateMessage($format);
            }

        }
    }
}