Search code examples
laraveltwilio

How to send messages/sms without Twilio phone number


I tried to send a message without a Twilio phone number because we has no intent to get any messages from users. I followed this tutorial written in Ruby https://www.twilio.com/blog/send-sms-without-phone-number-ruby. I search for any similar tutorial written in PHP but to no avail.

Code:

public function sendSms(string $message, string $phone)
    {
        $sid = env("TWILIO_ACCOUNT_SID");
        $token = env("TWILIO_AUTH_TOKEN");
        $messagingSid = env("MESSAGING_SERVICE_SID");
        $twilio = new Client($sid, $token);

        $message = $twilio->messages->create(
            $phone,
            [
                "body" => $message,
                "messaging_service_sid" => $messagingSid,
            ]
        );

        return $message->sid;
    }

When this code run, an error occurred saying [HTTP 400] Unable to create record: A 'From' phone number is required I just send messages without expecting them to reply back. How can I do it? Or Do I need to buy one for it to work?


Solution

  • It seems to me that you supply an unknown parameter to the function call. According to this docs page, it should be messagingServiceSid instead of messaging_service_sid.

    So you could should be:

    public function sendSms(string $message, string $phone)
        {
            $sid = env("TWILIO_ACCOUNT_SID");
            $token = env("TWILIO_AUTH_TOKEN");
            $messagingSid = env("MESSAGING_SERVICE_SID");
            $twilio = new Client($sid, $token);
    
            $message = $twilio->messages->create(
                $phone,
                [
                    "body" => $message,
                    "messagingServiceSid" => $messagingSid,
                ]
            )
    
    
            return $message->sid;
        }