PostInquiryForward.php 13.3 KB
<?php
/**
 * Created by PhpStorm.
 * User: akun
 * Date: 2025/02/26
 * Time: 10:14
 */

namespace App\Console\Commands\Inquiry;

use App\Models\Inquiry\InquiryInfo;
use App\Models\Inquiry\InquiryProject;
use App\Models\Inquiry\InquiryRelayDetail;
use App\Models\Inquiry\InquiryRelayDetailLog;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/**
 * Class postInquiry
 * @package App\Console\Commands\Inquiry
 */
class PostInquiryForward extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'post_inquiry_forward';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '执行询盘请求';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 芯片网站
     * @var array
     */
    protected $xp_websites = [
        'www.shinecomponents.com',
        'www.hk-allchips.com',
        'www.xinjiada-ic.com',
        'www.sic-components.com',
        'www.chip1-vip.com',
        'www.flash-turtle.com',
        'www.xinteerchip.com',
        'www.conevoelec.com'
    ];

    /**
     * 5.0询盘转发到自己站点的网站
     * @var array
     */
    protected $self_websites = [205570, 64532, 150535, 292114, 124579, 237114, 194809, 278184, 166223, 366238, 277923, 297045, 309218, 75191, 57616];


    public function handle()
    {
        while (true) {
            $list = InquiryRelayDetailLog::where('status', InquiryRelayDetailLog::STATUS_INIT)->where('start_at', '<=', date('Y-m-d H:i:s'))->orderBy('id', 'asc')->limit(100)->get();
            if (!$list->count()) {
                sleep(1);
            }
            // 询盘数据入库
            foreach ($list as $key => $val) {
                //加个锁 避免重复执行
                $lockKey = 'inquiry_relay_detail_log_lock_' . $val->id;
                if (!Redis::setnx($lockKey, 1)) {
                    continue;
                }
                Redis::expire($lockKey, 60);

                $log = InquiryRelayDetailLog::find($val->id);
                if ($log->status != InquiryRelayDetailLog::STATUS_INIT) {
                    continue;
                }

                $this->output('开始执行' . $val->id);
                try {
                    $detail = InquiryRelayDetail::find($val['detail_id']);

                    //防止 程序中断 启动时 同一时间一下就发了
                    $last_log = InquiryRelayDetailLog::where('detail_id', $val['detail_id'])->where('id', '<', $val['id'])->orderBy('id', 'desc')->first();
                    //不是第一个 或者 上一个处理失败了  直接处理
                    if (!empty($last_log)) {
                        //上一个还没有处理 直接跳过
                        if ($last_log->status == InquiryRelayDetailLog::STATUS_INIT) {
                            continue;
                        }
                        //上一个处理完成
                        if ($last_log->status == InquiryRelayDetailLog::STATUS_SUCCESS) {
                            //上次处理时间间隔达到没
                            $interval = strtotime($val->start_at) - strtotime($last_log->start_at);
                            if (time() - strtotime($last_log->updated_at) < $interval) {
                                continue;
                            }
                        }
                    }

                    if ($val['type'] == 1) {
                        $this->visit($detail, $val);
                    } else {
                        $res = $this->inquiry($detail, $val);

                        //转发详情
                        $detail->status = $res ? InquiryRelayDetail::STATUS_SEND : InquiryRelayDetail::STATUS_FAIL;
                        $detail->save();
                        //转发询盘
                        if ($res) {
                            $form = InquiryInfo::find($detail['form_id']);
                            $form->success = $form->success + 1;
                            $form->save();
                            Log::channel('inquiry_forward')->info('询盘成功:', [$detail['form_id'], $val->id, getmypid()]);
                        }
                    }
                } catch (\Exception $e) {
                    Log::channel('inquiry_forward')->error('post_inquiry_forward handle error', [$e->getMessage(), $e->getFile(), $e->getLine()]);

                    $val->status = InquiryRelayDetailLog::STATUS_FAIL;
                    $val->remark = mb_substr($e->getMessage(), 0, 200);
                    $val->save();
                }
            }
        }
    }

    public function visit(InquiryRelayDetail $detail, InquiryRelayDetailLog $log)
    {
        $website = 'https://' . $detail['website'] . '/';
        if ($detail['is_v6']) {
            $data = [
                'ip' => $detail['ip'],
                'url' => $log['url'],
                'device_port' => $detail['device_port'],
                'referrer_url' => $detail['referrer'],
                'user_agent' => $detail['user_agent'],
            ];
            $url = $website . 'api/traffic_visit/';
            $res = Http::withoutVerifying()->timeout(30)->post($url, $data)->json();
            if (empty($res['status']) || $res['status'] != 200) {
                $log->status = InquiryRelayDetailLog::STATUS_FAIL;
                $log->remark = mb_substr($res['message'] ?? '', 0, 200);
                $log->save();

                Log::channel('inquiry_forward')->error('post_inquiry_forward visit error', [$res, $url, $data]);
                return false;
            }
        } else {
            //v4 v5分离项目 往测试链接推
            $project_info = InquiryProject::select(['is_split', 'test_domain'])->where('domain', 'like', '%' . $detail['website'] . '%')->first();
            if (!$project_info) {
                $log->status = InquiryRelayDetailLog::STATUS_FAIL;
                $log->remark = '获取分离项目测试域名失败';
                $log->save();

                return false;
            }

            if ($project_info['is_split'] == 1) {
                $website = $project_info['test_domain'];
            }

            $data = [
                'action' => 'stats_init',
                'assort' => 0,
                'referrer' => $detail['referrer'],
                'currweb' => $log['url'],
                'user_agent' => $detail['user_agent'],
                "ip" => $detail['ip'],
            ];
            $url = $website . 'wp-admin/admin-ajax.php';
            $res = Http::withoutVerifying()->timeout(30)->get($url, $data);
            $status = $res->status();
            if ($status != 200) {
                $log->status = InquiryRelayDetailLog::STATUS_FAIL;
                $log->remark = mb_substr($res->body() ?? '', 0, 200);
                $log->save();

                Log::channel('inquiry_forward')->error('post_inquiry_forward v4|v5 visit error', [$res->body(), $url, $data]);
                return false;
            }
        }
        $log->status = InquiryRelayDetailLog::STATUS_SUCCESS;
        $log->save();
        return true;
    }

    public function inquiry(InquiryRelayDetail $detail, InquiryRelayDetailLog $log)
    {
        if (in_array($detail['website'], $this->xp_websites)) {
            // 芯片网站
            $res = $this->xpInquiry($detail, $log);
        } else {
            if ($detail['is_v6']) {
                // v6
                $res = $this->v6Inquiry($detail, $log);
            } else {
                // v5
                $res = $this->v5Inquiry($detail, $log);
            }
        }

        if (!$res) {
            return false;
        }

        $log->status = InquiryRelayDetailLog::STATUS_SUCCESS;
        $log->save();
        return true;
    }

    public function xpInquiry($detail, $log)
    {
        $data = [
            'refer' => $log['url'],
            'contact_name' => $detail['name'],
            'email' => $detail['email'],
            'tel' => $detail['phone'],
            'ip' => $detail['ip'],
            'remark' => $detail['message'],
            'submit_time' => date('Y-m-d H:i:s', time() + 20),
        ];
        $url = 'https://' . $detail['website'] . '/api/store/webmail?flag=opencart';
        $post_data = json_encode($data);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36');
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($post_data)));
        $curl_response = curl_exec($curl);
        curl_close($curl);

        $res = json_decode($curl_response, true);
        if (empty($res['code']) || $res['code'] != 200) {
            $log->status = InquiryRelayDetailLog::STATUS_FAIL;
            $log->remark = mb_substr($res['msg'] ?? '', 0, 200);
            $log->save();
            Log::channel('inquiry_forward')->error('post_inquiry_forward xp inquiry error', [$res, $url, $data]);
            return false;
        }

        return true;
    }

    public function v6Inquiry($detail, $log)
    {
        $website = 'https://' . $detail['website'] . '/';
        $data = [
            'name' => $detail['name'],
            'phone' => $detail['phone'],
            'message' => $detail['message'],
            'submit_ip' => $detail['ip'],
            'refer' => $log['url'],
        ];
        if ($detail['email']) {
            $data['email'] = $detail['email'];
        } else {
            $data['__amp_source_origin'] = trim($website, '/');
        }
        $url = $website . 'api/inquiryQd?source=5';
        $res = Http::withoutVerifying()->timeout(60)->withHeaders(['User-Agent' => $detail['user_agent']])->post($url, $data)->json();
        if (empty($res['code']) || $res['code'] != 200) {
            $log->status = InquiryRelayDetailLog::STATUS_FAIL;
            $log->remark = mb_substr($res['message'] ?? '', 0, 200);
            $log->save();
            Log::channel('inquiry_forward')->error('post_inquiry_forward v6 inquiry error', [$res, $url, $data]);
            return false;
        }

        return true;
    }

    public function v5Inquiry($detail, $log)
    {
        $project_id = InquiryProject::where('version', '<', 6)->where('domain', 'like', '%' . $detail['website'] . '%')->value('primary_id') ?? 0;
        if (in_array($project_id, $this->self_websites)) {
            //发送到自己站点项目
            $data = [
                'Name' => $detail['name'],
                'Phone' => $detail['phone'],
                'Message' => $detail['message'],
                'Email' => $detail['email'],
                'submit_ip' => $detail['ip'],
                'refer' => $log['url'],
                'submit_time' => date('Y-m-d H:i:s', time() + 60)
            ];
            $url = 'https://' . $detail['website'] . '/wp-admin/admin-ajax.php?action=live_remort_receive';
            $res = Http::withoutVerifying()->timeout(60)->withHeaders(['User-Agent' => $detail['user_agent']])->post($url, $data);
            $status = $res->status();
            if ($status != 200) {
                $log->status = InquiryRelayDetailLog::STATUS_FAIL;
                $log->remark = mb_substr($res->body() ?? '', 0, 200);
                $log->save();

                Log::channel('inquiry_forward')->error('post_inquiry_forward v4|v5 inquiry error', [$res->body(), $url, $data]);
                return false;
            }
        } else {
            $data = [
                'name' => $detail['name'],
                'phone' => $detail['phone'],
                'message' => $detail['message'],
                'email' => $detail['email'],
                'ip' => $detail['ip'],
                'token' => md5($log['url'] . $detail['name'] . $detail['ip'] . date("Y-m-d")),
                'refer' => $log['url'],
                'submit_time' => date('Y-m-d H:i:s'),
                'source' => 5,
            ];
            $url = 'https://form.globalso.com/api/external-interface/add/fa043f9cbec6b38f';
            $res = Http::withoutVerifying()->timeout(60)->withHeaders(['User-Agent' => $detail['user_agent']])->post($url, $data)->json();
            if (empty($res['status']) || $res['status'] != 200) {
                $log->status = InquiryRelayDetailLog::STATUS_FAIL;
                $log->remark = mb_substr($res['message'] ?? '', 0, 200);
                $log->save();

                Log::channel('inquiry_forward')->error('post_inquiry_forward v4|v5 inquiry error', [$res, $url, $data]);
                return false;
            }
        }

        return true;
    }


    public function output($message)
    {
        echo date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL;
    }
}