SendCode.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace frontend\server;
  3. use frontend\base\Help;
  4. use Yii;
  5. use Overtrue\EasySms\EasySms;
  6. class SendCode
  7. {
  8. protected $Sstatus = 1;
  9. protected $Estatus = 0;
  10. public function send($input = '')
  11. {
  12. if (empty($input['mobilephone'])) return json_encode(['code' => 400, 'msg' => '请输入手机号']);
  13. $config = Yii::$app->params['smsconfig'];
  14. $easySms = new EasySms($config);
  15. $code = mt_rand(100000, 999999);
  16. $data = ['code' => $code, 'expire_time' => time() + 300];
  17. $sess = Yii::$app->session;
  18. $sessionkey = 'live_' . $input['mobilephone'];
  19. $sess[$sessionkey] = $data;
  20. try {
  21. $easySms->send($input['mobilephone'], [
  22. 'content' => '您的验证码为: ' . $code,
  23. 'template' => 'SMS_176928060',
  24. 'data' => [
  25. 'code' => $code
  26. ],
  27. ]);
  28. } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $e) {
  29. $this->saverecord($input['mobilephone'], $this->Estatus, $code, $input['purpose']);
  30. return json_encode(['code' => 400, 'msg' => '短信发送失败']);
  31. }
  32. $this->saverecord($input['mobilephone'], $this->Sstatus, $code, $input['purpose']);
  33. return json_encode(['code' => 200, 'msg' => '短信发送成功']);
  34. }
  35. //存入短信记录到数据库
  36. public function saverecord($mobile, $status, $code, $purpose)
  37. {
  38. $sendcoderecordnew = new \common\models\Sendcoderecord();
  39. $sendcoderecordnew->mobilephone = $mobile;
  40. $sendcoderecordnew->status = $status;
  41. $sendcoderecordnew->code = $code;
  42. $sendcoderecordnew->purpose = $purpose;
  43. $sendcoderecordnew->content = '【品房阁】您的验证码是' . $code . ', 在五分钟内有效。如非本人操作请忽略本短信。';
  44. $sendcoderecordnew->save();
  45. }
  46. }