add clear

This commit is contained in:
as2252258@163.com
2020-03-05 12:41:49 +08:00
parent 0a16cc14e4
commit 291e882069
47 changed files with 104 additions and 107 deletions
-499
View File
@@ -1,499 +0,0 @@
<?php
namespace common;
class Config
{
/**
* @var string
*
* 小程序ID
*/
private $appid = '';
/**
* @var string
*
* 商户号ID
*/
private $mch_id = '';
/**
* @var string
*
* 设备号
*/
private $device_info = 'WEB';
private $token;
private $encodingAesKey;
/**
* @var string
*
* 随机字符串
*/
private $nonce_str = '';
/**
* @var string
*
* 商品简单描述
*/
private $body = '好友默契Pk充值!';
/**
* @var string
*
* 商户订单号
*/
private $out_trade_no = "";
/**
* @var int
*
* 金额
*/
private $total_fee = 0;
/**
* @var string
*
* 终端IP
*/
private $spbill_create_ip = "";
/**
* @var string
*
* 异步回调地址
*/
private $notify_url = "";
/**
* @var string
*
* 交易类型
*/
private $trade_type = 'JSAPI';
/**
* @var string
*
* 签名方式
*/
private $sign_type = 'MD5';
/**
* @var string
*
* 商户接口地址
*/
private $mch_host = 'https://api.mch.weixin.qq.com';
/**
* @var string
*/
private $appsecret = '';
private $remote_addr = '127.0.0.1';
private $ssl_cert = '';
private $ssl_key = '';
/**
* @var string
*/
private $key = '';
private $access_token = '';
private $agent = '';
private $usrSwoole = false;
/**
* @return bool
*/
public function isUsrSwoole(): bool
{
return $this->usrSwoole;
}
/**
* @param bool $usrSwoole
* @return Config
*/
public function setUsrSwoole(bool $usrSwoole): Config
{
$this->usrSwoole = $usrSwoole;
return $this;
}
/**
* @return string
*/
public function getAgent(): string
{
return $this->agent;
}
/**
* @param string $agent
* @return Config
*/
public function setAgent(string $agent): Config
{
$this->agent = $agent;
return $this;
}
/**
* @return mixed
*/
public function getToken()
{
return $this->token;
}
/**
* @param mixed $token
* @return Config
*/
public function setToken($token)
{
$this->token = $token;
return $this;
}
/**
* @return mixed
*/
public function getEncodingAesKey()
{
return $this->encodingAesKey;
}
/**
* @param mixed $encodingAesKey
* @return Config
*/
public function setEncodingAesKey($encodingAesKey)
{
$this->encodingAesKey = $encodingAesKey;
return $this;
}
/**
* @return string
*/
public function getAccessToken(): string
{
return $this->access_token;
}
/**
* @param string $access_token
*/
public function setAccessToken(string $access_token)
{
$this->access_token = $access_token;
}
/**
* @param string $remote_addr
*/
public function setRemoteAddr(string $remote_addr)
{
$this->remote_addr = $remote_addr;
}
/**
* @param string $appid
*/
public function setAppid(string $appid)
{
$this->appid = $appid;
}
/**
* @param string $mch_id
*/
public function setMchId(string $mch_id)
{
$this->mch_id = $mch_id;
}
/**
* @param string $device_info
*/
public function setDeviceInfo(string $device_info)
{
$this->device_info = $device_info;
}
/**
* @param string $nonce_str
*/
public function setNonceStr(string $nonce_str)
{
$this->nonce_str = $nonce_str;
}
/**
* @param string $body
*/
public function setBody(string $body)
{
$this->body = $body;
}
/**
* @param string $out_trade_no
*/
public function setOutTradeNo(string $out_trade_no)
{
$this->out_trade_no = $out_trade_no;
}
/**
* @param int $total_fee
*/
public function setTotalFee(int $total_fee)
{
$this->total_fee = $total_fee;
}
/**
* @param string $spbill_create_ip
*/
public function setSpbillCreateIp(string $spbill_create_ip)
{
$this->spbill_create_ip = $spbill_create_ip;
}
/**
* @param string $notify_url
*/
public function setNotifyUrl(string $notify_url)
{
$this->notify_url = $notify_url;
}
/**
* @param string $trade_type
*/
public function setTradeType(string $trade_type)
{
$this->trade_type = $trade_type;
}
/**
* @param string $sign_type
*/
public function setSignType(string $sign_type)
{
$this->sign_type = $sign_type;
}
/**
* @param string $mch_host
*/
public function setMchHost(string $mch_host)
{
$this->mch_host = $mch_host;
}
/**
* @param string $appsecret
*/
public function setAppsecret(string $appsecret)
{
$this->appsecret = $appsecret;
}
/**
* @param string $ssl_cert
*/
public function setSslCert(string $ssl_cert)
{
$this->ssl_cert = $ssl_cert;
}
/**
* @param string $ssl_key
*/
public function setSslKey(string $ssl_key)
{
$this->ssl_key = $ssl_key;
}
/**
* @param string $key
*/
public function setKey(string $key)
{
$this->key = $key;
}
/**
* @return string
*/
public function getAppid(): string
{
return $this->appid;
}
/**
* @return string
*/
public function getMchId(): string
{
return $this->mch_id;
}
/**
* @return string
*/
public function getDeviceInfo(): string
{
return $this->device_info;
}
/**
* @return string
*/
public function getNonceStr(): string
{
return $this->nonce_str;
}
/**
* @return string
*/
public function getBody(): string
{
return $this->body;
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->out_trade_no;
}
/**
* @return int
*/
public function getTotalFee(): int
{
return $this->total_fee;
}
/**
* @return string
*/
public function getSpbillCreateIp(): string
{
return $this->spbill_create_ip;
}
/**
* @return string
*/
public function getNotifyUrl(): string
{
return $this->notify_url;
}
/**
* @return string
*/
public function getTradeType(): string
{
return $this->trade_type;
}
/**
* @return string
*/
public function getSignType(): string
{
return $this->sign_type;
}
/**
* @return string
*/
public function getMchHost(): string
{
return $this->mch_host;
}
/**
* @return string
*/
public function getAppsecret(): string
{
return $this->appsecret;
}
/**
* @return string
*/
public function getRemoteAddr(): string
{
return $this->remote_addr;
}
/**
* @return string
*/
public function getSslCert(): string
{
return $this->ssl_cert;
}
/**
* @return string
*/
public function getSslKey(): string
{
return $this->ssl_key;
}
/**
* @return string
*/
public function getKey(): string
{
return $this->key;
}
/**
* @param array $configs
* @return $this
*/
public function setConfigs(array $configs)
{
if (empty($configs)) {
return $this;
}
foreach ($configs as $key => $val) {
if (empty($val) || is_array($val)) {
continue;
}
if (!property_exists($this, $key)) {
continue;
}
$this->$key = $val;
}
return $this;
}
}
-99
View File
@@ -1,99 +0,0 @@
<?php
namespace common;
class Decode
{
private $sessionKey;
private $iv;
private $encryptedData;
private $appId;
private $OK = 0;
private $IllegalAesKey = -41001;
private $IllegalIv = -41002;
private $IllegalBuffer = -41003;
private $DecodeBase64Error = -41004;
/**
* @param mixed $sessionKey
* @return Decode
*/
public function setSessionKey($sessionKey)
{
$this->sessionKey = $sessionKey;
return $this;
}
/**
* @param mixed $iv
* @return Decode
*/
public function setIv($iv)
{
$this->iv = $iv;
return $this;
}
/**
* @param mixed $encryptedData
* @return Decode
*/
public function setEncryptedData($encryptedData)
{
$this->encryptedData = $encryptedData;
return $this;
}
/**
* @param mixed $appId
* @return Decode
*/
public function setAppId($appId)
{
$this->appId = $appId;
return $this;
}
/**
* @param $asArray
* @return array|mixed
* @throws \Exception
*/
public function decode($asArray)
{
if (strlen($this->sessionKey) != 24) {
throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey);
}
$aesKey = base64_decode($this->sessionKey);
if (strlen($this->iv) != 24) {
throw new \Exception('base64解密失败', $this->IllegalIv);
}
$aesIV = base64_decode($this->iv);
$aesCipher = base64_decode($this->encryptedData);
$result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV);
if ($result === false) {
throw new \Exception('aes 解密失败', $this->IllegalBuffer);
}
$dataObj = json_decode($result);
if ($dataObj->watermark->appid != $this->appId) {
throw new \Exception('aes 解密失败', $this->IllegalBuffer);
}
if ($asArray) {
return get_object_vars($dataObj);
}
return $dataObj;
}
}
-107
View File
@@ -1,107 +0,0 @@
<?php
namespace common;
class Help extends Miniprogarampage
{
/**
* @param array $data
* @return string
*/
public static function toXml(array $data)
{
$xml = "<xml>";
foreach ($data as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
/**
* @param $xml
* @return mixed
*/
public static function toArray($xml)
{
if (is_array($xml)) {
return $xml;
}
if (!is_null($json = json_decode($xml, TRUE))) {
return $json;
}
if (is_array($json)) {
return $json;
}
if (!static::isXml($xml)) {
return $xml;
}
$data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
if (is_array($data)) {
return $data;
}
return json_decode(json_encode($data), TRUE);
}
public static function isXml($body)
{
return preg_match('/^<[a-zA-Z_]+>(.*?)?<\/[a-zA-Z_]+>$/', $body);
}
/**
* @param int $length
* @return string
*
* 随机字符串
*/
public static function random($length = 20)
{
$res = [];
$str = 'abcdefghijklmnopqrstuvwxyz';
$str .= strtoupper($str) . '1234567890';
for ($i = 0; $i < $length; $i++) {
$rand = substr($str, rand(0, strlen($str) - 2), 1);
if (empty($rand)) {
$rand = substr($str, strlen($str) - 3, 1);
}
array_push($res, $rand);
}
return implode($res);
}
/**
* @param array $array
* @param $key
* @param $type
* @return string
*/
public static function sign(array $array, $key, $type)
{
ksort($array, SORT_ASC);
$string = [];
foreach ($array as $hashKey => $val) {
if (empty($val)) {
continue;
}
$string[] = $hashKey . '=' . $val;
}
$string[] = 'key=' . $key;
$string = implode('&', $string);
if ($type == 'MD5') {
return strtoupper(md5($string));
} else {
return hash('sha256', $string);
}
}
}
-780
View File
@@ -1,780 +0,0 @@
<?php
namespace common;
use Swoole\Coroutine\Http\Client as SClient;
use Swoole\Coroutine\System;
class HttpClient
{
private $host = 'api.weixin.qq.com';
private $header = [];
private $callback = null;
private $method = 'get';
private $url = '';
private $isSSL = false;
private $agent = '';
private $isFileStream = false;
private $errorCodeField = '';
private $errorMsgField = '';
private $use_swoole = false;
private $ssl_cert_file = '';
private $ssl_key_file = '';
private $port = 80;
private $_data = '';
const POST = 'post';
const GET = 'get';
const PUT = 'put';
const DELETE = 'delete';
const OPTIONS = 'option';
/**
* HttpClient constructor.
*/
private function __construct()
{
}
public function setData($data)
{
$this->_data = $data;
}
/**
* @return string
*/
public function getSslCertFile(): string
{
return $this->ssl_cert_file;
}
/**
* @param string $ssl_cert_file
*/
public function setSslCertFile(string $ssl_cert_file)
{
$this->ssl_cert_file = $ssl_cert_file;
}
/**
* @return string
*/
public function getSslKeyFile(): string
{
return $this->ssl_key_file;
}
/**
* @param string $ssl_key_file
*/
public function setSslKeyFile(string $ssl_key_file)
{
$this->ssl_key_file = $ssl_key_file;
}
/**
*/
public static function NewRequest()
{
static $client = null;
if (!($client instanceof HttpClient)) {
$client = new HttpClient();
}
return $client;
}
/**
* @param string $name
* @return $this
*/
public function setErrorField(string $name)
{
$this->errorCodeField = $name;
return $this;
}
/**
* @param $bool
* @return $this
*/
public function setUseSwoole($bool)
{
$this->use_swoole = $bool;
return $this;
}
/**
* @param string $name
* @return $this
*/
public function setErrorMsgField(string $name)
{
$this->errorMsgField = $name;
return $this;
}
/**
* @param string $host
*/
public function setHost(string $host)
{
$this->host = $this->replaceHost($host);
$match_quest = '/^[a-zA-Z\-](\.[a-zA-Z\-])*/';
if (preg_match($match_quest, $this->host)) {
$this->addHeader('Host', $this->host);
}
}
/**
* @param array $header
*/
public function setHeader(array $header)
{
$this->header = $header;
}
/**
* @param $key
* @param $value
*/
public function addHeader($key, $value)
{
$this->header[$key] = $value;
}
/**
* @param null $callback
*/
public function setCallback($callback)
{
$this->callback = $callback;
}
/**
* @param string $method
*/
public function setMethod(string $method)
{
$this->method = $method;
}
/**
* @param string $url
*/
public function setUrl(string $url)
{
$this->url = $url;
}
public function setAgent(string $agent)
{
$this->agent = $agent;
}
/**
* @param bool $isSSL
*/
public function setIsSSL(bool $isSSL)
{
$this->isSSL = $isSSL;
if ($this->isSSL) {
$this->port = 443;
}
}
public function setPort($port)
{
$this->port = $port;
}
/**
* @return bool
*/
public function getIsSSL()
{
return $this->isSSL;
}
/**
* @param bool $isFIle
* 设置返回类型
*/
public function asFileStream($isFIle = true)
{
$this->isFileStream = $isFIle;
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
private function request($url, $data = [])
{
$data = $this->paramEncode($data);
if ($this->use_swoole === false) {
return $this->useCurl($url, $data);
} else if ($this->use_swoole) {
return $this->coroutine($this->parseUrlHost($url), $url, $data);
} else {
if (function_exists('getIsCli') && getIsCli()) {
return $this->coroutine($this->parseUrlHost($url), $url, $data);
}
return $this->useCurl($url, $data);
}
}
/**
* @param $url
* @param $data
* @return array|Result|mixed
*/
private function useCurl($url, $data)
{
if ($this->isHttp($url) || $this->isHttps($url)) {
return $this->curl($url, $data);
}
if ($this->isSSL) {
return $this->curl('https://' . $this->host . '/' . $url, $data);
} else {
return $this->curl('http://' . $this->host . '/' . $url, $data);
}
}
/**
* @param $url
* @return string
*/
private function parseUrlHost(&$url)
{
if (!empty($this->host)) {
$url = $this->host . '/' . ltrim($url, '/');
}
if (strpos($url, 'http') === false) {
$url = 'https://' . $url;
}
$host = $this->cutRequestUrl($url);
if ($this->checkIsIp($host)) {
return $host;
}
return System::gethostbyname($host);
}
/**
* @param $url
* @return mixed
*/
private function cutRequestUrl(&$url)
{
$url = $this->replaceHost($url);
$explode = explode('/', $url);
$first = array_shift($explode);
if (strpos($first, ':') !== false) {
[$first, $this->port] = explode(':', $first);
if ($this->port !== 443) {
$this->isSSL = false;
}
}
$url = '/' . implode('/', $explode);
return $first;
}
/**
* @param $host
* @return string|string[]
*/
private function replaceHost($host)
{
if ($this->isHttp($host)) {
$host = str_replace('http://', '', $host);
} else if ($this->isHttps($host)) {
$host = str_replace('https://', '', $host);
}
return $host;
}
/**
* @param $url
* @return false|int
*/
private function checkIsIp($url)
{
return preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $url);
}
/**
* @param $url
* @return bool
*/
private function isHttp($url)
{
return strpos($url, 'http://') === 0;
}
/**
* @param $url
* @return bool
*/
private function isHttps($url)
{
return strpos($url, 'https://') === 0;
}
/**
* @param $ip
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
* 使用swoole协程方式请求
*/
private function coroutine($ip, $url, $data = [])
{
$client = $this->generate_client($ip, $url, $data);
if ($client->statusCode < 0) {
throw new \Exception($client->errMsg);
}
$body = $client->body;
$client->close();
$header = $client->getHeaders();
$body = $this->resolve($header, $body);
unset($this->_data);
if ($client->getStatusCode() != 200) {
return new Result(['code' => $client->getStatusCode(), 'message' => $this->searchMessageByData($body), 'data' => $body]);
}
return $this->structure($body, $data, $header);
}
/**
* @return mixed
*/
private function getHostIp()
{
$host = \Co::getAddrInfo($this->host);
return array_shift($host);
}
/**
* @return int
*/
private function getHostPort()
{
if (!empty($this->port)) {
return $this->port;
}
$port = 80;
if ($this->isSSL) $port = 443;
return $port;
}
/**
* @param $host
* @param $port
* @param $url
* @param $data
* @return \Swoole\Coroutine\Http\Client
*/
private function generate_client($host, $url, $data)
{
$client = new SClient($host, $this->getHostPort(), $this->isSSL);
if (!empty($this->agent)) {
$this->header['User-Agent'] = $this->agent;
}
if (!empty($this->header)) {
$client->setHeaders($this->parseHeaderMat());
}
if (!empty($this->_data)) {
$client->setData($this->_data);
}
if (strtolower($this->method) == self::GET) {
if (!empty($data)) {
$url .= '?' . $data;
}
$client->get($url);
} else if (strtolower($this->method) == self::PUT) {
$client->setMethod('PUT');
if (!is_string($data)) {
$data = json_encode($data);
}
if (!empty($data)) {
$client->setData($data);
}
$client->execute($url);
} else if (strtolower($this->method) == self::DELETE) {
$client->setMethod('DELETE');
if (!is_string($data)) {
$data = json_encode($data);
}
if (!empty($data)) {
$client->setData($data);
}
$client->execute($url);
} else {
$client->post($url, $data);
}
return $client;
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
*/
private function curl($url, $data = [])
{
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->createRequestUrl($url, $data));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 超时设置
curl_setopt($ch, CURLOPT_HEADER, true);
if ($headers = $this->parseHeaderMat()) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if (!empty($this->agent)) {
curl_setopt($ch, CURLOPT_USERAGENT, $this->agent);
}
curl_setopt($ch, CURLOPT_SSLCERT, $this->getSslCertFile());
curl_setopt($ch, CURLOPT_SSLKEY, $this->getSslKeyFile());
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); // 超时设置
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//返回内容
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
if ($this->method == self::POST) {
curl_setopt($ch, CURLOPT_POST, 1);
}
if ($this->method != self::GET) {
if (!empty($this->_data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_data);
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method));
$output = curl_exec($ch);
curl_close($ch);
if ($output === FALSE) {
$data = new Result(['code' => 500, 'message' => curl_error($ch)]);
} else {
[$header, $body, $status] = $this->explode($output);
if ($status != 200) {
$data = new Result(['code' => 500, 'message' => $body, 'header' => $header]);
} else {
$data = $this->structure($body, $data, $header);
}
}
unset($ch);
return $data;
} catch (\Exception $exception) {
return new Result(['code' => 500, 'message' => $exception->getMessage(), 'header' => []]);
}
}
/**
* @param $output
* @return array
*/
private function explode($output)
{
[$header, $body] = explode("\r\n\r\n", $output, 2);
if ($header == 'HTTP/1.1 100 Continue') {
[$header, $body] = explode("\r\n\r\n", $body, 2);
} else if (strpos($body, "\r\n\r\n") !== false) {
[$header, $body] = explode("\r\n\r\n", $body, 2);
}
$header = explode("\r\n", $header);
unset($output);
$status = (int)explode(' ', trim($header[0]))[1];
$header = $this->headerFormat($header);
return [$header, $this->resolve($header, $body), $status];
}
/**
* @param $url
* @param $data
* @return string
*/
private function createRequestUrl($url, $data)
{
if ($this->isGet()) {
return $url . '?' . $data;
}
return $url;
}
/**
* @param $data
* @param $body
* @return mixed
*/
private function resolve($data, $body)
{
if (is_array($body)) {
return $body;
}
$type = $data['content-type'];
if (strpos($type, 'text/html') !== false) {
return $body;
} else if (strpos($type, 'json') !== false) {
return Help::toArray($body);
} else if (strpos($type, 'xml') !== false) {
return Help::toArray($body);
} else if (strpos($type, 'plain') !== false) {
return Help::toArray($body);
}
return $body;
}
/**
* @param $headers
* @return array
*/
private function headerFormat($headers)
{
$_tmp = [];
foreach ($headers as $key => $val) {
$trim = explode(': ', trim($val));
$_tmp[strtolower($trim[0])] = $trim[1] ?? '';
}
return $_tmp;
}
/**
* @param $body
* @param $_data
* @param $header
* @param $statusCode
* @return array|mixed|Result
* 构建返回体
*/
private function structure($body, $_data, $header = [], $statusCode = 200)
{
$this->setIsSSL(false);
$this->setHeaders([]);
if ($this->callback !== NULL) {
$result = call_user_func($this->callback, $body, $_data, $header);
$this->setCallback(null);
return $result;
}
if (is_string($body)) {
$result['code'] = 0;
$result['message'] = '';
} else {
$result['code'] = $body[$this->errorCodeField] ?? 0;
$result['message'] = $this->searchMessageByData($body);
}
$result['data'] = $body;
$result['header'] = $header;
$result['httpStatus'] = $statusCode;
return new Result($result);
}
/**
* @param $body
* @return array|mixed|string
*/
private function searchMessageByData($body)
{
$parent = [];
if (empty($this->errorMsgField)) {
return 'system success.';
}
$explode = explode('.', $this->errorMsgField);
if (!isset($body[$explode[0]])) {
return 'system success.';
}
foreach ($explode as $item) {
if (empty($item)) {
continue;
}
if (empty($parent)) {
$parent = $body[$item];
continue;
}
if (is_string($parent) || !isset($parent[$item])) {
break;
}
$parent = $parent[$item];
}
return !empty($parent) ? $parent : 'system success.';
}
/**
* @return bool
* check isPost Request
*/
public function isPost()
{
return strtolower($this->method) === self::POST;
}
/**
* @return bool
*
* check isGet Request
*/
public function isGet()
{
return strtolower($this->method) === self::GET;
}
/**
* @param $arr
*
* @return array|string
* 将请求参数进行编码
*/
private function paramEncode($arr)
{
if (!is_array($arr)) {
return $arr;
}
$_tmp = [];
foreach ($arr as $Key => $val) {
$_tmp[$Key] = $val;
}
if ($this->isGet()) {
return http_build_query($_tmp);
}
return $_tmp;
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws
*/
public function post($url, $data = [])
{
$this->setMethod(self::POST);
return $this->request($url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws
*/
public function put($url, $data = [])
{
$this->setMethod(self::PUT);
return $this->request($url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws
*/
public function get($url, $data = [])
{
$this->setMethod(self::GET);
return $this->request($url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
public function option($url, $data = [])
{
$this->setMethod(self::OPTIONS);
return $this->request($url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
public function delete($url, $data = [])
{
$this->setMethod(self::DELETE);
return $this->request($url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
public function send($url, $data = [])
{
return $this->request($url, $data);
}
/**
* @return array
*/
private function parseHeaderMat()
{
if ($this->use_swoole) {
return $this->header;
}
$headers = [];
foreach ($this->header as $key => $val) {
$header = $key . ':' . $val;
if (in_array($header, $headers)) {
continue;
}
$headers[] = $header;
}
$this->header = [];
return $headers;
}
/**
* @param array $headers
* @return array
*/
public function setHeaders(array $headers)
{
if (empty($headers)) {
return [];
}
foreach ($headers as $key => $val) {
$header = $key . ':' . $val;
if (in_array($header, $this->header)) {
continue;
}
$this->header[] = $header;
}
return $this->header;
}
}
-214
View File
@@ -1,214 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/26 0026
* Time: 10:23
*/
namespace common;
use common\Config;
abstract class Miniprogarampage implements Progaram
{
/** @var Config */
protected $config;
/** @var Miniprogarampage $instance */
protected static $instance = null;
/** @var HttpClient */
protected $request = null;
protected $errorCode = 0;
protected $errorMsg = '';
/**
* @param $message
* @param int $code
* @return Result
*/
protected function sendError($message, $code = 500)
{
return new Result(['code' => $code, 'message' => $message]);
}
/**
* @param $code
*/
public function setErrorCode($code)
{
$this->errorCode = $code;
}
/**
* @param $message
*/
public function setErrorMessage($message)
{
$this->errorMsg = $message;
}
/**
* @return int
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* @return string
*/
public function getErrorMessage()
{
return $this->errorMsg;
}
/**
* Miniprogarampage constructor.
*/
public function __construct()
{
$this->request = HttpClient::NewRequest();
$this->request->setIsSSL(true);
}
/**
* @param Config $config
* @return mixed
*/
public static function getInstance(Config $config)
{
if (static::$instance === null) {
static::$instance = new static();
}
static::$instance->config = $config;
static::$instance->request->setAgent($config->getAgent());
static::$instance->request->setUseSwoole($config->isUsrSwoole());
$request = static::$instance->request;
if ($request->getIsSSL()) {
$request->addHeader('ssl_cert_file', $config->getSslCert());
$request->addHeader('ssl_key_file', $config->getSslKey());
}
return static::$instance;
}
/**
* @param Config $config
* @return $this
*/
public function initConfig($config)
{
$this->config = $config;
$this->request->setUseSwoole($config->isUsrSwoole());
$this->request->setAgent($config->getAgent());
if (!empty($config->getSslCert())) {
$this->request->addHeader('ssl_cert_file', $config->getSslCert());
}
if (!empty($config->getSslKey())) {
$this->request->addHeader('ssl_key_file', $config->getSslKey());
}
return $this;
}
/**
* @return \common\Config
*/
public function getConfig()
{
return $this->config;
}
/**
* @return bool|mixed|string
* @throws \Exception
*/
protected function getAccessToken()
{
$access = $this->config->getAccessToken();
if (!empty($access)) {
return $access;
}
$this->request->setMethod(HttpClient::GET);
$data = $this->request->get('/cgi-bin/token', [
'grant_type' => 'client_credential',
'appid' => $this->config->getAppid(),
'secret' => $this->config->getAppsecret(),
]);
if (!$data->isResultsOK()) {
throw new \Exception($data->getMessage());
}
$access = $data->getData('access_token');
$this->config->setAccessToken($access);
return $access;
}
/**
* @param $data
* @param $body
* @return mixed
* @throws \Exception
*/
protected function buildResult($data, $body = NULL)
{
$data = $this->checkSign($data);
if (!$data) {
$return['code'] = -1;
$return['message'] = '签名错误.';
} else {
if (isset($data['return_code'])) {
if ($data['return_code'] == 'FAIL') {
$return['code'] = -1;
$return['message'] = $data['return_msg'];
} else {
$return['code'] = 0;
$return['data'] = $data;
$return['data']['postBody'] = $body;
}
} else {
if ($data['errcode'] == 'FAIL') {
$return['code'] = -1;
$return['message'] = $data['errmsg'];
} else {
$return['code'] = 0;
$return['data'] = $data;
$return['data']['postBody'] = $body;
}
}
}
return $return;
}
/**
* @param $result
* @return mixed
* @throws \Exception
*/
protected function checkSign($result)
{
$data = Help::toArray($result);
if (!isset($data['sign'])) {
return $data;
}
$sign = $data['sign'];
unset($data['sign']);
$key = $this->config->getKey();
$sign_type = $this->config->getSignType();
$_sign = Help::sign($data, $key, $sign_type);
if ($sign != $_sign) {
return FALSE;
}
return $data;
}
}
-10
View File
@@ -1,10 +0,0 @@
<?php
namespace common;
interface Progaram
{
}
-165
View File
@@ -1,165 +0,0 @@
<?php
namespace common;
/**
* Class Result
*
* @package app\components
*
* @property $code
* @property $message
* @property $count
* @property $data
*/
class Result
{
public $code;
public $message;
public $count = 0;
public $data;
public $header;
public function __construct(array $data)
{
foreach ($data as $key => $val) {
$this->$key = $val;
}
$this->header = $this->reloadResponse($this->header);
}
/**
* @param $header
*
* @return array
*/
private function reloadResponse($header)
{
$data = [];
if (is_array($header)) {
return $header;
}
$load = explode("\n", $header);
if (!empty($load) && is_array($load)) {
foreach ($load as $key => $val) {
if (empty($val)) continue;
$ex = explode(': ', $val);
if (!empty($ex[0]) && !empty($ex[1])) {
$data[trim($ex[0])] = trim($ex[1]);
}
}
}
return $data;
}
public function __get($name)
{
return $this->$name;
}
public function __set($name, $value)
{
$this->$name = $value;
return $this;
}
public function getTime()
{
return [
'startTime' => $this->startTime,
'requestTime' => $this->requestTime,
'runTime' => $this->runTime,
];
}
/**
* @param $key
* @param $data
* @return $this
* @throws \Exception
*/
public function setAttr($key, $data)
{
if (!property_exists($this, $key)) {
throw new \Exception('未查找到相应对象属性');
}
$this->$key = $data;
return $this;
}
public function isResultsOK()
{
if (!is_numeric($this->code)) {
return false;
}
return $this->code == 0;
}
/**
* @param array $headers
* 批量设置返回头
*/
public function setHeaders(array $headers)
{
foreach ($headers as $key => $val) {
$this->setHeader($key, $val);
}
}
/**
* @param $key
* @param $val
* 设置返回头
*/
public function setHeader($key, $val)
{
header($key . ':' . $val);
}
/**
* @param string $name
* @return mixed
*/
public function getData($name = '')
{
if (!$this->isResultsOK()) {
return $this->data;
}
if (!empty($name) && isset($this->data[$name])) {
return $this->data[$name];
}
return $this->data;
}
/**
* @param $key
* @param $data
* @return $this
*/
public function append($key, $data)
{
$this->data[$key] = $data;
return $this;
}
/**
* @return mixed
*/
public function getMessage()
{
return $this->message;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
}