Commit cf0bdc43 by BANice

使用原生db

parents
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/vendor/composer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/inflector" />
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/guzzle" />
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/promises" />
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/psr7" />
<excludeFolder url="file://$MODULE_DIR$/vendor/illuminate/container" />
<excludeFolder url="file://$MODULE_DIR$/vendor/illuminate/contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/illuminate/database" />
<excludeFolder url="file://$MODULE_DIR$/vendor/illuminate/support" />
<excludeFolder url="file://$MODULE_DIR$/vendor/monolog/monolog" />
<excludeFolder url="file://$MODULE_DIR$/vendor/nesbot/carbon" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/container" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/http-message" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/log" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/simple-cache" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-mbstring" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/translation" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" serverName="cdz">
<serverData>
<paths name="cdz">
<serverdata>
<mappings>
<mapping deploy="/cdzpay/customer_charger_order" local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/customer_charger_order.iml" filepath="$PROJECT_DIR$/.idea/customer_charger_order.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/vendor/doctrine/inflector" />
<path value="$PROJECT_DIR$/vendor/nesbot/carbon" />
<path value="$PROJECT_DIR$/vendor/composer" />
<path value="$PROJECT_DIR$/vendor/psr/container" />
<path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
<path value="$PROJECT_DIR$/vendor/illuminate/container" />
<path value="$PROJECT_DIR$/vendor/illuminate/database" />
<path value="$PROJECT_DIR$/vendor/psr/http-message" />
<path value="$PROJECT_DIR$/vendor/illuminate/contracts" />
<path value="$PROJECT_DIR$/vendor/guzzlehttp/guzzle" />
<path value="$PROJECT_DIR$/vendor/illuminate/support" />
<path value="$PROJECT_DIR$/vendor/symfony/translation" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-mbstring" />
<path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
<path value="$PROJECT_DIR$/vendor/guzzlehttp/promises" />
<path value="$PROJECT_DIR$/vendor/monolog/monolog" />
<path value="$PROJECT_DIR$/vendor/psr/log" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.2" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="WebServers">
<option name="servers">
<webServer id="db2a2143-5e09-40dd-85b0-0d2422e5a7eb" name="cdz" url="http://hub.senthink.com">
<fileTransfer anonymous="true" host="hub.senthink.com" port="21">
<advancedOptions>
<advancedOptions compatibilityMode="true" dataProtectionLevel="Private" passiveMode="true" />
</advancedOptions>
<option name="port" value="21" />
</fileTransfer>
</webServer>
</option>
</component>
</project>
\ No newline at end of file
This diff is collapsed. Click to expand it.
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/17
* Time: 下午3:35
*/
namespace Lib;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
/**
*
* @method static debug($info, $context = [])
* @method static warn($info, $context = [])
* @method static alert($info, $context = [])
* @method static error($info, $context = [])
* @method static info($info, $context = [])
*
*
* Class Log
* @package Lib
*/
class Log
{
/**
* @var Logger
*/
private static $log;
private function __construct(string $logName)
{
}
public static function bootLog(string $logName = './storage/log/customer')
{
if (static::$log instanceof Log) {
return static::$log;
} else {
static::$log = new Logger($logName);
static::$log->pushHandler(new RotatingFileHandler($logName, 30, 'debug'));
// static::$log->pushProcessor(function ($record) {
//
// $record['extra']['gateway_mac'] = S_SESSION['gateway_mac'] ?? 'no mac';
//
// });
}
}
/**
* @param $name
* @param $arguments
*/
public static function __callStatic($name, $arguments)
{
// $gatewayMac = isset($_SESSION['gateway_mac']) ? $_SESSION['gateway_mac'] : 'null mac';
// $arguments[0] = "[$gatewayMac] -> " . $arguments[0];
static::bootLog();
return call_user_func_array([static::$log, $name], $arguments);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/14
* Time: 下午5:16
*/
namespace Lib\api\message;
class ChargerExceedMessage extends MessageData
{
/**
* @var string
*/
protected $templateId = 'rdzTNQ7t4uRXkP0SkuwW10WH77A_CIgYFiJykXJ0utU';
/**
* @var string
*/
private $first = '尊敬的用户,你的爱车功率过大,本次充电已结束
';
/**
* @var string
*/
private $remark = '温馨提示:电瓶车的功率超出了充电口所允许的最大充电功率,您可以在公众号后台留言或直接拨打客服热线进行咨询';
/**
* @var string
*/
private $startTime = '';
/**
* @var string
*/
private $chargerTime = '';
/**
* @var string
*/
private $endTime = '';
public function getPushDataJson(): string
{
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->startTime,
'color' => '#333',
],
'keyword2' => [
'value' => $this->chargerTime.'分钟',
'color' => '#333',
],
'keyword3' => [
'value' => $this->endTime,
'color' => '#333',
],
'remark' => [
'value' => $this->remark,
'color' => '#333',
],
]);
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
/**
* @return string
*/
public function getStartTime(): string
{
return $this->startTime;
}
/**
* @param string $startTime
*/
public function setStartTime(string $startTime): void
{
$this->startTime = $startTime;
}
/**
* @return string
*/
public function getChargerTime(): string
{
return $this->chargerTime;
}
/**
* @param string $chargerTime
*/
public function setChargerTime(string $chargerTime): void
{
$this->chargerTime = $chargerTime;
}
/**
* @return string
*/
public function getEndTime(): string
{
return $this->endTime;
}
/**
* @param string $endTime
*/
public function setEndTime(string $endTime): void
{
$this->endTime = $endTime;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/7/6
* Time: 上午11:45
*/
namespace Lib\api\message;
class ChargerExcessMessage extends MessageData
{
public function getPushDataJson(): string
{
return 'a';
// TODO: Implement getPushDataJson() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/30
* Time: 下午4:13
*/
namespace Lib\api\message;
class ChargerFailMessage extends MessageData
{
/**
* @var string
*/
protected $templateId = 'C0LvfETe-1rCR_IhOydDGPTUwwYkrWZxgfwMsETrhw8';
/**
* @var string
*/
private $first = '尊敬的用户,我们检测的您的订单充电失败。
';
/**
* @var string
*/
private $portName = '';
/**
* @var string
*/
private $stationName = '';
/**
* @var string
*/
private $time = '';
/**
* @var string
*/
private $remark = '支付金额会在1个工作日内退回您的余额或零钱。';
public function getUserId(): int
{
// TODO: Implement getUserId() method.
}
/**
* @return string
*/
public function getPushDataJson(): string
{
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->stationName . "($this->portName)",
'color' => '#333',
],
'keyword2' => [
'value' => $this->time,
'color' => '#333',
],
'remark' => [
'value' => $this->remark,
'color' => '#333',
],
]);
// TODO: Implement getPushDataJson() method.
}
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return string
*/
public function getPortName(): string
{
return $this->portName;
}
/**
* @param string $portName
*/
public function setPortName(string $portName): void
{
$this->portName = $portName;
}
/**
* @return string
*/
public function getStationName(): string
{
return $this->stationName;
}
/**
* @param string $stationName
*/
public function setStationName(string $stationName): void
{
$this->stationName = $stationName;
}
/**
* @return string
*/
public function getTime(): string
{
return $this->time;
}
/**
* @param string $time
*/
public function setTime(string $time): void
{
$this->time = $time;
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/4
* Time: 下午3:56
*/
namespace Lib\api\message;
use Application\Model\OrderModel;
use Lib\Log;
class ChargerFinishMessage extends MessageData
{
protected $templateId = 'f0DDXSxvRTbHyzkCnwnYijtgteFTdfdUR7J8REwTYJ8';
private $first = '亲爱的用户,您的爱车已经完成充电啦';
/**
* @var string
*/
private $endTime = '';
/**
* @var string
*/
private $chargerPlc = '';
/**
* @var string
*/
private $chargerTime;
/**
* @var int
*/
private $orderAmount;
/**
* @var string
*/
private $remark = '感谢你的使用';
/**
* @var int
*/
/**
* @return string
*/
public function getPushDataJson(): string
{
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->endTime,
'color' => '#333',
],
'keyword2' => [
'value' => $this->chargerPlc,
'color' => '#333',
],
'keyword3' => [
'value' => $this->chargerTime.' 分',
'color' => '#333',
],
'keyword4' => [
'value' => $this->orderAmount.' ¥',
'color' => '#333',
],
'remark' => [
'value' => $this->remark,
'color' => '#333',
],
]);
}
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return string
*/
public function getEndTime(): string
{
return $this->endTime;
}
/**
* @param string $endTime
*/
public function setEndTime(string $endTime): void
{
$this->endTime = $endTime;
}
/**
* @return string
*/
public function getChargerPlc(): string
{
return $this->chargerPlc;
}
/**
* @param string $chargerPlc
*/
public function setChargerPlc(string $chargerPlc): void
{
$this->chargerPlc = $chargerPlc;
}
/**
* @return string
*/
public function getChargerTime(): string
{
return $this->chargerTime;
}
/**
* @param string $chargerTime
*/
public function setChargerTime(string $chargerTime): void
{
$this->chargerTime = $chargerTime;
}
/**
* @return int
*/
public function getOrderAmount(): int
{
return $this->orderAmount;
}
/**
* @param int $orderAmount
*/
public function setOrderAmount(int $orderAmount): void
{
$this->orderAmount = $orderAmount;
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
/**
* @return int
*/
public function getUserId(): int
{
return $this->userId;
}
/**
* @param int $userId
*/
public function setUserId(int $userId): void
{
$this->userId = $userId;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/7/7
* Time: 上午11:36
*/
namespace Lib\api\message;
class ChargerFullMessage extends MessageData
{
protected $templateId ='rdzTNQ7t4uRXkP0SkuwW10WH77A_CIgYFiJykXJ0utU';
private $first = '';
private $startTime = '';
public function getPushDataJson(): string
{
return '';
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/14
* Time: 下午2:19
*/
namespace Lib\api\message;
class ChargerRefundMessage extends MessageData
{
protected $templateId = '0al-a6kkNsdqFyXPEe97m4jjtbfOXjEC3eCjEsMHJdw';
private $first = '超时未插入插头,已取消订单,退款稍后送达,请注意查收';
/**
* @var string
*/
private $outTradeNo = '';
/**
* @var string
*/
private $orderInfo = '';
/**
* @var string
*/
private $orderFee = '';
private $remark = '温馨提示:超时关闭此次交易,支付金额会在1个工作日内退回您的余额或零钱,请注意查看,若未收到请联系我们的客服为您处理。若为充电口异常,请您及时更换至其它充电口充电
';
/**
* @return string
*/
public function getPushDataJson(): string
{
// TODO: Implement getPushDataJson() method.
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->outTradeNo,
'color' => '#333',
],
'keyword2' => [
'value' => $this->orderInfo,
'color' => '#333',
],
'keyword3' => [
'value' => '¥'.$this->orderFee ,
'color' => '#333',
],
'remark' => [
'value' => $this->remark,
'color' => '#333',
],
]);
}
public function getUserId(): int
{
return $this->userId;
}
/**
* @return string
*/
public function getTemplateId(): string
{
return $this->templateId;
}
/**
* @param mixed $templateId
*/
public function setTemplateId($templateId): void
{
$this->templateId = $templateId;
}
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->outTradeNo;
}
/**
* @param string $outTradeNo
*/
public function setOutTradeNo(string $outTradeNo): void
{
$this->outTradeNo = $outTradeNo;
}
/**
* @return string
*/
public function getOrderInfo(): string
{
return $this->orderInfo;
}
/**
* @param string $orderInfo
*/
public function setOrderInfo(string $orderInfo): void
{
$this->orderInfo = $orderInfo;
}
/**
* @return string
*/
public function getOrderFee(): string
{
return $this->orderFee;
}
/**
* @param string $orderFee
*/
public function setOrderFee(string $orderFee): void
{
$this->orderFee = $orderFee;
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/7/6
* Time: 上午9:45
*/
namespace Lib\api\message;
class ChargerReloadMessage extends MessageData
{
protected $templateId = 't_PyOGCKN_fmD0blw0EuIQs-8sS3qOTmpQay12haPZY';
private $first = '充电继续通知:';
private $stationName = '';
private $portName = '';
private $time = '';
private $remark = '';
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return string
*/
public function getStationName(): string
{
return $this->stationName;
}
/**
* @param string $stationName
*/
public function setStationName(string $stationName): void
{
$this->stationName = $stationName;
}
/**
* @return string
*/
public function getPortName(): string
{
return $this->portName;
}
/**
* @param string $portName
*/
public function setPortName(string $portName): void
{
$this->portName = $portName;
}
/**
* @return string
*/
public function getTime(): string
{
return $this->time;
}
/**
* @param string $time
*/
public function setTime(string $time): void
{
$this->time = $time;
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
public function getPushDataJson(): string
{
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->stationName,
'color' => '#333',
],
'keyword2' => [
'value' => $this->portName,
'color' => '#333',
],
'keyword3' => [
'value' => date('Y-m-d H:i:s'),
'color' => '#333',
],
'remark' => [
'value' => '感谢你的使用',
'color' => '#333',
],
]);
// TODO: Implement getPushDataJson() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/2
* Time: 上午11:01
*/
namespace Lib\api\message;
class ChargerStartMessage extends MessageData
{
protected $templateId = 'L9SEWl3X73v3PBYHtFBZlTlJeBMdO9DDNIwRgHX6SrY';
private $first = '充电已经开始,请注意接收消息';
private $startTime;
private $address;
private $amount;
public function __construct()
{
$this->startTime = date('Y-m-d H:i:s');
}
/**
* @return string
*/
public function getPushDataJson(): string
{
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->startTime,
'color' => '#333',
],
'keyword2' => [
'value' => $this->address,
'color' => '#333'
],
'keyword3' => [
'value' => $this->amount,
'color' => '#333'
],
'remark' => [
'value' => '感谢你的使用',
'color' => '#333'
],
]);
}
public function getUserId(): int
{
// TODO: Implement getUserId() method.
}
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return mixed
*/
public function getStartTime()
{
return $this->startTime;
}
/**
* @param mixed $startTime
*/
public function setStartTime($startTime): void
{
$this->startTime = $startTime;
}
/**
* @return mixed
*/
public function getAddress()
{
return $this->address;
}
/**
* @param mixed $address
*/
public function setAddress($address): void
{
$this->address = $address;
}
/**
* @return mixed
*/
public function getAmount()
{
return $this->amount;
}
/**
* @param mixed $amount
*/
public function setAmount($amount): void
{
$this->amount = $amount;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/7/9
* Time: 下午4:35
*/
namespace Lib\api\message;
class ChargerTimeoutMessage extends MessageData
{
protected $templateId = 'rdzTNQ7t4uRXkP0SkuwW10WH77A_CIgYFiJykXJ0utU';
private $first = '您的爱车插头脱落,等待10分钟未检测到插头重新插入,本次充电已结束。';
private $startTime = '';
private $chargerTime = '';
private $finishTime = '';
private $remark = '温馨提示:您的爱车已停止充电,如有疑问您可以在公众号后台留言或直接拨打客服热线进行咨询。\n
感谢您的使用';
/**
* @return string
*/
public function getPushDataJson(): string
{
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->startTime,
'color' => '#333',
],
'keyword2' => [
'value' => $this->chargerTime,
'color' => '#333'
],
'keyword3' => [
'value' => $this->finishTime,
'color' => '#333'
],
'remark' => [
'value' => $this->remark,
'color' => '#333'
],
]);
}
/**
* @return string
*/
public function getTemplateId(): string
{
return $this->templateId;
}
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return string
*/
public function getStartTime(): string
{
return $this->startTime;
}
/**
* @param string $startTime
*/
public function setStartTime(string $startTime): void
{
$this->startTime = $startTime;
}
/**
* @return string
*/
public function getChargerTime(): string
{
return $this->chargerTime;
}
/**
* @param string $chargerTime
*/
public function setChargerTime(string $chargerTime): void
{
$this->chargerTime = $chargerTime;
}
/**
* @return string
*/
public function getFinishTime(): string
{
return $this->finishTime;
}
/**
* @param string $finishTime
*/
public function setFinishTime(string $finishTime): void
{
$this->finishTime = $finishTime;
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/2
* Time: 上午11:03
*/
namespace Lib\api\message;
abstract class MessageData
{
protected $templateId;
/**
* @var int
*/
protected $userId = 1;
abstract public function getPushDataJson(): string;
/**
* @return mixed
*/
public function getTemplateId()
{
return $this->templateId;
}
/**
* @param mixed $templateId
*/
public function setTemplateId($templateId): void
{
$this->templateId = $templateId;
}
public function getUserId(): int
{
return $this->userId;
}
public function setUserId(int $userId): void
{
$this->userId = $userId;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/5
* Time: 上午9:48
*/
namespace Lib\api\message;
class PortShedMessage extends MessageData
{
/**
* @var string
*/
protected $templateId = 'C0LvfETe-1rCR_IhOydDGPTUwwYkrWZxgfwMsETrhw8';
/**
* @var string
*/
private $first = '尊敬的用户,充电端未检测到插头,请您在%s分钟内接入。';
/**
* @var string
*/
private $portName = '';
/**
* @var string
*/
private $stationName = '';
/**
* @var string
*/
private $time = '';
/**
* @var string
*/
private $remark = '超时将关闭此次交易哦,支付金额会在1个工作日内退回您的余额或零钱,请注意查看,若未收到请联系我们的客服为您处理。若为充电口异常,请您及时更换至其它充电口充电';
/**
* @var int
*/
private $waitingTime = 3;
public function __construct() {
$this->time = date('Y-m-d H:i:s');
}
public function getUserId(): int
{
// TODO: Implement getUserId() method.
}
/**
* @return string
*/
public function getPushDataJson(): string
{
$this->first = sprintf($this->first,$this->waitingTime);
return json_encode([
'first' => [
'value' => $this->first,
'color' => '#333',
],
'keyword1' => [
'value' => $this->stationName . "($this->portName)",
'color' => '#333',
],
'keyword2' => [
'value' => $this->time,
'color' => '#333',
],
'remark' => [
'value' => $this->remark,
'color' => '#333',
],
]);
// TODO: Implement getPushDataJson() method.
}
/**
* @return string
*/
public function getFirst(): string
{
return $this->first;
}
/**
* @param string $first
*/
public function setFirst(string $first): void
{
$this->first = $first;
}
/**
* @return string
*/
public function getPortName(): string
{
return $this->portName;
}
/**
* @param string $portName
*/
public function setPortName(string $portName): void
{
$this->portName = $portName;
}
/**
* @return string
*/
public function getStationName(): string
{
return $this->stationName;
}
/**
* @param string $stationName
*/
public function setStationName(string $stationName): void
{
$this->stationName = $stationName;
}
/**
* @return string
*/
public function getTime(): string
{
return $this->time;
}
/**
* @param string $time
*/
public function setTime(string $time): void
{
$this->time = $time;
}
/**
* @return string
*/
public function getRemark(): string
{
return $this->remark;
}
/**
* @param string $remark
*/
public function setRemark(string $remark): void
{
$this->remark = $remark;
}
/**
* @return int
*/
public function getWaitingTime(): int
{
return $this->waitingTime;
}
/**
* @param int $waitingTime
*/
public function setWaitingTime(int $waitingTime): void
{
$this->waitingTime = $waitingTime;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/2
* Time: 上午11:01
*/
namespace Lib\api\message;
use GuzzleHttp\Client;
use Lib\Log;
class Push
{
const URI = 'https://cdzback2.test.senthink.com';
const PATH = 'api/v1/wechatMessage';
/**
* @param MessageData $messageData
* @param string $userId
* @return bool
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function push(MessageData $messageData, string $userId)
{
$client = new Client([
'base_uri' => self::URI,
]);
$response = $client->request('POST', self::PATH, [
'form_params' => [
'userId' => $userId,
'templateId' => $messageData->getTemplateId(),
'data' => $messageData->getPushDataJson(),
],
'http_errors' => false,
]);
if ($response->getStatusCode() === 200) {
Log::debug('发送模版消息' . $messageData->getTemplateId(), json_decode($response->getBody(), true));
}
Log::debug($response->getStatusCode());
return $response->getStatusCode() === 200;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/5/28
* Time: 下午3:00
*/
namespace Lib\rabbit_mq;
class MyRabbitMq
{
const CONNECTION = [
'host' => 'rabbitmq.default.svc.cluster.local',
'port' => '5672',
'login' => 'rabbitmq',
'password' => 'senthink123!',
'vhost' => 'cdz_gateway',
];
/**
* @var \AMQPConnection
*/
protected $connection;
/**
* @var \AMQPChannel
*/
protected $channel;
/**
* @var string
*/
protected $routeKey;
/**
* @var string
*/
protected $exchangeKey;
/**
* @var \AMQPExchange
*/
protected $exchange;
/**
* @var \AMQPQueue
*/
protected $queue;
/**
* MyRabbitMq constructor.
* @throws \AMQPConnectionException
* @throws \AMQPExchangeException
*/
public function __construct()
{
$this->connection = new \AMQPConnection(self::CONNECTION);
if (!$this->connection->connect()) {
throw new \Exception('amqp connect fail');
} else {
$this->channel = new \AMQPChannel($this->connection);
$this->exchange = new \AMQPExchange($this->channel);
}
}
/**
* @return \AMQPQueue
* @throws \AMQPConnectionException
* @throws \AMQPQueueException
*/
public function getQueue()
{
return $this->queue = new \AMQPQueue($this->channel);
}
/**
* @throws \AMQPConnectionException
*/
public function getChannel()
{
$this->channel = new \AMQPChannel($this->connection);
}
/**
* @return \AMQPConnection
*/
public function getConnection(): \AMQPConnection
{
return $this->connection;
}
/**
* @param \AMQPConnection $connection
*/
public function setConnection(\AMQPConnection $connection)
{
$this->connection = $connection;
}
/**
* @return string
*/
public function getRouteKey(): string
{
return $this->routeKey;
}
/**
* @param string $routeKey
*/
public function setRouteKey(string $routeKey)
{
$this->routeKey = $routeKey;
}
/**
* @return string
*/
public function getExchangeKey(): string
{
return $this->exchangeKey;
}
/**
* @param string $exchangeKey
*/
public function setExchangeKey(string $exchangeKey)
{
$this->exchangeKey = $exchangeKey;
}
/**
* @return \AMQPExchange
*/
public function getExchange(): \AMQPExchange
{
return $this->exchange;
}
/**
* @param \AMQPExchange $exchange
*/
public function setExchange(\AMQPExchange $exchange)
{
$this->exchange = $exchange;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/7
* Time: 上午9:39
*/
namespace Lib\send;
abstract class Command
{
/**
* @var string
*/
protected $headerCtrl = '';
/**
* @var string
*/
protected $messageBody = '';
/**
* @var string
*/
protected $clientId = '';
/**
* @var string
*/
protected $clientUid = '';
abstract public function getMessageBody(): string;
abstract public function getClientId(): string;
abstract public function getClientUid(): string;
/**
* @return string
*/
public function getHeaderCtrl(): string
{
return $this->headerCtrl;
}
/**
* @param string $headerCtrl
*/
public function setHeadCtrl(string $headerCtrl)
{
$this->headerCtrl = $headerCtrl;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/7
* Time: 上午9:39
*/
namespace Lib\send;
use Lib\Gateway;
use Lib\tool\Crc;
use Lib\tool\StringTool;
class Send
{
/**
* 数据头标识符
*/
const PREAMBLE = 'ffaa';
/**
* @var string
*/
private $headerFlag = '04';
/**
* @var string
*/
private $headerCtrl = '';
/**
* @var string
*/
private $length;
/**
* @var string
*/
private $nonce;
/**
* @var Command
*/
private $command;
/**
* Send constructor.
*
* @param Command $command
*/
public function __construct(Command $command)
{
$this->command = $command;
$this->headerCtrl = $command->getHeaderCtrl();
$this->nonce = StringTool::padded(rand(0, 255), 2);
}
/**
* @param Command $command
*/
public function setCommand(Command $command): void
{
$this->command = $command;
$this->headerCtrl = $command->getHeaderCtrl();
$this->nonce = StringTool::padded(rand(0, 255), 2);
}
/**
* 发送至下位机
* @return bool
*/
public function send()
{
$result = false;
$clientUid = $this->command->getClientUid();
$message = $this->makeMessage();
//debug
if (Gateway::isUidOnline($clientUid) === 1) {
var_dump(['send_message' => $message,'time' => date('Y-m-d H:i:s')]);
Gateway::sendToUid($clientUid, $message);
$result = true;
}
return $result;
}
/**
* 按命令生成发送的message
* @return string
*/
public function makeMessage()
{
$body = $this->command->getMessageBody();
$length = 8;
$length += strlen($body) / 2;
$this->length = StringTool::padded($length, 4);
$message = self::PREAMBLE . $this->headerFlag . $this->headerCtrl . $this->length . $this->nonce . $body;
$crc = Crc::crc($message);
$mic = substr($crc, 0, 2);
$message .= $mic;
return $message;
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/5/30
* Time: 下午4:52
*/
namespace Lib\send\command;
use Lib\balance\BalanceOrder;
class BalanceChargerCommand extends Command
{
/**
* @var string
*/
protected $headerCtrl = '04';
/**
* @var BalanceOrder
*/
private $balanceOrder;
/**
* BalanceChargerCommand constructor.
* @param BalanceOrder $balanceOrder
*/
public function __construct(BalanceOrder $balanceOrder) {
$this->clientUid = $balanceOrder->getGatewayMac();
$this->balanceOrder = $balanceOrder;
}
/**
* @return string
*/
public function getMessageBody(): string
{
$portLogic = $this->balanceOrder->getPortLogic();
$orderId = sprintf('%08x',$this->balanceOrder->getOrderId());
$time = sprintf('%04x',$this->balanceOrder->getTime());
return '01'.$portLogic.$orderId.$time;
}
public function getClientId(): string
{
// TODO: Implement getClientId() method.
}
public function getClientUid(): string
{
return $this->balanceOrder->getGatewayMac();
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/7
* Time: 上午9:41
*/
namespace Lib\send\command;
use Illuminate\Support\Str;
use Lib\tool\StringTool;
use Lib\wx\pay_notify\order\ChargerOrder;
use Lib\wx\pay_notify\order\ChargerOrderTime;
use Log;
/**
* 充电命令
* Class ChargerCommand
* @package Lib\send\command
*/
class ChargerCommand extends Command
{
protected $headerCtrl = '04';
/**
* @var int
*/
private $type = 0;
/**
* @var int
*/
private $portLogicId;
/**l
* @var string
*/
private $outTradeNo;
/**
* @var int
*/
private $time;
/**
* ChargerCommand constructor.
* @param ChargerOrder $chargerOrder
* @throws \Exception
*/
public function __construct(ChargerOrder $chargerOrder)
{
$this->type = $chargerOrder->getChargerType();
// 获取端口的逻辑地址
$this->portLogicId = $chargerOrder->getPort()->getLogicNum();
$this->clientUid = $chargerOrder->getGateway()->getMacAddress();
$this->outTradeNo = $chargerOrder->getOrderId();
if ($this->type === 1) {
if ($chargerOrder instanceof ChargerOrderTime) {
$this->time = $chargerOrder->getChargerTime();
$this->clientUid = $chargerOrder->getGateway()->getMacAddress();
}
}
}
public function getMessageBody(): string
{
switch ($this->type) {
case 1 :
$this->messageBody = StringTool::padded($this->type, 2) . StringTool::padded($this->portLogicId, 2) . StringTool::padded($this->outTradeNo, 12) . StringTool::padded($this->time, 4);
break;
default:
break;
}
Log::debug('messageBody',[$this->messageBody]);
return $this->messageBody;
}
public function getClientId(): string
{
return $this->clientId;
}
public function getClientUid(): string
{
return $this->clientUid;
}
/**
* @return int
*/
public function getType(): int
{
return $this->type;
}
/**
* @param int $type
*/
public function setType(int $type)
{
$this->type = $type;
}
/**
* @return int
*/
public function getPortLogicId(): int
{
return $this->portLogicId;
}
/**
* @param int $portLogicId
*/
public function setPortLogicId(int $portLogicId)
{
$this->portLogicId = $portLogicId;
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->outTradeNo;
}
/**
* @param string $outTradeNo
*/
public function setOutTradeNo(string $outTradeNo)
{
$this->outTradeNo = $outTradeNo;
}
/**
* @return int
*/
public function getTime(): int
{
return $this->time;
}
/**
* @param int $time
*/
public function setTime(int $time)
{
$this->time = $time;
}
/**
* @param mixed $sendContent
*/
public function setSendContent($sendContent)
{
$this->sendContent = $sendContent;
}
/**
* @param mixed $clientId
*/
public function setClientId($clientId)
{
$this->clientId = $clientId;
}
/**
* @param mixed $clientUid
*/
public function setClientUid($clientUid)
{
$this->clientUid = $clientUid;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/6/7
* Time: 上午10:41
*/
namespace Lib\send\command;
use Lib\tool\StringTool;
class SimpleChargerCommand extends Command
{
protected $headerCtrl = '04';
/**
* @var string
*/
private $gatewayMac;
/**
* @var int
*/
private $orderId;
/**
* @var int
*/
private $chargerTime;
/**
* @var int
*/
private $logicNum;
/**
* @var int
*/
private $type = 1;
public function getMessageBody(): string
{
return $this->messageBody = StringTool::padded($this->type, 2) . StringTool::padded($this->logicNum, 2) . StringTool::padded($this->orderId
, 12) . StringTool::padded($this->chargerTime, 4);
}
public function getClientId(): string
{
// TODO: Implement getClientId() method.
}
public function getClientUid(): string
{
return $this->gatewayMac;
// TODO: Implement getClientUid() method.
}
/**
* @return string
*/
public function getGatewayMac(): string
{
return $this->gatewayMac;
}
/**
* @param string $gatewayMac
*/
public function setGatewayMac(string $gatewayMac): void
{
$this->gatewayMac = $gatewayMac;
}
/**
* @return int
*/
public function getOrderId(): int
{
return $this->orderId;
}
/**
* @param int $orderId
*/
public function setOrderId(int $orderId): void
{
$this->orderId = $orderId;
}
/**
* @return int
*/
public function getChargerTime(): int
{
return $this->chargerTime;
}
/**
* @param int $chargerTime
*/
public function setChargerTime(int $chargerTime): void
{
$this->chargerTime = $chargerTime;
}
/**
* @return int
*/
public function getLogicNum(): int
{
return $this->logicNum;
}
/**
* @param int $logicNum
*/
public function setLogicNum(int $logicNum): void
{
$this->logicNum = $logicNum;
}
/**
* @return int
*/
public function getType(): int
{
return $this->type;
}
/**
* @param int $type
*/
public function setType(int $type): void
{
$this->type = $type;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/5/30
* Time: 上午10:45
*/
namespace Lib\send\command;
use Lib\tool\Crc;
use Lib\send\Command;
class StopChargerCommand extends Command
{
/**
* @var int
*/
private $orderId;
/**
* @var int
*/
private $logicNum;
/**
* @var string
*/
private $gatewayMac;
protected $headerCtrl = '05';
public function getMessageBody(): string
{
$logicNum = sprintf('%02x',$this->logicNum);
$orderId = sprintf('%012x',$this->orderId);
return $this->messageBody = $logicNum.$orderId;
}
public function getClientId(): string
{
// TODO: Implement getClientId() method.
}
public function getClientUid(): string
{
return $this->gatewayMac;
}
/**
* @return int
*/
public function getOrderId(): int
{
return $this->orderId;
}
/**
* @param int $orderId
*/
public function setOrderId(int $orderId): void
{
$this->orderId = $orderId;
}
/**
* @return int
*/
public function getLogicNum(): int
{
return $this->logicNum;
}
/**
* @param int $logicNum
*/
public function setLogicNum(int $logicNum): void
{
$this->logicNum = $logicNum;
}
/**
* @return string
*/
public function getGatewayMac(): string
{
return $this->gatewayMac;
}
/**
* @param string $gatewayMac
*/
public function setGatewayMac(string $gatewayMac): void
{
$this->gatewayMac = $gatewayMac;
}
/**
* @return string
*/
public function getHeaderCtrl(): string
{
return $this->headerCtrl;
}
/**
* @param string $headerCtrl
*/
public function setHeaderCtrl(string $headerCtrl): void
{
$this->headerCtrl = $headerCtrl;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/1
* Time: 下午1:20
*/
namespace Lib\tool;
class ArrayToXml
{
/**
* @var array
*/
private $data;
/**
* @var string
*/
private $xml = '';
/**
* ArrayToXml constructor.
* @param array $data
*
*/
public function __construct(array $data =[])
{
$this->data = $data;
}
/**
* @param $data
* @return string
*/
public function arrayToXml($data)
{
foreach ($data as $key => $value)
{
if(blank($value))
{
continue;
}
$this->xml.="<$key>";
if(is_array($value))
{
$this->arrayToXml($value);
}else{
$this->xml.="<![CDATA[$value]]></$key>";
}
}
return '<xml>'.$this->xml.'</xml>';
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/4/25
* Time: 下午3:52
*/
namespace Lib\tool;
class Crc
{
const CRC_TABLE = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
/**
* @param $data
* @return int
*/
public static function crc($data)
{
$crc = 0xffffffff;
$size = strlen($data);
for($i=0;$i<$size;$i+=2)
{
$numHex = substr($data,$i,2);
$number = hexdec($numHex);
$tmp = ($crc^$number) & 0xff;
$crcRightMove = (hexdec(sprintf("%08x",$crc>>8)));
$crc = ($crcRightMove)^(self::CRC_TABLE[$tmp]);
}
$crc = $crc ^ 0xffffffff;
return sprintf('%08x',$crc);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/7
* Time: 上午9:50
*/
namespace Lib\tool;
class StringTool
{
public static function padded(string $str,int $length,string $need = '0')
{
return sprintf("%0$length"."x",(int)$str);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/5/23
* Time: 上午9:47
*/
namespace Lib\wx;
use GuzzleHttp\Client;
use Lib\tool\ArrayToXml;
use Lib\wx\Wx;
/**
* 微信退款
* Class Refund
* @package Lib\wx\refund
*/
class Refund
{
const URL = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
/**
* @var array
*/
private $requestParameters = [
'appid' => Wx::APP_ID,
'mch_id' => Wx::MCH_ID,
'nonce_str' => '',
'sign' => '',
'sign_type' => '',
'transaction_id' => '',
'out_trade_no' => '',
'out_refund_no' => '',
'total_fee' => '',
'refund_desc' => '',
'refund_fee' => '',
'notify_url' => '',
'cash_fee' => '',
];
/**
* @var string
*/
private $sign;
/**
* @var string
*/
private $signType;
/**
* @var string
*/
private $transactionId;
/**
* @var string
*/
private $outTradeNo;
/**
* @var string
*/
private $outRefundNo;
/**
* @var int
*/
private $totalFee;
/**
* @var int
*/
private $refundFee;
/**
* @var string
*/
private $refundDesc;
/**
* @var string
*/
private $notifyUrl;
/**
* @return bool
*/
public function refund()
{
$result = false;
$this->requestParameters['nonce_str'] = str_random(32);
$this->requestParameters['sign_type'] = 'MD5';
$this->requestParameters['transaction_id'] = $this->transactionId;
$this->requestParameters['out_trade_no'] = $this->outTradeNo;
$this->requestParameters['out_refund_no'] = $this->outRefundNo;
$this->requestParameters['total_fee'] = $this->totalFee;
$this->requestParameters['refund_desc'] = $this->refundDesc;
$this->requestParameters['refund_fee'] = $this->refundFee;
$this->requestParameters['notify_url'] = $this->notifyUrl;
$this->requestParameters['sign'] = $this->sign = Wx::sign($this->requestParameters);
$this->requestParameters = array_filter($this->requestParameters, function ($value, $key) {
return filled($value);
}, ARRAY_FILTER_USE_BOTH);
$arrayToXml = new ArrayToXml();
$requestXml = Wx::arrayToXml($this->requestParameters);
$client = new Client();
$response = $client->post(self::URL, [
'http_errors' => false,
'Content-Type' => 'text/xml; charset=UTF8', 'body' => $requestXml,
'ssl_key' => WX::SSLKEY_PATH,
'cert' => WX::SSLCERT_PATH,
]);
if ($response->getStatusCode() === 200) {
$data = Wx::xmlToArray($response->getBody()->getContents());
if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
$result = true;
} else {
var_dump($data);
}
}
return $result;
}
/**
* @return string
*/
public function getSign(): string
{
return $this->sign;
}
/**
* @param string $sign
*/
public function setSign(string $sign): void
{
$this->sign = $sign;
}
/**
* @return string
*/
public function getSignType(): string
{
return $this->signType;
}
/**
* @param string $signType
*/
public function setSignType(string $signType): void
{
$this->signType = $signType;
}
/**
* @return string
*/
public function getTransactionId(): string
{
return $this->transactionId;
}
/**
* @param string $transactionId
*/
public function setTransactionId(string $transactionId): void
{
$this->transactionId = $transactionId;
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->outTradeNo;
}
/**
* @param string $outTradeNo
*/
public function setOutTradeNo(string $outTradeNo): void
{
$this->outTradeNo = $outTradeNo;
}
/**
* @return string
*/
public function getOutRefundNo(): string
{
return $this->outRefundNo;
}
/**
* @param string $outRefundNo
*/
public function setOutRefundNo(string $outRefundNo): void
{
$this->outRefundNo = $outRefundNo;
}
/**
* @return int
*/
public function getTotalFee(): int
{
return $this->totalFee;
}
/**
* @param int $totalFee
*/
public function setTotalFee(int $totalFee): void
{
$this->totalFee = $totalFee;
}
/**
* @return int
*/
public function getRefundFee(): int
{
return $this->refundFee;
}
/**
* @param int $refundFee
*/
public function setRefundFee(int $refundFee): void
{
$this->refundFee = $refundFee;
}
/**
* @return string
*/
public function getRefundDesc(): string
{
return $this->refundDesc;
}
/**
* @param string $refundDesc
*/
public function setRefundDesc(string $refundDesc): void
{
$this->refundDesc = $refundDesc;
}
/**
* @return string
*/
public function getNotifyUrl(): string
{
return $this->notifyUrl;
}
/**
* @param string $notifyUrl
*/
public function setNotifyUrl(string $notifyUrl): void
{
$this->notifyUrl = $notifyUrl;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/4/28
* Time: 下午1:54
*/
namespace Lib\wx;
use Lib\tool\ArrayToXml;
/**
* 微信公共类
* Class Wx
* @package Lib\wx
*/
class Wx
{
const APP_ID = 'wx2d049ccbde322c2e';
// const APP_ID = 'wx72a0a0591e4e2539';
const APP_SECRET = '41e2827de3927f2c3de392c2800b90bf';
// const APP_SECRET = '075401bcb54ae99b62cd9755f4bd939f';
const APP_KEY = 'nLvB2fg9cJodrxEzCu9JKG0m6eM0eJ0u';
// const APP_KEY = 'senthink2015senthink2015senthink';
const LANG = 'zh_CN';
const MCH_ID = '1480201542';
// const MCH_ID = '1420618402';
const SSLCERT_PATH = __DIR__ . '/cert/apiclient_cert.pem';
const SSLKEY_PATH = __DIR__ . '/cert/apiclient_key.pem';
/**
* 生成签名
*
* @param array $content
*
* @return string
*/
public static function sign(array $content)
{
$content = array_filter($content, function ($value)
{
return filled($value);
});
ksort($content);
$str = '';
foreach ($content as $key => $value) {
if (!empty($value)) {
$str .= $key . '=' . $value . '&';
}
}
//$str = trim($str,'&');
$str .= 'key=' . self::APP_KEY;
return strtoupper(md5($str));
}
/**
* 验签
*
* @param array $response
*
* @return bool
*/
public static function validateSign(array $response)
{
if (!isset($response['sign'])) {
throw new Exception('response does not have sign');
}
$responseSign = $response['sign'];
unset($response['sign']);
$validateSign = Wx::sign($response);
return $responseSign === $validateSign;
}
/**
* @param string $xml
*
* @return mixed
*/
public static function xmlToArray(string $xml)
{
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXmlElement', LIBXML_NOCDATA)), true);
}
/**
* @param array $content
*
* @return string
*/
public static function arrayToXml(array $content)
{
$arrayToXml = new ArrayToXml();
return $arrayToXml->arrayToXml($content);
}
}
-----BEGIN CERTIFICATE-----
MIIEYzCCA8ygAwIBAgIEAQ/xYjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMC
Q04xEjAQBgNVBAgTCUd1YW5nZG9uZzERMA8GA1UEBxMIU2hlbnpoZW4xEDAOBgNV
BAoTB1RlbmNlbnQxDDAKBgNVBAsTA1dYRzETMBEGA1UEAxMKTW1wYXltY2hDQTEf
MB0GCSqGSIb3DQEJARYQbW1wYXltY2hAdGVuY2VudDAeFw0xNzA1MTgxMDAwMzha
Fw0yNzA1MTYxMDAwMzhaMIGSMQswCQYDVQQGEwJDTjESMBAGA1UECBMJR3Vhbmdk
b25nMREwDwYDVQQHEwhTaGVuemhlbjEQMA4GA1UEChMHVGVuY2VudDEOMAwGA1UE
CxMFTU1QYXkxJzAlBgNVBAMUHuadreW3nui0pOiKr+enkeaKgOaciemZkOWFrOWP
uDERMA8GA1UEBBMIMjc5MDI0MzAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQC+F/hyVGOyJOhfCiY26GmPAR9TXKshrYJvcRR9YA3eWR3rZpZv3giTi2xA
PfMEsM84euL9LlpojshUbuNaCiQDa6mPWWk/Husv8FozOKTkrd/wPjC/Igdi8JvM
qXxubrDHpCPY2P2NNw0qqFdF1GmaTqe+4mTLQ+a8iSgVLAjs9cI+TNce9poh69aH
tb4fEdCYUhbEkcptP4NItLHT3ghXe2zayR0oYmnB4dh8Wtuo1jlgfNEc4PsdsqKe
l0WNOTmKPXBvR6/scKO+lRRojK3K1SKY1ZNHai2z5Xl9TQtjEyy/zjiRtDhyUFWq
X7l6IpSjwkl0X6cnJ2LH/LPF9bQrAgMBAAGjggFGMIIBQjAJBgNVHRMEAjAAMCwG
CWCGSAGG+EIBDQQfFh0iQ0VTLUNBIEdlbmVyYXRlIENlcnRpZmljYXRlIjAdBgNV
HQ4EFgQUh1bd51EIjvAOvU3clijvYpwBCFYwgb8GA1UdIwSBtzCBtIAUPgUm9iJi
tBVbiM1kfrDUYqflhnShgZCkgY0wgYoxCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlH
dWFuZ2RvbmcxETAPBgNVBAcTCFNoZW56aGVuMRAwDgYDVQQKEwdUZW5jZW50MQww
CgYDVQQLEwNXWEcxEzARBgNVBAMTCk1tcGF5bWNoQ0ExHzAdBgkqhkiG9w0BCQEW
EG1tcGF5bWNoQHRlbmNlbnSCCQC7VJcrvADoVzAOBgNVHQ8BAf8EBAMCBsAwFgYD
VR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQEFBQADgYEAJr/FrHcMbN6X
BCkJ/CBhd8TVE//cHaj1yZu9hJwwAkvkz81WfOv/XARP6fqGj5IPAmxx2dpufX/O
ZXej8QPQh/ygUCn8QcE8/OavvsKR3RmByM8iBE5bLm3mXf2dtp8aHCz4HhF2bh/H
pmzMIWf+afXJ0f9iHJmLVbNcitBxgVs=
-----END CERTIFICATE-----
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+F/hyVGOyJOhf
CiY26GmPAR9TXKshrYJvcRR9YA3eWR3rZpZv3giTi2xAPfMEsM84euL9LlpojshU
buNaCiQDa6mPWWk/Husv8FozOKTkrd/wPjC/Igdi8JvMqXxubrDHpCPY2P2NNw0q
qFdF1GmaTqe+4mTLQ+a8iSgVLAjs9cI+TNce9poh69aHtb4fEdCYUhbEkcptP4NI
tLHT3ghXe2zayR0oYmnB4dh8Wtuo1jlgfNEc4PsdsqKel0WNOTmKPXBvR6/scKO+
lRRojK3K1SKY1ZNHai2z5Xl9TQtjEyy/zjiRtDhyUFWqX7l6IpSjwkl0X6cnJ2LH
/LPF9bQrAgMBAAECggEBAJOlnKR4pYLdpdsD0BC/zhVz4rfl90nOMcyLQUXsUHlO
MK4BXYGALJslJKx1MYeIKTuOPzY1RaWGmVTzWAU8cSJzAh1EbjnHsxbmEblNGs4/
uvsn4sbiEGipx+lcDzjbItW9yNYKHE4N310tqbOkO23N//6Ea5NxpwrzYT2omToq
hbPTnyYr6eOZlB42qv8n7ToUAJqp7yd9tPGSmGWjikgVmjZBLvss2KUfSYmNigON
hpQibLXkl+7wN8eEe1jEIT5tnJmfQuN/CDnAuRjzQlB3+7RGC306dLqLZrhQqHsf
N/owFIyUzcgx38EbVqc9lzB1/9vMmYgeW+hUwrv6xIkCgYEA4WHOeq08yDrT4GVR
F+stQ9UpnuydJJruM26DRA0pls2d6rhZyMhMsQua4M6jA1RmPJgb9XPxsniYJ6n4
fc3FJMRqLjJxMRo+cf1rebszqDEkXbFqMqye19LlvMBAALxIi0upFdi0Njzng28W
8eCNhUSqP1nRq1Rt1n2dT7Qnru8CgYEA1+rs+ldY98J+c9B+gM6BSYHWiNGXTqTL
U9le4KqeA4hEPifo35su++Wba0j1UZznthWWEUY5wGl6D6eJasHYTW25kxm9brV1
s8zLlaZM0dyRI8sKhEUq+G6Mp0Kjk2p8/Bo8/YYIWaafdqPvlqh7g8Qxxarx5Ye9
iTgg4gqlToUCgYBTCcgbZsxoMVRy7qFMILfSsCzfgun63KI6jNMMNZVHHIa8PiPG
WBX5fP8ZKMjipyvr01cpvggk602T/4mwQCoMe9lrH+aYYsTzFp2Mgi5sH374ji9E
cFktx2QhgOuT2csYl0264Na0zQe3Yyye/U7m9P+My7j2WOsHBcz52rRsPQKBgBHi
5zCxza/wj7MeYWxgLvuc4t3Apw0fv6w5hI+N8rsOLcEMY1EqtNCvK5nOmGvjWJqP
3TefHqee1Tq4wTxzxGxdm5Lg/f1O0OpNG8xQ02pLIEbbygo9BJtB5Srx7UUH/ESS
E91YnhZ3JBya5f0QBfNbbFgYmiNOhFf6q1auVRVVAoGAOnaj/hNeFZuiXPclZCvm
iiJMk7vfdAOU44GxyhRWTByE0YiCzFiBUI6dmY4A+FYW5wVg2wp44JXtqBs4gMBz
2ypfJ+pQRF1sCZNvnKSGMa8Rr7LSKuWqtQ78arqHBGXzTV7hJt1Ex7/JRBFYZ7kZ
tr7Vdsg9XxsthkOg2CnaXFI=
-----END PRIVATE KEY-----
{
"autoload" :{
"psr-4" : {
"Lib\\" : "Lib/"
}
},
"require": {
"illuminate/database": "^5.6",
"guzzlehttp/guzzle": "^6.3",
"monolog/monolog": "^1.23"
}
}
This diff is collapsed. Click to expand it.
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/5/28
* Time: 下午2:59
*/
require_once __DIR__ . '/vendor/autoload.php';
use Lib\rabbit_mq\MyRabbitMq;
use Lib\wx\Refund;
use Lib\send\Send;
use Lib\send\command\StopChargerCommand;
use Lib\Log;
try {
$rabbitMq = new MyRabbitMq();
} catch (AMQPConnectionException $e) {
} catch (AMQPExchangeException $e) {
}
try {
$queue = $rabbitMq->getQueue();
$queue->setName('queue_worker_check_order');
$queue->setFlags(AMQP_DURABLE);
} catch (Exception $exception) {
Log::debug($exception->getMessage());
}
try {
$queue->declareQueue();
} catch (AMQPChannelException $e) {
} catch (AMQPConnectionException $e) {
}
try {
$queue->bind('cdz_gateway', 'worker_check_order');
} catch (AMQPChannelException $e) {
} catch (AMQPConnectionException $e) {
}
try {
$queue->consume(function (AMQPEnvelope $envelope, AMQPQueue $queue) {
$dsn = 'mysql:dbname=cdzpay;host=db.test.senthink.com';
$user = 'cdz';
$password = 'senthink123';
try {
$dbh = new PDO($dsn, $user, $password, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
Log::error('connnection failed');
}
$data = json_decode($envelope->getBody(), true);
Log::debug('data',$data);
$orderId = $data['order_id'];
$outTradeNo = $data['out_trade_no'];
$totalFee = $data['total_fee'];
$logicNum = $data['logic_num'];
$gatewayMac = $data['gateway_mac'];
$orderInfo = $dbh->query('SELECT is_charger,port_id ,state FROM wx_charger_orders WHERE id = ' . $orderId);
$orderInfo = $orderInfo->fetch();
$isCharger = $orderInfo['is_charger'];
$portId = (int)$orderInfo['port_id'];
if($orderInfo['state'] === 3)//如果已经退款直接抛弃
{
$queue->ack($envelope->getDeliveryTag());
return ;
}
//todo 订单的端口id是否和消息中的相同,如果不同则发生过端口改变,无视该条消息
switch ($isCharger) {
case -1:
//todo 退款
$refundDesc = '充电失败';
break;
case 13:
//todo 退款
$refundDesc = '充电口打开失败';
break;
case 14:
//todo 退款
$refundDesc = '充电口打开成功,但未插上插头';
break;
break;
}
if ((int)$isCharger !== 12 && $portId === $data['port_id']) {
if ($data['pay_type'] === 1) {
Log::debug('退款');
$openId = $data['openid'];
$refund = new Refund();
$refund->setRefundDesc($refundDesc);
$refund->setOutTradeNo($outTradeNo);
$refund->setTotalFee($totalFee);
$refund->setRefundFee($totalFee);
$outRefundNo = time() . $totalFee . rand(10000, 999999);
$refund->setOutRefundNo($outRefundNo);
if ($refund->refund() === true) {
try {
$dbh->beginTransaction();
$sql = "UPDATE wx_charger_orders SET `refund_amount`=?, `state`=?, `refund_type`=? WHERE id= ?";
$insertRefundRecord = "INSERT INTO wx_refund_orders (`out_refund_no`,`refund_amount`,`gateway_id`,`port_id`,`station_id`,`out_trade_no`,`total_fee`,`created_at`,`desc`) VALUES (?,?,?,?,?,?,?,?,?)";
$result = $dbh->prepare($sql);
$result = $result->execute([$totalFee, 3, 1, $orderId]);
$insert = $dbh->prepare($insertRefundRecord);
$insert = $insert = $insert->execute([
$outRefundNo,
$totalFee,
$data['gateway_id'],
$data['port_id'],
$data['station_id'],
$outTradeNo,
$totalFee,
date('Y-m-d H:i:s'),
'端口未检测到电动自行车,系统自动退款',
]);
$dbh->commit();
} catch (PDOException $exception) {
$dbh->rollBack();
Log::debug($exception->getMessage());
}
}
} else {
$userId = $data['user_id'];
// 余额支付需要将余额加回钱包,消费金额减小.
try {
$dbh->beginTransaction();
$sql = "UPDATE wx_users SET `wallet_balance` = `wallet_balance` + ?, `total_cost` = `total_cost` - ? ,`current_cost` = `current_cost` - ? WHERE id = ?";
$updateBalance = $dbh->prepare($sql);
$updateBalance->execute([$totalFee, $totalFee, $totalFee, $userId]);
$updateOrder = "UPDATE wx_charger_orders SET `state` = ?, `refund_type` = ?,`refund_amount` = ? WHERE id = ?";
$updateOrder = $dbh->prepare($updateOrder);
$result = $updateOrder->execute([3, 1, $totalFee, $orderId]);
$insertRefundRecord = "INSERT INTO wx_refund_orders (`out_refund_no`,`refund_amount`,`gateway_id`,`port_id`,`station_id`,`out_trade_no`,`total_fee`,`created_at`,`desc`) VALUES (?,?,?,?,?,?,?,?,?)";
$insert = $dbh->prepare($insertRefundRecord);
$outRefundNo = time() . $totalFee . rand(10000, 999999);
$insert = $insert = $insert->execute([
$outRefundNo,
$totalFee,
$data['gateway_id'],
$data['port_id'],
$data['station_id'],
$outTradeNo,
$totalFee,
date('Y-m-d H:i:s'),
'端口未检测到电动自行车,系统自动退款',
]);
Log::debug($result);
$dbh->commit();
} catch (PDOException $exception) {
Log::debug($exception->getMessage());
}
}
$stopCommand = new StopChargerCommand();
$stopCommand->setOrderId($orderId);
$stopCommand->setGatewayMac($gatewayMac);
$stopCommand->setLogicNum($logicNum);
$send = new Send($stopCommand);
if ($send->send() === false) {
Log::debug('结束订单命令发送失败');
}else{
Log::debug('发送结束充电命令'.$orderId);
}
//todo 更新订单表和存储退款表
}else{
$stopCommand = new StopChargerCommand();
$stopCommand->setOrderId($orderId);
$stopCommand->setGatewayMac($gatewayMac);
$stopCommand->setLogicNum($logicNum);
$send = new Send($stopCommand);
echo '已更改过口子,此消息作废处理'.PHP_EOL;
}
unset($dbh);
Log::debug(['message' => json_decode($envelope->getBody(),true), 'time' => date('H:i:s')]);
$queue->ack($envelope->getDeliveryTag());
//$queue->ack($envelope->getDeliveryTag());
});
} catch (AMQPChannelException $e) {
} catch (AMQPConnectionException $e) {
} catch (AMQPEnvelopeException $e) {
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/7/5
* Time: 下午4:52
*/
require_once __DIR__ . '/vendor/autoload.php';
use Lib\rabbit_mq\MyRabbitMq;
use Lib\send\command\StopChargerCommand;
use Lib\Log;
use Lib\send\Send;
use Lib\api\message\ChargerTimeoutMessage;
use Lib\api\message\Push;
try {
$rabbitMq = new MyRabbitMq();
} catch (AMQPConnectionException $e) {
} catch (AMQPExchangeException $e) {
}
try {
$queue = $rabbitMq->getQueue();
$queue->setName('queue_worker_check_port_charger_state');
$queue->setFlags(AMQP_DURABLE);
} catch (Exception $exception) {
Log::error($exception->getMessage());
}
try {
$queue->declareQueue();
} catch (AMQPChannelException $e) {
} catch (AMQPConnectionException $e) {
}
try {
$queue->bind('cdz_gateway', 'worker_check_port_charger_state');
} catch (AMQPChannelException $e) {
} catch (AMQPConnectionException $e) {
}
Log::info('启动消费者');
try {
$queue->consume(function (AMQPEnvelope $envelope, AMQPQueue $queue) {
$dsn = 'mysql:dbname=cdzpay;host=db.test.senthink.com';
$user = 'cdz';
$password = 'senthink123';
try {
$dbh = new PDO($dsn, $user, $password, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$data = json_decode($envelope->getBody(), true);
Log::debug('body',$data);
$orderId = $data['order_id'];
$orderInfo = $dbh->query('SELECT is_stop,port_id,created_at,charger_time,wx_user_id FROM wx_charger_orders WHERE id = ' . $orderId);
$orderInfo = $orderInfo->fetch();
//todo 查询口子状态是否为插口脱落,是则下发结束充电命令。
if(isset($orderInfo['port_id'])) {
try {
$redis = new \Redis();
$redis->pconnect('redis.test.senthink.com', 6379, 1);
$redis->select(4);
$portId = $orderInfo['port_id'];
$redis->multi(2);
$redis->zScore('port:id_state:zset',$portId);
$redis->hGet('port:id_logic:hash',$portId);
$result = $redis->exec();
$portState = $result[0];
$logicNum = $result['1'];
if(!isset($logicNum))
{
Log::error('逻辑地址未找到');
return ;
}
if($portState == 14)
{
$gatewayMac = $data['gateway_mac'];
$stopCommand = new StopChargerCommand();
$stopCommand->setOrderId($orderId);
$stopCommand->setGatewayMac($gatewayMac);
$stopCommand->setLogicNum($logicNum);
$send = new Send($stopCommand);
if ($send->send() === false) {
Log::debug('结束订单命令发送失败');
}else{
Log::debug('发送结束充电命令'.$orderId);
}
$chargerTimeoutMessage = new ChargerTimeoutMessage();
$chargerTimeoutMessage->setStartTime($orderInfo['created_at']);
$chargerTimeoutMessage->setChargerTime($orderInfo['charger_time']);
$chargerTimeoutMessage->setFirst(date('Y-m-d H:i:s'));
$push = new Push();
$push->push($chargerTimeoutMessage,$orderInfo['wx_user_id']);
}
} catch (Exception $exception) {
Log::error($exception->getMessage());
}
}
$queue->ack($envelope->getDeliveryTag());
});
} catch (AMQPChannelException $e) {
} catch (AMQPConnectionException $e) {
} catch (AMQPEnvelopeException $e) {
}
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit8c119b004aa624b54e5609ed67b0bb28::getLoader();
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'72579e7bd17821bb1321b87411366eae' => $vendorDir . '/illuminate/support/helpers.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
);
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'Lib\\' => array($baseDir . '/Lib'),
'Illuminate\\Support\\' => array($vendorDir . '/illuminate/support'),
'Illuminate\\Database\\' => array($vendorDir . '/illuminate/database'),
'Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'),
'Illuminate\\Container\\' => array($vendorDir . '/illuminate/container'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib/Doctrine/Common/Inflector'),
'' => array($vendorDir . '/nesbot/carbon/src'),
);
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit8c119b004aa624b54e5609ed67b0bb28
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit8c119b004aa624b54e5609ed67b0bb28', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit8c119b004aa624b54e5609ed67b0bb28', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit8c119b004aa624b54e5609ed67b0bb28::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit8c119b004aa624b54e5609ed67b0bb28::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire8c119b004aa624b54e5609ed67b0bb28($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire8c119b004aa624b54e5609ed67b0bb28($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit8c119b004aa624b54e5609ed67b0bb28
{
public static $files = array (
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php',
'72579e7bd17821bb1321b87411366eae' => __DIR__ . '/..' . '/illuminate/support/helpers.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Component\\Translation\\' => 30,
),
'P' =>
array (
'Psr\\SimpleCache\\' => 16,
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
'Psr\\Container\\' => 14,
),
'M' =>
array (
'Monolog\\' => 8,
),
'L' =>
array (
'Lib\\' => 4,
),
'I' =>
array (
'Illuminate\\Support\\' => 19,
'Illuminate\\Database\\' => 20,
'Illuminate\\Contracts\\' => 21,
'Illuminate\\Container\\' => 21,
),
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
'GuzzleHttp\\Promise\\' => 19,
'GuzzleHttp\\' => 11,
),
'D' =>
array (
'Doctrine\\Common\\Inflector\\' => 26,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Component\\Translation\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/translation',
),
'Psr\\SimpleCache\\' =>
array (
0 => __DIR__ . '/..' . '/psr/simple-cache/src',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Container\\' =>
array (
0 => __DIR__ . '/..' . '/psr/container/src',
),
'Monolog\\' =>
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'Lib\\' =>
array (
0 => __DIR__ . '/../..' . '/Lib',
),
'Illuminate\\Support\\' =>
array (
0 => __DIR__ . '/..' . '/illuminate/support',
),
'Illuminate\\Database\\' =>
array (
0 => __DIR__ . '/..' . '/illuminate/database',
),
'Illuminate\\Contracts\\' =>
array (
0 => __DIR__ . '/..' . '/illuminate/contracts',
),
'Illuminate\\Container\\' =>
array (
0 => __DIR__ . '/..' . '/illuminate/container',
),
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
),
'GuzzleHttp\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
),
'GuzzleHttp\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
),
'Doctrine\\Common\\Inflector\\' =>
array (
0 => __DIR__ . '/..' . '/doctrine/inflector/lib/Doctrine/Common/Inflector',
),
);
public static $fallbackDirsPsr4 = array (
0 => __DIR__ . '/..' . '/nesbot/carbon/src',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit8c119b004aa624b54e5609ed67b0bb28::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit8c119b004aa624b54e5609ed67b0bb28::$prefixDirsPsr4;
$loader->fallbackDirsPsr4 = ComposerStaticInit8c119b004aa624b54e5609ed67b0bb28::$fallbackDirsPsr4;
}, null, ClassLoader::class);
}
}
inflector @ 5527a48b
Subproject commit 5527a48b7313d15261292c149e55e26eae771b0a
Copyright (c) 2011-2018 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Guzzle, PHP HTTP client
=======================
[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases)
[![Build Status](https://img.shields.io/travis/guzzle/guzzle.svg?style=flat-square)](https://travis-ci.org/guzzle/guzzle)
[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle)
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
trivial to integrate with web services.
- Simple interface for building query strings, POST requests, streaming large
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
etc...
- Can send both synchronous and asynchronous requests using the same interface.
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
to utilize other PSR-7 compatible libraries with Guzzle.
- Abstracts away the underlying HTTP transport, allowing you to write
environment and transport agnostic code; i.e., no hard dependency on cURL,
PHP streams, sockets, or non-blocking event loops.
- Middleware system allows you to augment and compose client behavior.
```php
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// '{"id": 1420053, "name": "guzzle", ...}'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
## Help and docs
- [Documentation](http://guzzlephp.org/)
- [Stack Overflow](http://stackoverflow.com/questions/tagged/guzzle)
- [Gitter](https://gitter.im/guzzle/guzzle)
## Installing Guzzle
The recommended way to install Guzzle is through
[Composer](http://getcomposer.org).
```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
```
Next, run the Composer command to install the latest stable version of Guzzle:
```bash
php composer.phar require guzzlehttp/guzzle
```
After installing, you need to require Composer's autoloader:
```php
require 'vendor/autoload.php';
```
You can then later update Guzzle using composer:
```bash
composer.phar update
```
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|------------|---------------------|--------------|---------------------|---------------------|-------|-------------|
| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >= 5.3.3 |
| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >= 5.4 |
| 5.x | Maintained | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >= 5.4 |
| 6.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >= 5.5 |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle
[guzzle-3-docs]: http://guzzle3.readthedocs.org/en/latest/
[guzzle-5-docs]: http://guzzle.readthedocs.org/en/5.3/
[guzzle-6-docs]: http://guzzle.readthedocs.org/en/latest/
{
"name": "guzzlehttp/guzzle",
"type": "library",
"description": "Guzzle is a PHP HTTP client library",
"keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"],
"homepage": "http://guzzlephp.org/",
"license": "MIT",
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"require": {
"php": ">=5.5",
"guzzlehttp/psr7": "^1.4",
"guzzlehttp/promises": "^1.0"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0",
"psr/log": "^1.0"
},
"autoload": {
"files": ["src/functions_include.php"],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\": "tests/"
}
},
"suggest": {
"psr/log": "Required for using the Log middleware"
},
"extra": {
"branch-alias": {
"dev-master": "6.3-dev"
}
}
}
<?php
namespace GuzzleHttp;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
interface ClientInterface
{
const VERSION = '6.3.3';
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []);
/**
* Asynchronously send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @return PromiseInterface
*/
public function sendAsync(RequestInterface $request, array $options = []);
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function request($method, $uri, array $options = []);
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @return PromiseInterface
*/
public function requestAsync($method, $uri, array $options = []);
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*/
public function getConfig($option = null);
}
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Cookie jar that stores cookies as an array
*/
class CookieJar implements CookieJarInterface
{
/** @var SetCookie[] Loaded cookie data */
private $cookies = [];
/** @var bool */
private $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
* cookies are added to the cookie jar.
* @param array $cookieArray Array of SetCookie objects or a hash of
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct($strictMode = false, $cookieArray = [])
{
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
if (!($cookie instanceof SetCookie)) {
$cookie = new SetCookie($cookie);
}
$this->setCookie($cookie);
}
}
/**
* Create a new Cookie jar from an associative array and domain.
*
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*
* @return self
*/
public static function fromArray(array $cookies, $domain)
{
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true
]));
}
return $cookieJar;
}
/**
* @deprecated
*/
public static function getCookieValue($value)
{
return $value;
}
/**
* Evaluate if this cookie should be persisted to storage
* that survives between requests.
*
* @param SetCookie $cookie Being evaluated.
* @param bool $allowSessionCookies If we should persist session cookies
* @return bool
*/
public static function shouldPersist(
SetCookie $cookie,
$allowSessionCookies = false
) {
if ($cookie->getExpires() || $allowSessionCookies) {
if (!$cookie->getDiscard()) {
return true;
}
}
return false;
}
/**
* Finds and returns the cookie based on the name
*
* @param string $name cookie name to search for
* @return SetCookie|null cookie that was found or null if not found
*/
public function getCookieByName($name)
{
// don't allow a null name
if ($name === null) {
return null;
}
foreach ($this->cookies as $cookie) {
if ($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) {
return $cookie;
}
}
}
public function toArray()
{
return array_map(function (SetCookie $cookie) {
return $cookie->toArray();
}, $this->getIterator()->getArrayCopy());
}
public function clear($domain = null, $path = null, $name = null)
{
if (!$domain) {
$this->cookies = [];
return;
} elseif (!$path) {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain) {
return !$cookie->matchesDomain($domain);
}
);
} elseif (!$name) {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain) {
return !($cookie->matchesPath($path) &&
$cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain, $name) {
return !($cookie->getName() == $name &&
$cookie->matchesPath($path) &&
$cookie->matchesDomain($domain));
}
);
}
}
public function clearSessionCookies()
{
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) {
return !$cookie->getDiscard() && $cookie->getExpires();
}
);
}
public function setCookie(SetCookie $cookie)
{
// If the name string is empty (but not 0), ignore the set-cookie
// string entirely.
$name = $cookie->getName();
if (!$name && $name !== '0') {
return false;
}
// Only allow cookies with set and valid domain, name, value
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new \RuntimeException('Invalid cookie: ' . $result);
} else {
$this->removeCookieIfEmpty($cookie);
return false;
}
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() != $cookie->getPath() ||
$c->getDomain() != $cookie->getDomain() ||
$c->getName() != $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function count()
{
return count($this->cookies);
}
public function getIterator()
{
return new \ArrayIterator(array_values($this->cookies));
}
public function extractCookies(
RequestInterface $request,
ResponseInterface $response
) {
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
foreach ($cookieHeader as $cookie) {
$sc = SetCookie::fromString($cookie);
if (!$sc->getDomain()) {
$sc->setDomain($request->getUri()->getHost());
}
if (0 !== strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
$this->setCookie($sc);
}
}
}
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
* @link https://tools.ietf.org/html/rfc6265#section-5.1.4
*
* @param RequestInterface $request
* @return string
*/
private function getCookiePathFromRequest(RequestInterface $request)
{
$uriPath = $request->getUri()->getPath();
if ('' === $uriPath) {
return '/';
}
if (0 !== strpos($uriPath, '/')) {
return '/';
}
if ('/' === $uriPath) {
return '/';
}
if (0 === $lastSlashPos = strrpos($uriPath, '/')) {
return '/';
}
return substr($uriPath, 0, $lastSlashPos);
}
public function withCookieHeader(RequestInterface $request)
{
$values = [];
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->matchesPath($path) &&
$cookie->matchesDomain($host) &&
!$cookie->isExpired() &&
(!$cookie->getSecure() || $scheme === 'https')
) {
$values[] = $cookie->getName() . '='
. $cookie->getValue();
}
}
return $values
? $request->withHeader('Cookie', implode('; ', $values))
: $request;
}
/**
* If a cookie already exists and the server asks to set it again with a
* null value, the cookie must be deleted.
*
* @param SetCookie $cookie
*/
private function removeCookieIfEmpty(SetCookie $cookie)
{
$cookieValue = $cookie->getValue();
if ($cookieValue === null || $cookieValue === '') {
$this->clear(
$cookie->getDomain(),
$cookie->getPath(),
$cookie->getName()
);
}
}
}
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Stores HTTP cookies.
*
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
* CookieJarInterface instances automatically expire contained cookies when
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @link http://docs.python.org/2/library/cookielib.html Inspiration
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
/**
* Create a request with added cookie headers.
*
* If no matching cookies are found in the cookie jar, then no Cookie
* header is added to the request and the same request is returned.
*
* @param RequestInterface $request Request object to modify.
*
* @return RequestInterface returns the modified request.
*/
public function withCookieHeader(RequestInterface $request);
/**
* Extract cookies from an HTTP response and store them in the CookieJar.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
*/
public function extractCookies(
RequestInterface $request,
ResponseInterface $response
);
/**
* Sets a cookie in the cookie jar.
*
* @param SetCookie $cookie Cookie to set.
*
* @return bool Returns true on success or false on failure
*/
public function setCookie(SetCookie $cookie);
/**
* Remove cookies currently held in the cookie jar.
*
* Invoking this method without arguments will empty the whole cookie jar.
* If given a $domain argument only cookies belonging to that domain will
* be removed. If given a $domain and $path argument, cookies belonging to
* the specified path within that domain are removed. If given all three
* arguments, then the cookie with the specified name, path and domain is
* removed.
*
* @param string $domain Clears cookies matching a domain
* @param string $path Clears cookies matching a domain and path
* @param string $name Clears cookies matching a domain, path, and name
*
* @return CookieJarInterface
*/
public function clear($domain = null, $path = null, $name = null);
/**
* Discard all sessions cookies.
*
* Removes cookies that don't have an expire field or a have a discard
* field set to true. To be called when the user agent shuts down according
* to RFC 2965.
*/
public function clearSessionCookies();
/**
* Converts the cookie jar to an array.
*
* @return array
*/
public function toArray();
}
<?php
namespace GuzzleHttp\Cookie;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
/** @var string filename */
private $filename;
/** @var bool Control whether to persist session cookies or not. */
private $storeSessionCookies;
/**
* Create a new FileCookieJar object
*
* @param string $cookieFile File to store the cookie data
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function __construct($cookieFile, $storeSessionCookies = false)
{
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (file_exists($cookieFile)) {
$this->load($cookieFile);
}
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->save($this->filename);
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
* @throws \RuntimeException if the file cannot be found or created
*/
public function save($filename)
{
$json = [];
foreach ($this as $cookie) {
/** @var SetCookie $cookie */
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$jsonStr = \GuzzleHttp\json_encode($json);
if (false === file_put_contents($filename, $jsonStr)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
*
* @param string $filename Cookie file to load.
* @throws \RuntimeException if the file cannot be loaded.
*/
public function load($filename)
{
$json = file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
} elseif ($json === '') {
return;
}
$data = \GuzzleHttp\json_decode($json, true);
if (is_array($data)) {
foreach (json_decode($json, true) as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (strlen($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
}
}
container @ 1a29b314
This diff is collapsed. Click to expand it.
contracts @ 3dc639fe
This diff is collapsed. Click to expand it.
database @ fe10cc28
This diff is collapsed. Click to expand it.
support @ 7ba15bb0
This diff is collapsed. Click to expand it.
carbon @ b1cc4493
This diff is collapsed. Click to expand it.
container @ b7ce3b17
This diff is collapsed. Click to expand it.
simple-cache @ 408d5eaf
This diff is collapsed. Click to expand it.
polyfill-mbstring @ 3296adf6
This diff is collapsed. Click to expand it.
translation @ e1f5863d
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment