How To

Magento 2: How to use Default Curl Class For API Call

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.

Introduction:

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.

Steps to use Default Curl Class For API Call in Magento 2:

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()];
        }
    }
}

Conclusion:

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!

Click to rate this post!
[Total: 10 Average: 4.8]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

7 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago