SmsService.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use Exception;
  5. class SmsService
  6. {
  7. private static string $uri = "https://api.smsbao.com/sms";
  8. private static array $errors = [
  9. '30' => '错误密码',
  10. '40' => '账号不存在',
  11. '41' => '余额不足',
  12. '43' => "IP地址限制",
  13. '50' => "内容含有敏感词",
  14. '51' => '手机号码不正确'
  15. ];
  16. /**
  17. * @param $phone
  18. * @throws Exception
  19. */
  20. public static function sendPhoneCode($phone)
  21. {
  22. $username = config('services.sms.username');
  23. $password = config('services.sms.password');
  24. $content = config("services.sms.content");
  25. $code = mt_rand(100000, 999999);
  26. $content = str_replace("{code}", $code, $content);
  27. $url = static::$uri . "?u=" . $username . "&p=" . md5($password);
  28. $url .= "&c=" . urlencode($content);
  29. $url .= "&m=" . $phone;
  30. $code = file_get_contents($url);
  31. if (!empty(static::$errors[$code])) {
  32. throw new Exception(static::$errors[$code], HttpStatus::CUSTOM_ERROR);
  33. }
  34. if ($code != 0) throw new Exception("发送失败:$code", HttpStatus::CUSTOM_ERROR);
  35. }
  36. }