<?php
namespace DtApp\ThinkLibrary\service;
use DtApp\ThinkLibrary\Service;
use DtApp\ThinkLibrary\service\curl\HttpService;
use think\App;
use think\exception\HttpException;
class KaShAngWl extends Service
{
private $api_url = 'http://www.kashangwl.com/api';
private $customer_id, $customer_key;
public function setCustomerId(string $customer_id): self
{
$this->customer_id = $customer_id;
return $this;
}
public function setCustomerKey(string $customer_key): self
{
$this->customer_key = $customer_key;
return $this;
}
private $method = '';
public function setMethod($method): self
{
$this->method = "{$this->api_url}/$method";
return $this;
}
private $param;
public function param($param): self
{
$this->param = $param;
return $this;
}
private $output;
private $time;
public function __construct(App $app)
{
$this->time = time();
parent::__construct($app);
}
public function toArray()
{
if (!extension_loaded("curl")) {
throw new HttpException(404, '请开启curl模块!');
}
$this->http();
if (is_array($this->output)) {
return $this->output;
}
if (is_object($this->output)) {
$this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE);
}
$this->output = json_decode($this->output, true);
return $this->output;
}
private function http(): void
{
$sign = $this->createSign();
$this->param['customer_id'] = $this->customer_id;
$this->param['timestamp'] = $this->time;
$this->param['sign'] = $sign;
$result = HttpService::instance()
->url($this->method)
->data($this->param)
->post()
->toArray();
$this->output = $result;
}
private function createSign(): string
{
$sign = $this->customer_key;
$this->param['customer_id'] = $this->customer_id;
$this->param['timestamp'] = $this->time;
ksort($this->param);
foreach ($this->param as $key => $val) {
if ($key !== '' && $val !== '') {
$sign .= $key . $val;
}
}
$sign = strtolower(md5($sign));
return $sign;
}
}