mListenPort = $port; } private function handle_error($level, $message, $file, $line) { if($level == E_NOTICE) return; $trace = "handle_error: level={$level},msg={$message} file={$file},line={$line}\n"; $backtrace = debug_backtrace(); foreach ($backtrace as $item) { $trace .= "{$item['file']}\t{$item['line']}\t{$item['function']}\n"; } Log::record($trace,Log::ERR); } public function looper() { set_error_handler([$this, 'handle_error']); $fd = event\util::listen_block("0.0.0.0", $this->mListenPort); if ($fd === false) { Log::record("Cannot Listen on port = {$this->mListenPort}", Log::DEBUG); return false; } while (true) { Log::record("Waitting another connect...."); if (($client = socket_accept($fd)) !== false) { try { Log::record("Client {$client} has connected", Log::DEBUG); socket_set_option($client, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 8, 'usec' => 0]); $body = $this->read_order($client); if (!empty($body)) { Log::record("req:{$body}", Log::DEBUG); $resp = $this->relay_request($body); Log::record("resp={$resp}",Log::ERR); $resp = mb_convert_encoding($resp, 'GBK', 'UTF-8'); socket_write($client, $resp); Log::record("resp:{$resp}", Log::DEBUG); } else { Log::record("不合法的包", Log::DEBUG); } } catch (Exception $ex) { Log::record(__FUNCTION__ . " " . $ex->getMessage(),Log::ERR); } socket_close($client); } } socket_close($fd); } private function relay_request($body) { $url = BASE_SITE_URL . "/mobile/bridge_shr.php"; $headers = ['Content-Type: application/json']; $resp = http_post_data($url, $body, $headers); if ($resp === false) { Log::record("Net error.", Log::ERR); return $this->err_body($body); } else { return $resp; } } private function err_body($body) { $params = json_decode($body,true); //交易结果 0:未处理 1:充值成功 2:充值结果不确定 3:充值失败 $retCode = 3; $retDetail = "服务维护中....."; $result = [ 'action' => 'CZ', 'chargeId' => $params['chargeId'], 'retCode' => $retCode, 'retDetail' => $retDetail, 'retRsn' => $params['retRsn']]; $body = "{$params['chargeId']}{$retCode}{$params['retRsn']}" . WSDBridge::KEY; $sign = md5($body); $result['sign'] = $sign; return json_encode($result); } private function read_order($client) { $content = ''; $buf = socket_read($client, 1024); if ($buf === false) { $error = socket_strerror(socket_last_error($client)); Log::record("read_order err:{$error}", Log::ERR); return false; } else { $content .= $buf; } $content = mb_convert_encoding($content, 'UTF-8', 'GBK'); if ($this->isbody($content)) { return $content; } else { Log::record("err body = {$content}", Log::DEBUG); return false; } } private function isbody($content) { $ret = json_decode($content, true); return !empty($ret); } } $brider = new WSDBridge($port); $brider->looper();