add clear

This commit is contained in:
as2252258@163.com
2019-11-11 18:14:47 +08:00
parent 62a2326e23
commit 7f138ef255
47 changed files with 2440 additions and 1100 deletions
+19 -34
View File
@@ -7,7 +7,12 @@
*/
namespace wchat;
class Account extends Miniprogarampage
use common\Decode;
use common\HttpClient;
use common\Result;
class Account extends SmallProgram
{
private $wxaqr = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=';
@@ -43,7 +48,7 @@ class Account extends Miniprogarampage
$param['js_code'] = $code;
$param['grant_type'] = 'authorization_code';
$this->request->setMethod(WxClient::GET);
$this->request->setMethod(HttpClient::GET);
$this->request->addHeader('Content-Type', 'text/xml');
return $this->request->get('sns/jscode2session', $param);
@@ -58,11 +63,11 @@ class Account extends Miniprogarampage
{
$query = [
'access_token' => $this->getAccessToken(),
'openid' => $openid,
'lang' => 'zh_CN'
'openid' => $openid,
'lang' => 'zh_CN'
];
$this->request->setMethod(WxClient::GET);
$this->request->setMethod(HttpClient::GET);
$this->request->setIsSSL(true);
return $this->request->get($this->publicInfo, $query);
}
@@ -84,33 +89,13 @@ class Account extends Miniprogarampage
*/
public function decode($encryptedData, $iv, $sessionKey, $asArray = false)
{
$config = Wx::getMiniProGaRamPage()->getConfig();
if (strlen($sessionKey) != 24) {
throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey);
}
$decode = new Decode();
$decode->setSessionKey($sessionKey);
$decode->setEncryptedData($encryptedData);
$decode->setAppId($this->config->getAppid());
$decode->setIv($iv);
$aesKey = base64_decode($sessionKey);
if (strlen($iv) != 24) {
throw new \Exception('base64解密失败', $this->IllegalIv);
}
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($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 != $config->getAppid()) {
throw new \Exception('aes 解密失败', $this->IllegalBuffer);
}
if ($asArray) {
return get_object_vars($dataObj);
}
return $dataObj;
return $decode->decode($asArray);
}
@@ -127,7 +112,7 @@ class Account extends Miniprogarampage
$sendBody['path'] = $path;
$sendBody['width'] = $width;
$this->request->setMethod(WxClient::POST);
$this->request->setMethod(HttpClient::POST);
$this->request->setCallback([$this, 'saveByPath']);
return $this->request->post($url, $sendBody);
@@ -155,7 +140,7 @@ class Account extends Miniprogarampage
$url = $this->getwxacode . $this->getAccessToken();
$this->request->setMethod(WxClient::POST);
$this->request->setMethod(HttpClient::POST);
$this->request->setCallback([$this, 'saveByPath']);
return $this->request->post($url, $sendBody);
}
@@ -182,7 +167,7 @@ class Account extends Miniprogarampage
$url = $this->getwxacodeunlimit . $this->getAccessToken();
$this->request->setMethod(WxClient::POST);
$this->request->setMethod(HttpClient::POST);
$this->request->setCallback([$this, 'saveByPath']);
return $this->request->post($url, $sendBody);
}
-443
View File
@@ -1,443 +0,0 @@
<?php
namespace wchat;
class Config
{
/**
* @var string
*
* 小程序ID
*/
private $appid = '';
/**
* @var string
*
* 商户号ID
*/
private $mch_id = '';
/**
* @var string
*
* 设备号
*/
private $device_info = 'WEB';
/**
* @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 = '';
/**
* @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 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;
}
}
-93
View File
@@ -1,93 +0,0 @@
<?php
namespace wchat;
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_null($json = json_decode($xml, TRUE))) {
return $json;
}
if (is_array($json)) {
return $json;
}
$data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
return json_decode(json_encode($data), TRUE);
}
/**
* @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);
}
}
}
+5 -4
View File
@@ -3,8 +3,9 @@
namespace wchat;
class Message extends Miniprogarampage
use common\HttpClient;
use common\Result;
class Message extends SmallProgram
{
const TEXT = 0;
const IMAGE = 1;
@@ -253,7 +254,7 @@ class Message extends Miniprogarampage
$data = ['media' => $real_path, 'description[title]' => $title, 'description[introduction]' => $introduction];
}
$this->request->setMethod(WxClient::POST);
$this->request->setMethod(HttpClient::POST);
/** @var Result $body */
$data = $this->request->post($url, $data);
@@ -298,7 +299,7 @@ class Message extends Miniprogarampage
$data = json_encode($this->msgData, JSON_UNESCAPED_UNICODE);
$url = '/cgi-bin/message/custom/send?access_token=' . $this->getAccessToken();
$this->request->setMethod(WxClient::POST);
$this->request->setMethod(HttpClient::POST);
/** @var Result $body */
$body = $this->request->post($url, $data);
-140
View File
@@ -1,140 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/26 0026
* Time: 10:23
*/
namespace wchat;
abstract class Miniprogarampage
{
/** @var Config */
protected $config;
/** @var Miniprogarampage $instance */
protected static $instance = null;
/** @var WxClient */
protected $request = null;
/**
* Miniprogarampage constructor.
*/
private function __construct()
{
$this->request = WxClient::getInstance();
$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());
$request = static::$instance->request;
if ($request->getIsSSL()) {
$request->addHeader('ssl_cert_file', $config->getSslCert());
$request->addHeader('ssl_key_file', $config->getSslKey());
}
return static::$instance;
}
/**
* @return bool|mixed|string
* @throws \Exception
*/
protected function getAccessToken()
{
$access = $this->config->getAccessToken();
if (!empty($access)) {
return $access;
}
$this->request->setMethod(WxClient::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;
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
namespace wchat;
class Notify extends Miniprogarampage
class Notify extends SmallProgram
{
public $appid = '';
public $mch_id = '';
+3 -1
View File
@@ -8,7 +8,9 @@
namespace wchat;
class PublicTemplate extends Miniprogarampage
use common\Result;
class PublicTemplate extends SmallProgram
{
private $keywords = [];
+4 -1
View File
@@ -8,7 +8,10 @@
namespace wchat;
class Recharge extends Miniprogarampage
use common\Result;
use common\Help;
class Recharge extends SmallProgram
{
private $money = 0;
-156
View File
@@ -1,156 +0,0 @@
<?php
namespace wchat;
/**
* 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 = [];
$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 '';
}
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;
}
public function getMessage()
{
return $this->message;
}
public function getCode()
{
return $this->code;
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace wchat;
use common\Miniprogarampage;
class SmallProgram extends Miniprogarampage
{
protected static $instance;
private $url = 'https://api.weixin.qq.com/cgi-bin/token';
/**
* @return mixed
* @throws \Exception
*/
public function generateAccess_token()
{
if (!empty($this->config->getToken())) {
return $this->config->getToken();
}
$query = [
'grant_type' => 'client_credential',
'appid' => $this->config->getAppid(),
'secret' => $this->config->getAppsecret()
];
$param = $this->request->get($this->url, $query);
if (!$param->isResultsOK()) {
throw new \Exception($param->getMessage());
}
return $param->getData();
}
}
+3 -1
View File
@@ -4,7 +4,9 @@
namespace wchat;
class Subject extends Miniprogarampage
use common\Result;
class Subject extends SmallProgram
{
+3 -1
View File
@@ -8,7 +8,9 @@
namespace wchat;
class Template extends Miniprogarampage
use common\Result;
class Template extends SmallProgram
{
private $keywords = [];
+1 -20
View File
@@ -4,28 +4,9 @@
namespace wchat;
class Token extends Miniprogarampage
class Token extends SmallProgram
{
private $url = 'https://api.weixin.qq.com/cgi-bin/token';
/**
* @return mixed|null
*/
public function generateAccess_token()
{
$query = [
'grant_type' => 'client_credential',
'appid' => $this->config->getAppid(),
'secret' => $this->config->getAppsecret()
];
$param = $this->request->get($this->url, $query);
if (!$param->isResultsOK()) {
return null;
}
return $param->getData('access_token');
}
}
-123
View File
@@ -1,123 +0,0 @@
<?php
namespace wchat;
class Wx
{
/** @var static $instance */
private static $instance = null;
/** @var Config $config */
private $config = null;
/**
* @return static
*/
public static function getMiniProGaRamPage()
{
if (static::$instance === null) {
static::$instance = new Wx();
}
return static::$instance;
}
/**
* @return Config
*/
public function getConfig()
{
return $this->config;
}
/**
* @param Config $config
* @return $this
*/
public function setConfig(Config $config)
{
$this->config = $config;
return $this;
}
/**
* @return Template
*/
public function getTemplate()
{
return Template::getInstance($this->config);
}
/**
* @return PublicTemplate
*/
public function getPublicTemplate()
{
return PublicTemplate::getInstance($this->config);
}
/**
* @return Account
*/
public function getAccount()
{
return Account::getInstance($this->config);
}
/**
* @return Message
*/
public function getMessage()
{
return Message::getInstance($this->config);
}
/**
* @return Recharge
*/
public function getRecharge()
{
return Recharge::getInstance($this->config);
}
/**
* @return Notify
*/
public function getNotify()
{
return Notify::getInstance($this->config);
}
/**
* @return Token
*/
public function getToken()
{
return Token::getInstance($this->config);
}
/**
* @return WxClient
*/
public function getClient()
{
$client = WxClient::getInstance();
$client->setAgent($this->config->getAgent());
return $client;
}
/**
* @return Subject
*/
public function getSubject()
{
return Subject::getInstance($this->config);
}
}
-428
View File
@@ -1,428 +0,0 @@
<?php
namespace wchat;
use Swoole\Coroutine\Http\Client;
use Swoole\Coroutine\System;
class WxClient
{
private $host = 'api.weixin.qq.com';
private $header = [];
private $callback = null;
private $method = 'get';
private $url = '';
private $isSSL = false;
private $agent = '';
const POST = 'post';
const GET = 'get';
const PUT = 'put';
const DELETE = 'delete';
const OPTIONS = 'option';
private function __construct()
{
}
/**
* @return WxClient
*/
public static function getInstance()
{
static $client = null;
if (!($client instanceof WxClient)) {
$client = new WxClient();
}
return $client;
}
/**
* @param string $host
*/
public function setHost(string $host)
{
$this->host = $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;
}
public function getIsSSL()
{
return $this->isSSL;
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
private function request($url, $data = [])
{
if (function_exists('getIsCli') && getIsCli()) {
if (strpos($url, 'http://') !== FALSE) {
$url = str_replace('http://', '', $url);
} else if (strpos($url, 'https://') !== FALSE) {
$url = str_replace('https://', '', $url);
}
$explode = explode('/', $url);
$ip = System::gethostbyname(array_shift($explode));
return $this->coroutine($ip, $url, $data);
}
if (
strpos($url, 'http://') === 0 ||
strpos($url, 'https://') === 0
) {
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 $ip
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
* 使用swoole协程方式请求
*/
private function coroutine($ip, $url, $data = [])
{
$_data = $this->paramEncode($data);
if ($this->method == 'get' && is_array($_data)) {
$url .= '?' . http_build_query($_data);
}
$client = $this->getClient($ip, $this->getHostPort(), $url, $data);
if ($client->statusCode < 0) {
throw new \Exception($client->errMsg);
}
$body = $client->body;
$client->close();
return $this->structure($body, $_data);
}
/**
* @return mixed
*/
private function getHostIp()
{
$host = \Co::getAddrInfo($this->host);
return array_shift($host);
}
/**
* @return int
*/
private function getHostPort()
{
$port = 80;
if ($this->isSSL) $port = 443;
return $port;
}
/**
* @param $host
* @param $port
* @param $url
* @param $data
* @return Client
*/
private function getClient($host, $port, $url, $data)
{
$client = new Client($host, $port, $this->isSSL);
if (!empty($this->agent)) {
$this->header['User-Agent'] = $this->agent;
}
if (!empty($this->header)) {
$client->setHeaders($this->header);
}
switch (strtolower($this->method)) {
case self::GET:
$client->get($url);
break;
default:
$client->post($url, $data);
}
return $client;
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
*/
private function curl($url, $data = [])
{
$data = $this->paramEncode($data, self::POST);
$ch = $this->structureCurlRequest($url, $data);
if ($this->method != self::GET) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} else if ($this->method == self::POST) {
curl_setopt($ch, CURLOPT_POST, 1);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method));
$output = curl_exec($ch);
if ($output === FALSE) {
return new Result(['code' => 500, 'message' => curl_error($ch)]);
}
curl_close($ch);
return $this->structure($output, $data);
}
/**
* @param $url
* @param $_data
* @return resource
*/
private function structureCurlRequest($url, $_data)
{
$ch = curl_init();
if ($this->method == self::GET) {
if (is_array($_data)) {
$_data = http_build_query($_data);
}
$url = $url . '?' . $_data;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 超时设置
curl_setopt($ch, CURLOPT_HEADER, FALSE);
if (!empty($this->header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);
}
if (!empty($this->agent)) {
curl_setopt($ch, CURLOPT_USERAGENT, $this->agent);
}
if ($this->isSSL) {
curl_setopt($ch, CURLOPT_SSLCERT, $this->header['ssl_cert_file']);
curl_setopt($ch, CURLOPT_SSLKEY, $this->header['ssl_key_file']);
}
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');
return $ch;
}
/**
* @param $body
* @param $_data
* @return array|mixed|Result
* 构建返回体
*/
private function structure($body, $_data)
{
$this->setIsSSL(false);
$this->setHeaders([]);
if ($this->callback !== NULL) {
$result = call_user_func($this->callback, $body, $_data);
} else {
$result = $this->formatResponseBody($body);
}
$this->setCallback(null);
if (!is_array($result)) {
return $result;
}
return new Result($result);
}
/**
* @param $body
* @return array|Result
*/
private function formatResponseBody($body)
{
$result = [];
if (is_null($results = json_decode($body, TRUE))) {
$data = simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA);
$results = json_decode(json_encode($data), TRUE);
}
if (!is_array($results)) {
$result = new Result(['code' => 505, 'message' => '服务器返回体错误!']);
} else if (isset($results['errcode'])) {
$result['code'] = $results['errcode'];
$result['message'] = $results['errmsg'];
} else {
$result['code'] = 0;
$result['message'] = 'system success.';
$result['data'] = $results;
}
return $result;
}
/**
* @param $arr
* @param string $pushType
*
* @return array|string
* 将请求参数进行编码
*/
private function paramEncode($arr, $pushType = 'post')
{
if (!is_array($arr)) {
return $arr;
}
$_tmp = [];
foreach ($arr as $Key => $val) {
$_tmp[$Key] = $val;
}
return ($pushType == 'post' ? $_tmp : http_build_query($_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);
}
/**
* @param array $headers
* @return array
*/
public function setHeaders(array $headers)
{
if (empty($headers)) {
return [];
}
foreach ($headers as $key => $val) {
$this->header[] = $key . ':' . $val;
}
return $this->header;
}
}