<?php
namespace wx;

use think\facade\Db;
use think\facade\Cache;
use think\Request;
use think\Session;

class wxMsg
{   
    //公众号接口
    public function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'cqaptivoms';
        $echostr = $_GET['echostr'];
        @file_put_contents('Public/checksing.html', '<br/>'.$signature.'-'.$timestamp.'-'.$nonce.'-'.$token, FILE_APPEND);
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        @file_put_contents('Public/checksing.html', '<br/>'.$tmpStr.'--'.$echostr, FILE_APPEND);
        if($signature){
            echo  $echostr;
        }else{
            return false;
        }
    }
    
    //微信消息推送
    public function send_msg($res){
        //获取access_token
        $access_token = $this->getAccessToken();
        //模板消息
        $temp = json_decode($res,true);
        $GIDs = Cache::get('GIDs');
        if(!$GIDs){
            $gzhOpenid = Db::name('admin_user_mobile')->where('gzhOpenid','<>',null)->lists();
            foreach ($gzhOpenid as $k => $v) {
                $GIDs[$v['user_id'].'-'.($v['user_type']>1?2:1)] = $v['gzhOpenid'];
            }
            Cache::set('GIDs', $GIDs, 3600);
        }
        if(is_array($temp['touser'])){
            foreach ($temp['touser'] as $k => $v) {
                if(isset($GIDs[$v.'-'.($temp['type']>1?2:1)])){
                    $template = array(
                        'touser'=>$GIDs[$v.'-'.($temp['type']>1?2:1)],  //用户openid
                        'template_id'=>$temp['template_id'], //在公众号下配置的模板id
                        'miniprogram'=>array(
                            'appid'=>'wx7e20ac89979b477a',
                            'pagepath'=>'pages/index/index'
                        ),
                        'topcolor'=>"#7B68EE",
                        'data'=>$temp['data'],
                    );
                    $msg = $this->curl_post($access_token,json_encode($template));
                    if($msg['errcode']!=0){
                        return $v.':'.$msg['errcode'].',';
                    }
                    
                }else{
                    return 'noopenid';
                }
            }
        }else{
            if(isset($GIDs[$temp['touser'].'-'.($temp['type']>1?2:1)])){
                $template = array(
                    'touser'=>$GIDs[$temp['touser'].'-'.($temp['type']>1?2:1)],  //用户openid
                    'template_id'=>$temp['template_id'], //在公众号下配置的模板id
                    'miniprogram'=>array(
                        'appid'=>'wx7e20ac89979b477a',
                        'pagepath'=>'pages/index/index'
                    ),
                    'topcolor'=>"#7B68EE",
                    'data'=>$temp['data'],
                );
                $msg = $this->curl_post($access_token,json_encode($template));
                if($msg['errcode']!=0){
                        return $temp['touser'].':'.$msg['errcode'].',';
                    }
            }else{
                return 'noopenid';
            }
        }
    }
    //微信消息推送
    public function send_msg_eid($res){
        //获取access_token
        $access_token = $this->getAccessToken();
        //模板消息
        $temp = json_decode($res,true);
        $GIDs = Cache::get('Gids_eid');
        if(!$GIDs){
            $gzhOpenid = Db::name('admin_user_mobile')->where('gzhOpenid','<>',null)->lists();
            foreach ($gzhOpenid as $k => $v) {
                $GIDs[$v['username']] = $v['gzhOpenid'];
            }
            Cache::set('Gids_eid', $GIDs, 120);
        }
        if(isset($GIDs[$temp['touser']])){
            $template = array(
                'touser'=>$GIDs[$temp['touser']],  //用户openid
                'template_id'=>$temp['template_id'], //在公众号下配置的模板id
                'miniprogram'=>array(
                    'appid'=>'wx7e20ac89979b477a',
                    'pagepath'=>'pages/index/index'
                ),
                'topcolor'=>"#7B68EE",
                'data'=>$temp['data'],
            );
            $msg = $this->curl_post($access_token,json_encode($template));
            return $msg['errcode'];
        }else{
            return 'noopenid';
        }
    }
    //获取access_token
    private function getAccessToken(){
        $access_token = Cache::get('access_token');
        if(!$access_token){
            $wx_token = Db::name('admin_base')->where('mid',5)->find();
            if($wx_token['content']==''||$wx_token['content']==null||time()>$wx_token['mark']-100){
                $data = array(
                    'grant_type'=> "client_credential",
                    "appid"=> 'wxc09a873c089683ae',
                    "secret"=> 'd0f123bf85cab46c1300d6a59325e788',
                    "force_refresh"=> false
                );
                $dataJson = json_encode($data);
                $json_token = $this->curl_get_stable_token("https://api.weixin.qq.com/cgi-bin/stable_token",$dataJson);
                $access_token1 = json_decode($json_token,true);
                // print_r($dataJson);die;
                $access_token = isset($access_token1['access_token'])?$access_token1['access_token']:'';
                Db::name('admin_base')->where('mid',5)->update(['content'=>$access_token,'mark'=>time()+$access_token1['expires_in']]);
                Cache::set('access_token', $access_token, 60);
            }else{
                $access_token = $wx_token['content'];
                $end_time = $wx_token['mark']+7100-time();
                Cache::set('access_token', $access_token, 60);
            }
        }
        return $access_token;
    }
    //模板消息发送CURL接口
    private function curl_post($access_token , $data = array()){
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $ch = curl_init($url);
        // 将头部文件的信息作为数据流输出 
        // curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_POST, true);           // post 请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    // post 传参
        // $headerArr = [                               // 设置头部信息 [get 方式一般不用]
        //     'Content-Type: application/json',
        //     'Content-Length: '.strlen($data)
        // ];
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output,true);
    }
    //获取Token的CURL接口
    private function curl_get_stable_token($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, true);           // post 请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    // post 传参
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    // 微信错误码说明
    public function get_wx_errmsg($code)
    {
        $err = [
            0 => '成功',
            40037 => '模板ID不正确',
            40036 => 'touser字段不正确或openid无效',
            43004 => '过期的access_token',
            40003 => '不合法的OpenID',
            48001 => '未授权模板消息权限',
            45015 => '超过发送频率限制',
        ];
        return isset($err[$code]) ? $err[$code] : '未知错误';
    }
}
