1

I am calling third party API using below methods:

public function setCredentials($data)
{

    $curl = curl_init('https://example_url.com/');
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl); 
    curl_close($curl);
}

i have tried some of the examples here but I still get errors. How to curl in magento 2?

1
  • what error did you get?
    – fmsthird
    Jun 20, 2019 at 6:51

1 Answer 1

0

Here I have write curl code

/**
 * @var \Magento\Framework\HTTP\Client\Curl
 */
protected $_curl;

/**
 * @param Context                             $context
 * @param \Magento\Framework\HTTP\Client\Curl $curl
 */
public function __construct(
    Context $context,
    \Magento\Framework\HTTP\Client\Curl $curl
) {
    $this->_curl = $curl;
    parent::__construct($context);
}

public function setCredentials($params)
{
    //if the method is get
    $this->_curl->get($url);
    //if the method is post
    $this->_curl->post($url, $params);
    //response will contain the output in form of JSON string
    $response = $this->_curl->getBody();
}
1
  • shouldn't it be returning a response?
    – Mohit Rane
    Dec 7, 2020 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.