Bhaveshpp

Professional Magento Developr - Healp eachother to grow

Magento 2: Curl call

28 Dec 2021 » magento2, php

patch code

namespace Bhaveshpp\Shipping\Model;

use Magento\Framework\HTTP\Client\Curl;
use Magento\Marketplace\Helper\Cache;
use Magento\Backend\Model\UrlInterface;

/**
 * @api
 * @since 100.0.2
 */
class Webservice
{
    /**
     * @var Curl
     */
    protected $curlClient;

    /**
     * @var string
     */
    protected $urlPrefix = 'https://';

    /**
     * @var string
     */
    protected $apiUrl = 'ontrack.firstflightme.com/FFCService.svc';

    /**
     * @var \Magento\Marketplace\Helper\Cache
     */
    protected $cache;

    /**
     * @var UrlInterface
     */
    private $backendUrl;

    /**
     * @param Curl $curl
     * @param Cache $cache
     * @param UrlInterface $backendUrl
     */
    public function __construct(Curl $curl, Cache $cache, UrlInterface $backendUrl)
    {
        $this->curlClient = $curl;
        $this->cache = $cache;
        $this->backendUrl = $backendUrl;
    }

    /**
     * @return string
     */
    public function getApiUrl()
    {
        return $this->urlPrefix . $this->apiUrl;
    }
    
    public function getCurl($data, $method)
    {
        $apiUrl = $this->getApiUrl() ."/". $method;
        try {
            $data_string = json_encode($data);

            $this->getCurlClient()->setOptions(
                [
                    CURLOPT_URL => $apiUrl,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => $data_string,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_HTTPHEADER => array('Content-Type: application/json')
                ]
            );
            $this->getCurlClient()->post($apiUrl, []);
            $response = json_decode($this->getCurlClient()->getBody(), true);
            if ($response) {
                $this->getCache()->savePartnersToCache($response);
                return $response;
            } else {
                return $this->getCache()->loadPartnersFromCache();
            }
        } catch (\Exception $e) {
            return $this->getCache()->loadPartnersFromCache();
        }
    }

    /**
     * @return Curl
     */
    public function getCurlClient()
    {
        return $this->curlClient;
    }

    /**
     * @return cache
     */
    public function getCache()
    {
        return $this->cache;
    }

}

Thanks.