SmsService.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. * @return bool
  19. * @throws Exception
  20. */
  21. public static function sendPhoneCode($phone): bool
  22. {
  23. $username = config('services.sms.username');
  24. $password = config('services.sms.password');
  25. $content = config("services.sms.content");
  26. $code = mt_rand(100000, 999999);
  27. $content = str_replace("{code}", $code, $content);
  28. $url = static::$uri . "?u=" . $username . "&p=" . md5($password);
  29. $url .= "&c=" . urlencode($content);
  30. $url .= "&m=" . $phone;
  31. $code = file_get_contents($url);
  32. if (!empty(static::$errors[$code])) {
  33. throw new Exception(static::$errors[$code], HttpStatus::CUSTOM_ERROR);
  34. }
  35. if ($code == 0) return true;
  36. throw new Exception("发送失败", HttpStatus::CUSTOM_ERROR);
  37. }
  38. }