Events.php 8.2 KB
<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * wale
 * 主要是处理 onMessage onClose
 */

use think\Config;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WeMini\Newtmpl;
use Workerman\Lib\Timer;


class Events
{

    /**
     * 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次。
     * 可以在这里为每一个businessWorker进程做一些全局初始化工作,例如设置定时器,初始化redis等连接等。
     *
     * @param $businessWorker
     *
     * @throws Exception
     */
    public static function onWorkerStart($businessWorker)
    {
        echo 'WorkerStart id: ' . $businessWorker->id;

        $config = [
            'appid'      => 'wx670b02d7406045d1',
            'appsecret'  => '2c2aa784ee902248d7360dde74c8e299',
            'mch_id'     => '1577676721',
            'mch_key'    => 'MmXiXHO16b89tNx75t3T8rHTYMQBbn19',
            'notify_url' => 'https://wake.w.brotop.cn/api/order/notify',
            'course_sign_tmp' => 'yBH9F7IO75_fc7w4SDWIrmTyLHsPLZ5fOf2Z4jwY-Q4',
            'course_start_tmp' => 'Y24N0zGcKj2tEFOh1elMoy5j5ppRK8MSGGINyaX5gYc',
            'order_over_tmp' => '586FN0OLJ1DPZgwPwh7Ke2P4wewhm7l67awB77qrOi8',
        ];

        //订单到期
        $timer = 60*1;
        Timer::add($timer, function ($config){
            $config = config('weChat');
            error_log('order_over');
            $template = new Newtmpl($config);
            $order = new \app\admin\model\Order();
            $order = $order->where(['status'=>'success','end'=>['<',date('Y-m-d H:i:s'), 'notify'=> false]])->with('user')->select();
            $notice = new \app\admin\model\UserNotice();
            foreach ($order as $k){

                $order = new \app\admin\model\Order();
                $order->save(['status'=>'over','notify'=>true],['id'=>$k['id']]);

                $insert = [
                    'user_id'    => $k['id'],
                    'type'       => 'order_over',
                    'content_id' => $k['id'],
                    'time'       => date('Y-m-d H:i:s'),
                ];
                $notice->insert($insert);

                //小程序通知
                $data = [
                    'touser' => $k['user']['openid'],
                    'template_id' => $config['order_over_tmp'],
                    'form_id'=> $k['id'],
                    'page'=>'pages/classReserve/classReserve',
                    'data'=>[
                        "thing1" => ["value" => "维克猩球"],
                        "number2" => ["value" => "0"],
                        "name3" => ["value" => $k['user']['nickname']],
                    ],
                ];
                try {
                    $template->send($data);
                } catch (InvalidResponseException $e) {
                } catch (LocalCacheException $e) {

                }

            }
        });



        //开课提醒
        $timer = 60*1;
        Timer::add($timer, function ($config){
            $config = config('weChat');
            error_log('course_start');

            $template = new Newtmpl($config);

            $setting = new \app\admin\model\CourseSetting();
            $setting = $setting->where(['setting_key'=>'course_start'])->find();
            if(empty($setting)){
                $time = 3600;
            }else{
                $time =  $setting['setting_value']*3600;
            }

            $courseStore = new \app\admin\model\CourseStore();
            $courseStore = $courseStore->with(['store','course'])->where(['notify'=>false,'status'=>'confirmed','start' => ['<',date('Y-m-d H:i:s',time()+$time)] ])->select();
            $notice = new \app\admin\model\UserNotice();
            foreach ($courseStore as $k){
                $courseStore = new \app\admin\model\CourseStore();
                $courseStore->save(['notify'=>true],['id'=>$k['id']]);
                $sign = new \app\admin\model\CourseSign();
                $sign = $sign->with(['user','CourseStore'])->where(['course_store_id'=>$k['id']])->select();
                foreach ($sign as $v){

                    $insert = [
                        'user_id'    => $v['user_id'],
                        'type'       => 'course_start',
                        'content_id' => $v['id'],
                        'time'       => date('Y-m-d H:i:s'),
                    ];
                    $notice->insert($insert);

                    //小程序通知
                    $data = [
                        'touser' => $v['user']['openid'],
                        'template_id' => $config['course_start_tmp'],
                        'form_id'=> $v['id'],
                        'page'=>'pages/classReserve/classReserve',
                        'data'=>[
                            "thing2" => ["value" => $k['course']['name']],
                            "thing4" => ["value" => $k['store']['address']],
                            "date1" => ["value" => $v['CourseStore']['start']],
                            "name3" => ["value" => $v['user']['nickname']],
                            "thing5" => ["value" => "课程即将开始"],
                        ],
                    ];

                    try {
                        $template->send($data);
                    } catch (InvalidResponseException $e) {
                    } catch (LocalCacheException $e) {

                    }
                }
            }
        });


        //完成课程
        $timer = 60*1;
        Timer::add($timer, function (){

            error_log('course_over');
            $courseStore = new \app\admin\model\CourseStore();
            $courseStoreData = $courseStore->where(['status'=>'confirmed','end' => ['<',date('Y-m-d H:i:s',time())], 'is_end'=>false])->select();
            foreach ($courseStoreData as $k){
                $sign = new \app\admin\model\CourseSign();
                $sign_data = $sign->with('user')->where(['status'=>'publish','course_store_id'=>$k['id']])->select();
                foreach ($sign_data as $v){
                    $sign->save(['status'=>'finish','finish_time'=>date('Y-m-d H:i:s')],['id'=>$v['id']]);
                }
                $courseStore = new \app\admin\model\CourseStore();
                $courseStore->save(['is_end'=>true],['id'=>$k['id']]);
            }
        });




    }

    /**
     * 有消息时
     *
     * @param int   $client_id
     * @param mixed $message
     *
     * @return void
     */
    public static function onMessage($client_id, $message)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:" . json_encode($_SESSION) . " onMessage:" . $message . "\n";

        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if ($message_data) {

            //是否回传给自己
            $returnMe = empty($message_data['returnMe']) ? false : true;

            // 根据类型执行不同的业务
            switch ($message_data['type']) {
                // 客户端回应服务端的心跳
                case 'pong':
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 当客户端断开连接时
     *
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";

    }


}