Send SMS using msg91 API | PHP | Curl call




Msg91 is a my preferred SMS gateway. I used in most of the Apps and websites.

Requirement for SMS send using API.
1) MSG91 account and Authentication Key
2) Approved SMS templates
3) Approved DLT
4) Approved Sender Name

PHP Code as follows.

//below is the post-fields 
//json_string = "{ \"sender\": \"<SENDER_NAME>\", \"route\": \"4\", \"country\": \"91\", \"sms\": [ { \"message\": \"Hi, Your OTP is $num for verification on test.\", \"to\": [ \"$phone\" ] } ] }",

$postDataJson = json_encode($postData);

$authentication_key = "<MSG91_Authntication_Key>";    

//phone number with country code prefix
//here 91 in country code for India
$phone = '910000000000';

$postData = array(
    "sender" => "<SENDER_NAME>", 
    "route" => "4", 
    "country" => "91", 
    "sms" => array(
        "message" => "Hi, Your OTP is {$otp} for verification on {$var2}.",
        "to" => [$phone]
    )
);

$curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.msg91.com/api/v2/sendsms",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $postDataJson,
      CURLOPT_SSL_VERIFYHOST => 0,
      CURLOPT_SSL_VERIFYPEER => 0,
      CURLOPT_HTTPHEADER => array(
        "authkey: $authentication_key",
        "content-type: application/json"
    ),
  ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

0 comments :