如何在Laravel中实施SMS验证或OTP

时间:2018-07-13 09:33:58

标签: php laravel sms-gateway one-time-password

我是一个新的laravel用户,正在开发系统,被困在使用SMS进行用户验证的过程中,该消息将通过验证码发送给用户,用户将使用该验证码填写系统以验证其电话号码。

3 个答案:

答案 0 :(得分:1)

您可以为此使用laravel软件包:https://packagist.org/packages/intergo/sms.to-laravel-lumen 您可以通过Composer将此软件包安装到Laravel项目中。 然后在.env文件中设置所有这些配置值。

在安装和配置了软件包之后,您唯一要做的就是使用SmsTo门面:

    use SmsTo;
in class files (typically controllers) in which you will use this package for sending SMS.

Sending SMS to multiple numbers (broadcasting):
// Text message that will be sent to multiple numbers:
$message = 'Hello World!';

// Array of mobile phone numbers (starting with the "+" sign and country code):
$recipients = ['+4474*******', '+35799******', '+38164*******'];

// Send (broadcast) the $message to $recipients: 
SmsTo::setMessage($message)
    ->setRecipients($recipients)
    ->sendMultiple();
As for the sender ID and callback URL, the values set in the configuration file will be used by default. You can also specify these values by using the ->setSenderId() and ->setCallbackUrl() methods:

SmsTo::setMessage($message)
    ->setRecipients($recipients)
    ->setSenderId('YOUR_NAME')
    ->setCallbackUrl('https://your-site.com/smscallback')
    ->sendMultiple();
Please note that using these methods will override the values set in the configuration file.

Sending different SMS to single numbers:
 $messages = [
    [
        'to' => '+4474*******',
        'message' => 'Hello World!'
    ],
    [
        'to' => '+35799******',
        'message' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
    ],
];

SmsTo::setMessages($messages)->sendSingle();

希望获得帮助!

答案 1 :(得分:0)

修改表以使其具有用于存储otp的列“ otp”。

生成长度为4-6的otp。

function generateotp($len) {
   $result = '';
   for($i = 0; $i < $len; $i++) {
   $result .= mt_rand(0, 9);
   }
   return $result;
   }
   $otp= generateotp(6);

将此otp保存到表中。

   $user->otp=$otp;
   $user->save();

使用服务提供商的api将此otp发送到用户的手机。 您可以从批量短信提供商处获得otp / transactional短信api。

例如

http://xyz.xyz/api/send?user=id&apikey=apikey&sndr=senderid&mobile=mobile&text=$otp

然后重定向到用户将放置otp的页面。将用户输入的otp与表中存储的匹配。验证后或一段时间后,将表的otp设置为null。

以同样的方式,您还可以通过语音通话使用otp。

答案 2 :(得分:0)

基本上,您需要创建一个uuiduniqid())或任何随机数。并使用用户ID将其保存在数据库中。

要发送短信,这里有多种服务。波纹管是一些可靠的服务,价格也可以承受

https://aws.amazon.com/sns/

https://cloud.google.com/appengine/docs/standard/php/sms/twilio

您可以使用这些或任何您喜欢的东西。然后,您可以发送之前生成的uuid或随机编号。到用户的电话并要求用户输入您在表单中获得的验证码。

然后,您可以检查他们输入的代码是否与当前用户的otp代码匹配。如果是这样,请允许他们登录。

您还需要做的重要事情是将OTP_requires中间件添加到所有需要它的路由。在会话中检查OPT_Passed的值是否在会话中设置为true。如果是,请继续。否则,重定向到请求OPT页面。