Hello Magento Friends,
Hope all are doing well. Today I am going to justify Magento 2: How to use Default Curl Class For API Call. In case you missed checking out our previous blog, Magento 2: Add extra “Proceed to Checkout” Button on top of grid on shopping cart page.
Sometimes, developers have a requirement to call third-party API and for that client URL (cURL) request is used. Many developers use the PHP curl function directly and it works perfectly fine. But Magento has already created a curl class for future enhancement. To maintain Magento standards, we must use it. Going against the Magento coding standards will show some warnings.
For e.g, I want to create one function in helper data that is responsible for sending API messages using cURL. Let’s look at the steps to implement it.
Step 1: Create Data.php file in the below path
Vendor\Extension\Helper\Data.php
And add the below code
<?php namespace Vendor\Extension\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\HTTP\Client\Curl; /** * Class Data * Vendor\Extension\Helper */class Data extends AbstractHelper { /** * Data constructor. * @param Curl $curl */ public function __construct( Curl $curl ) { $this->curl = $curl; } /** * @return string * @throws LocalizedException */ public function defualtCurl() { try { if ($this->isEnable()) { $postData = [ 'first_param' => 'first_value' ]; $this->curl->setOption(CURLOPT_SSL_VERIFYPEER, false); $this->curl->setOption(CURLOPT_SSL_VERIFYHOST, 2); // we can add all option which is we used for default PHP curl $this->curl->post($this->getApiUrl(), $postData); // Response Text $response = $this->curl->getBody(); // Response Header $responseHeader = $this->curl->getHeaders(); // Response cookies $responseCookies = $this->curl->getCookies(); return $response; } } catch (Exception $e) { $return = ["status"=>false, "message"=> $e->getMessage()]; } } }
Accordingly, one can successfully use the default curl class for API call in Magento 2. In case you face any trouble with the implementation of the above code, mention it in the comment part below. I will be happy to help you out. See you with another solution, till then stay in touch!
Happy Coding!
In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…