1
0
mirror of synced 2025-02-21 09:23:14 +03:00

Update payment, fix transferring shipping types, fix calculating discount (#44)

This commit is contained in:
Akolzin Dmitry 2018-01-23 14:09:44 +03:00 committed by Alex Lushpai
parent f7c2c71d93
commit dd1f5c3d14
13 changed files with 4851 additions and 5667 deletions

View File

@ -1,836 +0,0 @@
<?php
/**
* PHP version 5.3
*
* Request class
*
* @category Integration
* @package WC_Retailcrm_Client
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://retailcrm.ru/docs/Developers/ApiVersion3
*/
if ( ! class_exists( 'WC_Retailcrm_Request' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-request.php' );
}
if ( ! class_exists( 'WC_Retailcrm_Response' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-response.php' );
}
class WC_Retailcrm_Client_V3
{
protected $client;
/**
* Site code
*/
protected $siteCode;
/**
* Client creating
*
* @param string $url
* @param string $apiKey
* @param string $site
*/
public function __construct($url, $apiKey, $version = null, $site = null)
{
if ('/' != substr($url, strlen($url) - 1, 1)) {
$url .= '/';
}
$url = $version == null ? $url . 'api' : $url . 'api/' . $version;
$this->client = new WC_Retailcrm_Request($url, array('apiKey' => $apiKey));
$this->siteCode = $site;
}
/**
* Returns api versions list
*
* @return WC_Retailcrm_Response
*/
public function apiVersions()
{
return $this->client->makeRequest('/api-versions', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Create a order
*
* @param array $order
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function ordersCreate(array $order, $site = null)
{
if (!sizeof($order)) {
throw new InvalidArgumentException('Parameter `order` must contains a data');
}
return $this->client->makeRequest("/orders/create", WC_Retailcrm_Request::METHOD_POST, $this->fillSite($site, array(
'order' => json_encode($order)
)));
}
/**
* Edit a order
*
* @param array $order
* @param string $by
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function ordersEdit(array $order, $by = 'externalId', $site = null)
{
if (!sizeof($order)) {
throw new InvalidArgumentException('Parameter `order` must contains a data');
}
$this->checkIdParameter($by);
if (!isset($order[$by])) {
throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by));
}
return $this->client->makeRequest(
"/orders/" . $order[$by] . "/edit",
WC_Retailcrm_Request::METHOD_POST,
$this->fillSite($site, array(
'order' => json_encode($order),
'by' => $by,
))
);
}
/**
* Upload array of the orders
*
* @param array $orders
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function ordersUpload(array $orders, $site = null)
{
if (!sizeof($orders)) {
throw new InvalidArgumentException('Parameter `orders` must contains array of the orders');
}
return $this->client->makeRequest("/orders/upload", WC_Retailcrm_Request::METHOD_POST, $this->fillSite($site, array(
'orders' => json_encode($orders),
)));
}
/**
* Get order by id or externalId
*
* @param string $id
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function ordersGet($id, $by = 'externalId', $site = null)
{
$this->checkIdParameter($by);
return $this->client->makeRequest("/orders/$id", WC_Retailcrm_Request::METHOD_GET, $this->fillSite($site, array(
'by' => $by
)));
}
/**
* Returns a orders history
*
* @param DateTime $startDate (default: null)
* @param DateTime $endDate (default: null)
* @param int $limit (default: 100)
* @param int $offset (default: 0)
* @param bool $skipMyChanges (default: true)
* @return WC_Retailcrm_Response
*/
public function ordersHistory(
DateTime $startDate = null,
DateTime $endDate = null,
$limit = 100,
$offset = 0,
$skipMyChanges = true
) {
$parameters = array();
if ($startDate) {
$parameters['startDate'] = $startDate->format('Y-m-d H:i:s');
}
if ($endDate) {
$parameters['endDate'] = $endDate->format('Y-m-d H:i:s');
}
if ($limit) {
$parameters['limit'] = (int) $limit;
}
if ($offset) {
$parameters['offset'] = (int) $offset;
}
if ($skipMyChanges) {
$parameters['skipMyChanges'] = (bool) $skipMyChanges;
}
return $this->client->makeRequest('/orders/history', WC_Retailcrm_Request::METHOD_GET, $parameters);
}
/**
* Returns filtered orders list
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return WC_Retailcrm_Response
*/
public function ordersList(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/orders', WC_Retailcrm_Request::METHOD_GET, $parameters);
}
/**
* Returns statuses of the orders
*
* @param array $ids (default: array())
* @param array $externalIds (default: array())
* @return WC_Retailcrm_Response
*/
public function ordersStatuses(array $ids = array(), array $externalIds = array())
{
$parameters = array();
if (sizeof($ids)) {
$parameters['ids'] = $ids;
}
if (sizeof($externalIds)) {
$parameters['externalIds'] = $externalIds;
}
return $this->client->makeRequest('/orders/statuses', WC_Retailcrm_Request::METHOD_GET, $parameters);
}
/**
* Save order IDs' (id and externalId) association in the CRM
*
* @param array $ids
* @return WC_Retailcrm_Response
*/
public function ordersFixExternalIds(array $ids)
{
if (!sizeof($ids)) {
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
return $this->client->makeRequest("/orders/fix-external-ids", WC_Retailcrm_Request::METHOD_POST, array(
'orders' => json_encode($ids),
));
}
/**
* Get orders assembly history
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return WC_Retailcrm_Response
*/
public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/orders/packs/history', WC_Retailcrm_Request::METHOD_GET, $parameters);
}
/**
* Create a customer
*
* @param array $customer
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function customersCreate(array $customer, $site = null)
{
if (!sizeof($customer)) {
throw new InvalidArgumentException('Parameter `customer` must contains a data');
}
return $this->client->makeRequest("/customers/create", WC_Retailcrm_Request::METHOD_POST, $this->fillSite($site, array(
'customer' => json_encode($customer)
)));
}
/**
* Edit a customer
*
* @param array $customer
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function customersEdit(array $customer, $by = 'externalId', $site = null)
{
if (!sizeof($customer)) {
throw new InvalidArgumentException('Parameter `customer` must contains a data');
}
$this->checkIdParameter($by);
if (!isset($customer[$by])) {
throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by));
}
return $this->client->makeRequest(
"/customers/" . $customer[$by] . "/edit",
WC_Retailcrm_Request::METHOD_POST,
$this->fillSite(
$site,
array(
'customer' => json_encode($customer),
'by' => $by
)
)
);
}
/**
* Upload array of the customers
*
* @param array $customers
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function customersUpload(array $customers, $site = null)
{
if (!sizeof($customers)) {
throw new InvalidArgumentException('Parameter `customers` must contains array of the customers');
}
return $this->client->makeRequest("/customers/upload", WC_Retailcrm_Request::METHOD_POST, $this->fillSite($site, array(
'customers' => json_encode($customers),
)));
}
/**
* Get customer by id or externalId
*
* @param string $id
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function customersGet($id, $by = 'externalId', $site = null)
{
$this->checkIdParameter($by);
return $this->client->makeRequest("/customers/$id", WC_Retailcrm_Request::METHOD_GET, $this->fillSite($site, array(
'by' => $by
)));
}
/**
* Returns filtered customers list
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return WC_Retailcrm_Response
*/
public function customersList(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/customers', WC_Retailcrm_Request::METHOD_GET, $parameters);
}
/**
* Save customer IDs' (id and externalId) association in the CRM
*
* @param array $ids
* @return WC_Retailcrm_Response
*/
public function customersFixExternalIds(array $ids)
{
if (!sizeof($ids)) {
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
return $this->client->makeRequest("/customers/fix-external-ids", WC_Retailcrm_Request::METHOD_POST, array(
'customers' => json_encode($ids),
));
}
/**
* Get purchace prices & stock balance
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/store/inventories', WC_Retailcrm_Request::METHOD_GET, $this->fillSite($site, $parameters));
}
/**
* Upload store inventories
*
* @param array $offers
* @param string $site (default: null)
* @return WC_Retailcrm_Response
*/
public function storeInventoriesUpload(array $offers, $site = null)
{
if (!sizeof($offers)) {
throw new InvalidArgumentException('Parameter `offers` must contains array of the customers');
}
return $this->client->makeRequest(
"/store/inventories/upload",
WC_Retailcrm_Request::METHOD_POST,
$this->fillSite($site, array('offers' => json_encode($offers)))
);
}
/**
* Returns deliveryServices list
*
* @return WC_Retailcrm_Response
*/
public function deliveryServicesList()
{
return $this->client->makeRequest('/reference/delivery-services', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns deliveryTypes list
*
* @return WC_Retailcrm_Response
*/
public function deliveryTypesList()
{
return $this->client->makeRequest('/reference/delivery-types', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns orderMethods list
*
* @return WC_Retailcrm_Response
*/
public function orderMethodsList()
{
return $this->client->makeRequest('/reference/order-methods', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns orderTypes list
*
* @return WC_Retailcrm_Response
*/
public function orderTypesList()
{
return $this->client->makeRequest('/reference/order-types', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns paymentStatuses list
*
* @return WC_Retailcrm_Response
*/
public function paymentStatusesList()
{
return $this->client->makeRequest('/reference/payment-statuses', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns paymentTypes list
*
* @return WC_Retailcrm_Response
*/
public function paymentTypesList()
{
return $this->client->makeRequest('/reference/payment-types', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns productStatuses list
*
* @return WC_Retailcrm_Response
*/
public function productStatusesList()
{
return $this->client->makeRequest('/reference/product-statuses', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns statusGroups list
*
* @return WC_Retailcrm_Response
*/
public function statusGroupsList()
{
return $this->client->makeRequest('/reference/status-groups', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns statuses list
*
* @return WC_Retailcrm_Response
*/
public function statusesList()
{
return $this->client->makeRequest('/reference/statuses', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns sites list
*
* @return WC_Retailcrm_Response
*/
public function sitesList()
{
return $this->client->makeRequest('/reference/sites', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Returns stores list
*
* @return WC_Retailcrm_Response
*/
public function storesList()
{
return $this->client->makeRequest('/reference/stores', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Edit deliveryService
*
* @param array $data delivery service data
* @return WC_Retailcrm_Response
*/
public function deliveryServicesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/delivery-services/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'deliveryService' => json_encode($data)
)
);
}
/**
* Edit deliveryType
*
* @param array $data delivery type data
* @return WC_Retailcrm_Response
*/
public function deliveryTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/delivery-types/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'deliveryType' => json_encode($data)
)
);
}
/**
* Edit orderMethod
*
* @param array $data order method data
* @return WC_Retailcrm_Response
*/
public function orderMethodsEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/order-methods/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'orderMethod' => json_encode($data)
)
);
}
/**
* Edit orderType
*
* @param array $data order type data
* @return WC_Retailcrm_Response
*/
public function orderTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/order-types/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'orderType' => json_encode($data)
)
);
}
/**
* Edit paymentStatus
*
* @param array $data payment status data
* @return WC_Retailcrm_Response
*/
public function paymentStatusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/payment-statuses/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'paymentStatus' => json_encode($data)
)
);
}
/**
* Edit paymentType
*
* @param array $data payment type data
* @return WC_Retailcrm_Response
*/
public function paymentTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/payment-types/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'paymentType' => json_encode($data)
)
);
}
/**
* Edit productStatus
*
* @param array $data product status data
* @return WC_Retailcrm_Response
*/
public function productStatusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/product-statuses/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'productStatus' => json_encode($data)
)
);
}
/**
* Edit order status
*
* @param array $data status data
* @return WC_Retailcrm_Response
*/
public function statusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/statuses/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'status' => json_encode($data)
)
);
}
/**
* Edit site
*
* @param array $data site data
* @return WC_Retailcrm_Response
*/
public function sitesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/sites/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'site' => json_encode($data)
)
);
}
/**
* Edit store
*
* @param array $data site data
* @return WC_Retailcrm_Response
*/
public function storesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
if (!isset($data['name'])) {
throw new InvalidArgumentException('Data must contain "name" parameter.');
}
return $this->client->makeRequest(
'/reference/stores/' . $data['code'] . '/edit',
WC_Retailcrm_Request::METHOD_POST,
array(
'store' => json_encode($data)
)
);
}
/**
* Update CRM basic statistic
*
* @return WC_Retailcrm_Response
*/
public function statisticUpdate()
{
return $this->client->makeRequest('/statistic/update', WC_Retailcrm_Request::METHOD_GET);
}
/**
* Return current site
*
* @return string
*/
public function getSite()
{
return $this->siteCode;
}
/**
* Set site
*
* @param string $site
* @return void
*/
public function setSite($site)
{
$this->siteCode = $site;
}
/**
* Check ID parameter
*
* @param string $by
* @return bool
*/
protected function checkIdParameter($by)
{
$allowedForBy = array('externalId', 'id');
if (!in_array($by, $allowedForBy)) {
throw new InvalidArgumentException(sprintf(
'Value "%s" for parameter "by" is not valid. Allowed values are %s.',
$by,
implode(', ', $allowedForBy)
));
}
return true;
}
/**
* Fill params by site value
*
* @param string $site
* @param array $params
* @return array
*/
protected function fillSite($site, array $params)
{
if ($site) {
$params['site'] = $site;
} elseif ($this->siteCode) {
$params['site'] = $this->siteCode;
}
return $params;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,16 @@
<?php
/**
* PHP version 5.3
*
* WC_Retailcrm_Exception_Curl class
*
* @category RetailCRM
* @package WC_Retailcrm_Exception_Curl
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://retailcrm.ru/docs/Developers/ApiVersion4
*/
class WC_Retailcrm_Exception_Curl extends \RuntimeException
{
}
/**
* PHP version 5.3
*
* WC_Retailcrm_Exception_Curl class
*
* @category RetailCRM
* @package WC_Retailcrm_Exception_Curl
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://retailcrm.ru/docs/Developers/ApiVersion4
*/
class WC_Retailcrm_Exception_Curl extends \RuntimeException
{
}

View File

@ -1,16 +1,16 @@
<?php
/**
* PHP version 5.3
*
* WC_Retailcrm_Exception_Json class
*
* @category RetailCRM
* @package WC_Retailcrm_Exception_Json
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
*/
/**
* PHP version 5.3
*
* WC_Retailcrm_Exception_Json class
*
* @category RetailCRM
* @package WC_Retailcrm_Exception_Json
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
*/
class WC_Retailcrm_Exception_Json extends \DomainException
{
}
class WC_Retailcrm_Exception_Json extends \DomainException
{
}

View File

@ -21,10 +21,6 @@ if ( ! class_exists( 'WC_Retailcrm_Proxy' ) ) :
{
$this->logger = new WC_Logger();
if ( ! class_exists( 'WC_Retailcrm_Client_V3' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-client-v3.php' );
}
if ( ! class_exists( 'WC_Retailcrm_Client_V4' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-client-v4.php' );
}
@ -34,9 +30,6 @@ if ( ! class_exists( 'WC_Retailcrm_Proxy' ) ) :
}
switch ($api_vers) {
case 'v3':
$this->retailcrm = new WC_Retailcrm_Client_V3($api_url, $api_key, $api_vers);
break;
case 'v4':
$this->retailcrm = new WC_Retailcrm_Client_V4($api_url, $api_key, $api_vers);
break;
@ -44,7 +37,7 @@ if ( ! class_exists( 'WC_Retailcrm_Proxy' ) ) :
$this->retailcrm = new WC_Retailcrm_Client_V5($api_url, $api_key, $api_vers);
break;
case null:
$this->retailcrm = new WC_Retailcrm_Client_V3($api_url, $api_key, $api_vers);
$this->retailcrm = new WC_Retailcrm_Client_V4($api_url, $api_key, $api_vers);
break;
}
}

View File

@ -1,117 +1,116 @@
<?php
/**
* PHP version 5.3
*
* Request class
*
* @category Integration
* @package WC_Retailcrm_Request
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
*/
/**
* PHP version 5.3
*
* Request class
*
* @category Integration
* @package WC_Retailcrm_Request
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
*/
if ( ! class_exists( 'WC_Retailcrm_Exception_Curl' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-exception-curl.php' );
}
if ( ! class_exists( 'WC_Retailcrm_Exception_Curl' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-exception-curl.php' );
}
if ( ! class_exists( 'WC_Retailcrm_Response' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-response.php' );
}
if ( ! class_exists( 'WC_Retailcrm_Response' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-response.php' );
}
class WC_Retailcrm_Request
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
class WC_Retailcrm_Request
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
protected $url;
protected $defaultParameters;
protected $url;
protected $defaultParameters;
/**
* Client constructor.
*
* @param string $url api url
* @param array $defaultParameters array of parameters
*
* @throws \InvalidArgumentException
*/
public function __construct($url, array $defaultParameters = array())
{
if (false === stripos($url, 'https://')) {
throw new \InvalidArgumentException(
'API schema requires HTTPS protocol'
);
}
/**
* Client constructor.
*
* @param string $url api url
* @param array $defaultParameters array of parameters
*
* @throws \InvalidArgumentException
*/
public function __construct($url, array $defaultParameters = array())
{
if (false === stripos($url, 'https://')) {
throw new \InvalidArgumentException(
'API schema requires HTTPS protocol'
);
}
$this->url = $url;
$this->defaultParameters = $defaultParameters;
}
$this->url = $url;
$this->defaultParameters = $defaultParameters;
}
/**
* Make HTTP request
*
* @param string $path request url
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*
* @throws \InvalidArgumentException
* @throws WC_Retailcrm_Exception_Curl
*
* @return WC_Retailcrm_Response
*/
public function makeRequest(
$path,
$method,
array $parameters = array()
) {
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
/**
* Make HTTP request
*
* @param string $path request url
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*
* @throws \InvalidArgumentException
* @throws WC_Retailcrm_Exception_Curl
*
* @return WC_Retailcrm_Response
*/
public function makeRequest(
$path,
$method,
array $parameters = array()
) {
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
if (!in_array($method, $allowedMethods, false)) {
throw new \InvalidArgumentException(
sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
)
);
}
if (!in_array($method, $allowedMethods, false)) {
throw new \InvalidArgumentException(
sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
)
);
}
$parameters = array_merge($this->defaultParameters, $parameters);
$parameters = array_merge($this->defaultParameters, $parameters);
$url = $this->url . $path;
$url = $this->url . $path;
if (self::METHOD_GET === $method && count($parameters)) {
$url .= '?' . http_build_query($parameters, '', '&');
}
if (self::METHOD_GET === $method && count($parameters)) {
$url .= '?' . http_build_query($parameters, '', '&');
}
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
if (self::METHOD_POST === $method) {
curl_setopt($curlHandler, CURLOPT_POST, true);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters);
}
if (self::METHOD_POST === $method) {
curl_setopt($curlHandler, CURLOPT_POST, true);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters);
}
$responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$errno = curl_errno($curlHandler);
$error = curl_error($curlHandler);
$responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$errno = curl_errno($curlHandler);
$error = curl_error($curlHandler);
curl_close($curlHandler);
curl_close($curlHandler);
if ($errno) {
throw new WC_Retailcrm_Exception_Curl($error, $errno);
}
if ($errno) {
throw new WC_Retailcrm_Exception_Curl($error, $errno);
}
return new WC_Retailcrm_Response($statusCode, $responseBody);
}
}
return new WC_Retailcrm_Response($statusCode, $responseBody);
}
}

View File

@ -1,169 +1,169 @@
<?php
/**
* PHP version 5.3
*
* Response class
*
* @category Integration
* @package WC_Retailcrm_Response
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
*/
/**
* PHP version 5.3
*
* Response class
*
* @category Integration
* @package WC_Retailcrm_Response
* @author RetailCRM <dev@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
*/
if ( ! class_exists( 'WC_Retailcrm_Exception_Json' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-exception-json.php' );
}
if ( ! class_exists( 'WC_Retailcrm_Exception_Json' ) ) {
include_once( __DIR__ . '/class-wc-retailcrm-exception-json.php' );
}
class WC_Retailcrm_Response implements \ArrayAccess
{
// HTTP response status code
protected $statusCode;
class WC_Retailcrm_Response implements \ArrayAccess
{
// HTTP response status code
protected $statusCode;
// response assoc array
protected $response;
// response assoc array
protected $response;
/**
* ApiResponse constructor.
*
* @param int $statusCode HTTP status code
* @param mixed $responseBody HTTP body
*
* @throws WC_Retailcrm_Exception_Json
*/
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = (int) $statusCode;
/**
* ApiResponse constructor.
*
* @param int $statusCode HTTP status code
* @param mixed $responseBody HTTP body
*
* @throws WC_Retailcrm_Exception_Json
*/
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = (int) $statusCode;
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new WC_Retailcrm_Exception_Json(
"Invalid JSON in the API response body. Error code #$error",
$error
);
}
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new WC_Retailcrm_Exception_Json(
"Invalid JSON in the API response body. Error code #$error",
$error
);
}
$this->response = $response;
}
}
$this->response = $response;
}
}
/**
* Return HTTP response status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* Return HTTP response status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* HTTP request was successful
*
* @return bool
*/
public function isSuccessful()
{
return $this->statusCode < 400;
}
/**
* HTTP request was successful
*
* @return bool
*/
public function isSuccessful()
{
return $this->statusCode < 400;
}
/**
* Allow to access for the property throw class method
*
* @param string $name method name
* @param mixed $arguments method parameters
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __call($name, $arguments)
{
// convert getSomeProperty to someProperty
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
/**
* Allow to access for the property throw class method
*
* @param string $name method name
* @param mixed $arguments method parameters
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __call($name, $arguments)
{
// convert getSomeProperty to someProperty
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
if (!isset($this->response[$propertyName])) {
throw new \InvalidArgumentException("Method \"$name\" not found");
}
if (!isset($this->response[$propertyName])) {
throw new \InvalidArgumentException("Method \"$name\" not found");
}
return $this->response[$propertyName];
}
return $this->response[$propertyName];
}
/**
* Allow to access for the property throw object property
*
* @param string $name property name
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new \InvalidArgumentException("Property \"$name\" not found");
}
/**
* Allow to access for the property throw object property
*
* @param string $name property name
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new \InvalidArgumentException("Property \"$name\" not found");
}
return $this->response[$name];
}
return $this->response[$name];
}
/**
* Offset set
*
* @param mixed $offset offset
* @param mixed $value value
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException('This activity not allowed');
}
/**
* Offset set
*
* @param mixed $offset offset
* @param mixed $value value
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException('This activity not allowed');
}
/**
* Offset unset
*
* @param mixed $offset offset
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetUnset($offset)
{
throw new \BadMethodCallException('This call not allowed');
}
/**
* Offset unset
*
* @param mixed $offset offset
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetUnset($offset)
{
throw new \BadMethodCallException('This call not allowed');
}
/**
* Check offset
*
* @param mixed $offset offset
*
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->response[$offset]);
}
/**
* Check offset
*
* @param mixed $offset offset
*
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->response[$offset]);
}
/**
* Get offset
*
* @param mixed $offset offset
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new \InvalidArgumentException("Property \"$offset\" not found");
}
/**
* Get offset
*
* @param mixed $offset offset
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new \InvalidArgumentException("Property \"$offset\" not found");
}
return $this->response[$offset];
}
}
return $this->response[$offset];
}
}

View File

@ -311,8 +311,8 @@ if ( ! class_exists( 'WC_Retailcrm_Base' ) ) :
public function validate_api_version_field( $key, $value ) {
$post = $this->get_post_data();
$versionMap = array(
'v3' => '3.0',
'v4' => '4.0',
'v5' => '5.0'
);

View File

@ -143,295 +143,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$this->removeFuncsHook();
try {
if ($record['field'] == 'status' && !empty($record['newValue']) && !empty($record['oldValue'])) {
$newStatus = $record['newValue']['code'];
if (!empty($options[$newStatus]) && !empty($record['order']['externalId'])) {
$order = new WC_Order($record['order']['externalId']);
$order->update_status($options[$newStatus]);
}
}
elseif($record['field'] == 'order_product' && $record['newValue']) {
$product = wc_get_product($record['item']['offer']['externalId']);
$order = new WC_Order($record['order']['externalId']);
$order->add_product($product, $record['item']['quantity']);
$this->update_total($order);
}
elseif($record['field'] == 'order_product.quantity' && $record['newValue']) {
$order = new WC_Order($record['order']['externalId']);
$product = wc_get_product($record['item']['offer']['externalId']);
$items = $order->get_items();
foreach ($items as $order_item_id => $item) {
if ($item['variation_id'] != 0 ) {
$offer_id = $item['variation_id'];
} else {
$offer_id = $item['product_id'];
}
if ($offer_id == $record['item']['offer']['externalId']) {
wc_delete_order_item($order_item_id);
$order->add_product($product, $record['newValue']);
$this->update_total($order);
}
}
}
elseif ($record['field'] == 'order_product' && !$record['newValue']) {
$order = new WC_Order($record['order']['externalId']);
$items = $order->get_items();
foreach ($items as $order_item_id => $item) {
if ($item['variation_id'] != 0 ) {
$offer_id = $item['variation_id'];
} else {
$offer_id = $item['product_id'];
}
if ($offer_id == $record['item']['offer']['externalId']) {
wc_delete_order_item($order_item_id);
$this->update_total($order);
}
}
}
elseif ($record['field'] == 'delivery_type') {
$newValue = $record['newValue']['code'];
if (!empty($options[$newValue]) && !empty($record['order']['externalId'])) {
if (isset($options[$newValue])) {
$order = new WC_Order($record['order']['externalId']);
$items = $order->get_items('shipping');
$item_id = $this->getShippingItemId($items);
$crmOrder = $this->retailcrm->ordersGet($record['order']['externalId']);
$shipping_methods = get_wc_shipping_methods(true);
if (isset($shipping_methods[$options[$newValue]])) {
$method_id = $options[$newValue];
} else {
$method_id = explode(':', $options[$newValue]);
$method_id = $method_id[0];
$shipping_method = $shipping_methods[$method_id]['shipping_methods'][$options[$newValue]];
}
if ( is_object($crmOrder)) {
if ($crmOrder->isSuccessful()) {
$deliveryCost = isset($crmOrder['order']['delivery']['cost']) ? $crmOrder['order']['delivery']['cost'] : 0;
}
}
$args = array(
'method_id' => $options[$newValue],
'method_title' => isset($shipping_method) ? $shipping_method['title'] : $shipping_methods[$options[$newValue]]['name'],
'total' => $deliveryCost
);
$item = $order->get_item((int)$item_id);
$item->set_order_id((int)$order->get_id());
$item->set_props($args);
$item->save();
}
$updateOrder = new WC_Order((int)$order->get_id());
$this->update_total($updateOrder);
}
}
elseif ($record['field'] == 'delivery_address.region') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_state($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.city') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_city($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.street') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_address_1($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.building') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_address_2($record['newValue']);
}
elseif ($record['field'] == 'payment_type') {
$order = new WC_Order($record['order']['externalId']);
$newValue = $record['newValue']['code'];
if (!empty($options[$newValue]) && !empty($record['order']['externalId'])) {
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
if (isset($payment_types[$options[$newValue]])) {
update_post_meta($order->get_id(), '_payment_method', $payment->id);
}
}
}
elseif ($record['field'] == 'payments') {
$response = $this->retailcrm->ordersGet($record['order']['externalId']);
if ($response->isSuccessful()) {
$order_data = $response['order'];
$order = new WC_Order($record['order']['externalId']);
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
if (count($order_data['payments']) == 1) {
$paymentType = end($order_data['payments']);
if (isset($payment_types[$options[$paymentType['type']]])) {
$payment = $payment_types[$options[$paymentType['type']]];
update_post_meta($order->get_id(), '_payment_method', $payment->id);
}
} else {
foreach ($order_data['payments'] as $payment_data) {
if (isset($payment_data['externalId'])) {
$paymentType = $payment_data;
}
}
if (!isset($paymentType)) {
$paymentType = $order_data['payments'][0];
}
if (isset($payment_types[$options[$paymentType['type']]])) {
update_post_meta($order->get_id(), '_payment_method', $payment->id);
}
}
}
}
elseif (isset($record['created']) &&
$record['created'] == 1 &&
!isset($record['order']['externalId'])) {
$args = array(
'status' => $options[$record['order']['status']],
'customer_id' => isset($record['order']['customer']['externalId']) ?
$record['order']['customer']['externalId'] :
null
);
$order_record = $record['order'];
$order_data = wc_create_order($args);
$order = new WC_Order($order_data->id);
$address_shipping = array(
'first_name' => $order_record['firstName'],
'last_name' => isset($order_record['lastName']) ? $order_record['lastName'] : '',
'company' => '',
'email' => isset($order_record['email']) ? $order_record['email'] : '',
'phone' => isset($order_record['phone']) ? $order_record['phone'] : '',
'address_1' => isset($order_record['delivery']['address']['text']) ? $order_record['delivery']['address']['text'] : '',
'address_2' => '',
'city' => isset($order_record['delivery']['address']['city']) ? $order_record['delivery']['address']['city'] : '',
'state' => isset($order_record['delivery']['address']['region']) ? $order_record['delivery']['address']['region'] : '',
'postcode' => isset($order_record['delivery']['address']['postcode']) ? $order_record['delivery']['address']['postcode'] : '',
'country' => $order_record['delivery']['address']['countryIso']
);
$address_billing = array(
'first_name' => $order_record['customer']['firstName'],
'last_name' => isset($order_record['customer']['lastName']) ? $order_record['customer']['lastName'] : '',
'company' => '',
'email' => isset($order_record['customer']['email']) ? $order_record['customer']['email'] : '',
'phone' => isset($order_record['customer'][0]['number']) ? $order_record['customer'][0]['number'] : '',
'address_1' => isset($order_record['customer']['address']['text']) ? $order_record['customer']['address']['text'] : '',
'address_2' => '',
'city' => isset($order_record['customer']['address']['city']) ? $order_record['customer']['address']['city'] : '',
'state' => isset($order_record['customer']['address']['region']) ? $order_record['customer']['address']['region'] : '',
'postcode' => isset($order_record['customer']['address']['postcode']) ? $order_record['customer']['address']['postcode'] : '',
'country' => $order_record['customer']['address']['countryIso']
);
if ($this->retailcrm_settings['api_version'] == 'v5') {
if ($order_record['payments']) {
$payment = new WC_Payment_Gateways();
if (count($order_record['payments']) == 1) {
$payment_types = $payment->get_available_payment_gateways();
$paymentType = end($order_record['payments']);
if (isset($payment_types[$options[$paymentType['type']]])) {
$order->set_payment_method($payment_types[$options[$paymentType['type']]]);
}
}
}
} else {
if ($order_record['paymentType']) {
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
if (isset($payment_types[$options[$order_record['paymentType']]])) {
$order->set_payment_method($payment_types[$options[$order_record['paymentType']]]);
}
}
}
$order->set_address($address_billing, 'billing');
$order->set_address($address_shipping, 'shipping');
$product_data = isset($order_record['items']) ? $order_record['items'] : array();
if ($product_data) {
foreach ($product_data as $product) {
$order->add_product(wc_get_product($product['offer']['externalId']), $product['quantity']);
}
}
if (array_key_exists('delivery', $order_record)) {
$deliveryCode = isset($order_record['delivery']['code']) ? $order_record['delivery']['code'] : false;
if ($deliveryCode && isset($options[$deliveryCode])) {
$delivery = explode(':', $options[$deliveryCode]);
if (isset($delivery[1])) {
$instance_id = $delivery[1];
}
}
if (isset($instance_id)) {
$wc_shipping = WC_Shipping_Zones::get_shipping_method($instance_id);
$shipping_method_title = $wc_shipping->method_title;
$shipping_method_id = $options[$deliveryCode];
$shipping_total = $order_record['delivery']['cost'];
} else {
$wc_shipping = new WC_Shipping();
$wc_shipping_types = $wc_shipping->get_shipping_methods();
foreach ($wc_shipping_types as $shipping_type) {
if ($shipping_type->id == $options[$deliveryCode]) {
$shipping_method_id = $shipping_type->id;
$shipping_method_title = $shipping_type->method_title;
$shipping_total = $order_record['delivery']['cost'];
}
}
}
if (version_compare(get_option('woocommerce_db_version'), '3.0', '<' )) {
$shipping_rate = new WC_Shipping_Rate($shipping_method_id, isset($shipping_method_title) ? $shipping_method_title : '', isset($shipping_total) ? floatval($shipping_total) : 0, array(), $shipping_method_id);
$order->add_shipping($shipping_rate);
} else {
$shipping = new WC_Order_Item_Shipping();
$shipping->set_props( array(
'method_title' => $shipping_method_title,
'method_id' => $shipping_method_id,
'total' => wc_format_decimal($shipping_total),
'order_id' => $order->id
) );
$shipping->save();
$order->add_item( $shipping );
}
}
$this->update_total($order);
$ids[] = array(
'id' => (int)$order_record['id'],
'externalId' => (int)$order_data->id
);
$this->retailcrm->ordersFixExternalIds($ids);
}
$this->orderEdit($record, $options);
} catch (Exception $exception) {
$logger = new WC_Logger();
$logger->add('retailcrm', sprintf("[%s] - %s", $exception->getMessage(), 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine()));
@ -497,6 +209,298 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
}
}
protected function orderEdit($record, $options)
{
if ($record['field'] == 'status' && !empty($record['newValue']) && !empty($record['oldValue'])) {
$newStatus = $record['newValue']['code'];
if (!empty($options[$newStatus]) && !empty($record['order']['externalId'])) {
$order = new WC_Order($record['order']['externalId']);
$order->update_status($options[$newStatus]);
}
}
elseif($record['field'] == 'order_product' && $record['newValue']) {
$product = wc_get_product($record['item']['offer']['externalId']);
$order = new WC_Order($record['order']['externalId']);
$order->add_product($product, $record['item']['quantity']);
$this->update_total($order);
}
elseif($record['field'] == 'order_product.quantity' && $record['newValue']) {
$order = new WC_Order($record['order']['externalId']);
$product = wc_get_product($record['item']['offer']['externalId']);
$items = $order->get_items();
foreach ($items as $order_item_id => $item) {
if ($item['variation_id'] != 0 ) {
$offer_id = $item['variation_id'];
} else {
$offer_id = $item['product_id'];
}
if ($offer_id == $record['item']['offer']['externalId']) {
wc_delete_order_item($order_item_id);
$order->add_product($product, $record['newValue']);
$this->update_total($order);
}
}
}
elseif ($record['field'] == 'order_product' && !$record['newValue']) {
$order = new WC_Order($record['order']['externalId']);
$items = $order->get_items();
foreach ($items as $order_item_id => $item) {
if ($item['variation_id'] != 0 ) {
$offer_id = $item['variation_id'];
} else {
$offer_id = $item['product_id'];
}
if ($offer_id == $record['item']['offer']['externalId']) {
wc_delete_order_item($order_item_id);
$this->update_total($order);
}
}
}
elseif ($record['field'] == 'delivery_type') {
$newValue = $record['newValue']['code'];
if (!empty($options[$newValue]) && !empty($record['order']['externalId'])) {
if (isset($options[$newValue])) {
$order = new WC_Order($record['order']['externalId']);
$items = $order->get_items('shipping');
$item_id = $this->getShippingItemId($items);
$crmOrder = $this->retailcrm->ordersGet($record['order']['externalId']);
$shipping_methods = get_wc_shipping_methods(true);
if (isset($shipping_methods[$options[$newValue]])) {
$method_id = $options[$newValue];
} else {
$method_id = explode(':', $options[$newValue]);
$method_id = $method_id[0];
$shipping_method = $shipping_methods[$method_id]['shipping_methods'][$options[$newValue]];
}
if ( is_object($crmOrder)) {
if ($crmOrder->isSuccessful()) {
$deliveryCost = isset($crmOrder['order']['delivery']['cost']) ? $crmOrder['order']['delivery']['cost'] : 0;
}
}
$args = array(
'method_id' => $options[$newValue],
'method_title' => isset($shipping_method) ? $shipping_method['title'] : $shipping_methods[$options[$newValue]]['name'],
'total' => $deliveryCost
);
$item = $order->get_item((int)$item_id);
$item->set_order_id((int)$order->get_id());
$item->set_props($args);
$item->save();
}
$updateOrder = new WC_Order((int)$order->get_id());
$this->update_total($updateOrder);
}
}
elseif ($record['field'] == 'delivery_address.region') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_state($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.city') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_city($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.street') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_address_1($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.building') {
$order = new WC_Order($record['order']['externalId']);
$order->set_shipping_address_2($record['newValue']);
}
elseif ($record['field'] == 'payment_type') {
$order = new WC_Order($record['order']['externalId']);
$newValue = $record['newValue']['code'];
if (!empty($options[$newValue]) && !empty($record['order']['externalId'])) {
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
if (isset($payment_types[$options[$newValue]])) {
update_post_meta($order->get_id(), '_payment_method', $payment->id);
}
}
}
elseif ($record['field'] == 'payments') {
$response = $this->retailcrm->ordersGet($record['order']['externalId']);
if ($response->isSuccessful()) {
$order_data = $response['order'];
$order = new WC_Order($record['order']['externalId']);
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
if (count($order_data['payments']) == 1) {
$paymentType = end($order_data['payments']);
if (isset($payment_types[$options[$paymentType['type']]])) {
$payment = $payment_types[$options[$paymentType['type']]];
update_post_meta($order->get_id(), '_payment_method', $payment->id);
}
} else {
foreach ($order_data['payments'] as $payment_data) {
if (isset($payment_data['externalId'])) {
$paymentType = $payment_data;
}
}
if (!isset($paymentType)) {
$paymentType = $order_data['payments'][0];
}
if (isset($payment_types[$options[$paymentType['type']]])) {
update_post_meta($order->get_id(), '_payment_method', $payment->id);
}
}
}
}
elseif (isset($record['created']) &&
$record['created'] == 1 &&
!isset($record['order']['externalId'])) {
$args = array(
'status' => $options[$record['order']['status']],
'customer_id' => isset($record['order']['customer']['externalId']) ?
$record['order']['customer']['externalId'] :
null
);
$order_record = $record['order'];
$order_data = wc_create_order($args);
$order = new WC_Order($order_data->id);
$address_shipping = array(
'first_name' => $order_record['firstName'],
'last_name' => isset($order_record['lastName']) ? $order_record['lastName'] : '',
'company' => '',
'email' => isset($order_record['email']) ? $order_record['email'] : '',
'phone' => isset($order_record['phone']) ? $order_record['phone'] : '',
'address_1' => isset($order_record['delivery']['address']['text']) ? $order_record['delivery']['address']['text'] : '',
'address_2' => '',
'city' => isset($order_record['delivery']['address']['city']) ? $order_record['delivery']['address']['city'] : '',
'state' => isset($order_record['delivery']['address']['region']) ? $order_record['delivery']['address']['region'] : '',
'postcode' => isset($order_record['delivery']['address']['postcode']) ? $order_record['delivery']['address']['postcode'] : '',
'country' => $order_record['delivery']['address']['countryIso']
);
$address_billing = array(
'first_name' => $order_record['customer']['firstName'],
'last_name' => isset($order_record['customer']['lastName']) ? $order_record['customer']['lastName'] : '',
'company' => '',
'email' => isset($order_record['customer']['email']) ? $order_record['customer']['email'] : '',
'phone' => isset($order_record['customer'][0]['number']) ? $order_record['customer'][0]['number'] : '',
'address_1' => isset($order_record['customer']['address']['text']) ? $order_record['customer']['address']['text'] : '',
'address_2' => '',
'city' => isset($order_record['customer']['address']['city']) ? $order_record['customer']['address']['city'] : '',
'state' => isset($order_record['customer']['address']['region']) ? $order_record['customer']['address']['region'] : '',
'postcode' => isset($order_record['customer']['address']['postcode']) ? $order_record['customer']['address']['postcode'] : '',
'country' => $order_record['customer']['address']['countryIso']
);
if ($this->retailcrm_settings['api_version'] == 'v5') {
if ($order_record['payments']) {
$payment = new WC_Payment_Gateways();
if (count($order_record['payments']) == 1) {
$payment_types = $payment->get_available_payment_gateways();
$paymentType = end($order_record['payments']);
if (isset($payment_types[$options[$paymentType['type']]])) {
$order->set_payment_method($payment_types[$options[$paymentType['type']]]);
}
}
}
} else {
if ($order_record['paymentType']) {
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
if (isset($payment_types[$options[$order_record['paymentType']]])) {
$order->set_payment_method($payment_types[$options[$order_record['paymentType']]]);
}
}
}
$order->set_address($address_billing, 'billing');
$order->set_address($address_shipping, 'shipping');
$product_data = isset($order_record['items']) ? $order_record['items'] : array();
if ($product_data) {
foreach ($product_data as $product) {
$order->add_product(wc_get_product($product['offer']['externalId']), $product['quantity']);
}
}
if (array_key_exists('delivery', $order_record)) {
$deliveryCode = isset($order_record['delivery']['code']) ? $order_record['delivery']['code'] : false;
if ($deliveryCode && isset($options[$deliveryCode])) {
$delivery = explode(':', $options[$deliveryCode]);
if (isset($delivery[1])) {
$instance_id = $delivery[1];
}
}
if (isset($instance_id)) {
$wc_shipping = WC_Shipping_Zones::get_shipping_method($instance_id);
$shipping_method_title = $wc_shipping->method_title;
$shipping_method_id = $options[$deliveryCode];
$shipping_total = $order_record['delivery']['cost'];
} else {
$wc_shipping = new WC_Shipping();
$wc_shipping_types = $wc_shipping->get_shipping_methods();
foreach ($wc_shipping_types as $shipping_type) {
if ($shipping_type->id == $options[$deliveryCode]) {
$shipping_method_id = $shipping_type->id;
$shipping_method_title = $shipping_type->method_title;
$shipping_total = $order_record['delivery']['cost'];
}
}
}
if (version_compare(get_option('woocommerce_db_version'), '3.0', '<' )) {
$shipping_rate = new WC_Shipping_Rate($shipping_method_id, isset($shipping_method_title) ? $shipping_method_title : '', isset($shipping_total) ? floatval($shipping_total) : 0, array(), $shipping_method_id);
$order->add_shipping($shipping_rate);
} else {
$shipping = new WC_Order_Item_Shipping();
$shipping->set_props( array(
'method_title' => $shipping_method_title,
'method_id' => $shipping_method_id,
'total' => wc_format_decimal($shipping_total),
'order_id' => $order->id
) );
$shipping->save();
$order->add_item( $shipping );
}
}
$this->update_total($order);
$ids[] = array(
'id' => (int)$order_record['id'],
'externalId' => (int)$order_data->id
);
$this->retailcrm->ordersFixExternalIds($ids);
}
}
protected function getShippingItemId($items)
{
if ($items) {

View File

@ -277,10 +277,11 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
* process to combine order data
*
* @param int $order_id
*
* @param boolean $update
*
* @return array $order_data
*/
public function processOrder($order_id)
public function processOrder($order_id, $update = false)
{
if ( !$order_id ){
return;
@ -303,8 +304,8 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$shipping = end($order->get_items( 'shipping' ));
$shipping_code = explode(':', $shipping['method_id']);
if (isset($this->retailcrm_settings[$shipping])) {
$shipping_method = $shipping;
if (isset($this->retailcrm_settings[$shipping['method_id']])) {
$shipping_method = $shipping['method_id'];
} else {
$shipping_method = $shipping_code[0];
}
@ -369,7 +370,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
foreach ($order->get_items() as $item) {
$uid = ($item['variation_id'] > 0) ? $item['variation_id'] : $item['product_id'] ;
$_product = wc_get_product($uid);
$price = wc_get_price_including_tax($_product);
$price = round($item['line_subtotal'] + $item['line_subtotal_tax'], 2);
if ($_product) {
$product_price = $item->get_total() ? $item->get_total() / $item->get_quantity() : 0;
@ -384,10 +385,10 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
'quantity' => $item['qty'],
);
if ($this->retailcrm_settings['api_version'] == 'v5') {
$order_item['discountManualAmount'] = $discount_price;
} elseif ($this->retailcrm_settings['api_version'] == 'v4') {
$order_item['discount'] = $discount_price;
if ($this->retailcrm_settings['api_version'] == 'v5' && round($discount_price, 2)) {
$order_item['discountManualAmount'] = round($discount_price, 2);
} elseif ($this->retailcrm_settings['api_version'] == 'v4' && round($discount_price, 2)) {
$order_item['discount'] = round($discount_price, 2);
}
}
@ -419,12 +420,24 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$payment['paidAt'] = trim($pay_date->date('Y-m-d H:i:s'));
}
$order_data['payments'][] = $payment;
if (!$update) {
$order_data['payments'][] = $payment;
} else {
$this->editPayment($payment);
}
}
return $order_data;
}
/**
* Create payment in CRM
*
* @param WC_Order $order
* @param int $order_id
*
* @return void
*/
protected function createPayment($order, $order_id)
{
$payment = array(
@ -452,16 +465,35 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$this->retailcrm->ordersPaymentCreate($payment);
}
/**
* Edit payment in CRM
*
* @param array $payment
*
* @return void
*/
protected function editPayment($payment)
{
$this->retailcrm->ordersPaymentEdit($payment);
}
/**
* Edit order in CRM
*
* @param int $order_id
*
* @return void
*/
public function updateOrder($order_id)
{
$order = $this->processOrder($order_id);
$order = $this->processOrder($order_id, true);
$response = $this->retailcrm->ordersEdit($order);
$order = new WC_Order($order_id);
$orderWc = new WC_Order($order_id);
if ($response->isSuccessful()) {
$this->orderUpdatePaymentType($order_id, $order->payment_method);
$this->orderUpdatePaymentType($order_id, $orderWc->payment_method);
}
}
}

View File

@ -1,6 +1,6 @@
<?php
/**
* Version: 2.0.2
* Version: 2.0.3
* Plugin Name: WooCommerce RetailCRM
* Plugin URI: https://wordpress.org/plugins/woo-retailcrm/
* Description: Integration plugin for WooCommerce & RetailCRM
@ -413,13 +413,5 @@ if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_
add_action('admin_print_footer_scripts', 'ajax_generate_icml', 99);
add_action( 'woocommerce_created_customer', 'create_customer', 10, 1 );
add_action( 'woocommerce_checkout_update_user_meta', 10, 2 );
if (version_compare(get_option('woocommerce_db_version'), '3.0', '<' )) {
add_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
add_action('woocommerce_saved_order_items', 'retailcrm_update_order_items', 10, 2);
add_action('update_post_meta', 'retailcrm_update_order', 11, 4);
add_action('woocommerce_payment_complete', 'retailcrm_update_order_payment', 11, 1);
} else {
add_action('woocommerce_update_order', 'update_order', 11, 1);
}
add_action('woocommerce_update_order', 'update_order', 11, 1);
}

View File

@ -15,7 +15,7 @@
*
*
* @link https://wordpress.org/plugins/woo-retailcrm/
* @since 2.0.2
* @since 2.0.3
*
* @package RetailCRM
*/