Skip to content

How to use curl in magento 2 method?

I have a curl script to send sms. Below is the code.

 $userId    = $this->gupShupConfig->getSenderUsername();
 $password  = $this->gupShupConfig->getSenderPassword();
 $smsApiUrl = $this->gupShupConfig->getSmsApiUrl();

 $post_fields = array();
 $post_fields["method"] = "sendMessage";
 $post_fields["send_to"] = $formattedMobileNumber;//"919820XXXXXX";
 $post_fields["msg"] = $smsMessage;
 $post_fields["msg_type"] = "TEXT";
 $post_fields["userid"] = $userId;
 $post_fields["password"] = $password;
 $post_fields["auth_scheme"] = "PLAIN";
 $post_fields["format"] = "JSON";

$curl = curl_init();
curl_setopt_array($curl, array(CURLOPT_URL => $smsApiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $post_fields));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        //echo $response;
    }

This code is working fine and sending sms.

But i want to inject curl using Magento way and send the sms. I followed How to Make a cURL Request in Magento 2 the RIGHT WAY

<?php 
use MagentoFrameworkHTTPClientCurl;
-----
public function __construct(
Curl $curl
){
  $this->curl =  $curl;
}
public function sendSms($mobileNumber, $smsMessage){
 $userId    = $this->gupShupConfig->getSenderUsername();
 $password  = $this->gupShupConfig->getSenderPassword();
 $smsApiUrl = $this->gupShupConfig->getSmsApiUrl();

 $post_fields = array();
 $post_fields["method"] = "sendMessage";
 $post_fields["send_to"] = $formattedMobileNumber;//"919820XXXXXX";
 $post_fields["msg"] = $smsMessage;
 $post_fields["msg_type"] = "TEXT";
 $post_fields["userid"] = $userId;
 $post_fields["password"] = $password;
 $post_fields["auth_scheme"] = "PLAIN";
 $post_fields["format"] = "JSON";

$this->curl->setOption(CURLOPT_USERPWD, $userId . ":" . $password);
    $this->curl->setOption(CURLOPT_RETURNTRANSFER, true);
    //$this->curl->setOption(CURLOPT_ENCODING, "");
    $this->curl->setOption(CURLOPT_MAXREDIRS, 10);
    $this->curl->setOption(CURLOPT_TIMEOUT, 30);
    $this->curl->setOption(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    $this->curl->setOption(CURLOPT_URL, $smsApiUrl);
    $this->curl->setOption(CURLOPT_POSTFIELDS, $post_fields);
    
    //set curl header
    $this->curl->addHeader("Content-Type", "application/json");
    //post request with url and data
    $this->curl->post($smsApiUrl);
    //read response
    $response = $this->curl->getBody();

This way i am getting an error like below

main.CRITICAL: Response error | 331 | exception.message.invalid.json
[] []

How can i fix this error?