MailCaptcha.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\index\service\passport;
  13. use think\facade\Log;
  14. use yiovo\cache\facade\Cache;
  15. use yiovo\captcha\facade\CaptchaApi;
  16. use app\api\validate\passport\EmailCaptcha as ValidateEmailCaptcha;
  17. use app\common\service\BaseService;
  18. use cores\exception\BaseException;
  19. use PHPMailer\PHPMailer\PHPMailer;
  20. use PHPMailer\PHPMailer\SMTP;
  21. use PHPMailer\PHPMailer\Exception;
  22. /**
  23. * 服务类:发送邮箱验证码
  24. * Class MailCaptcha
  25. * @package app\api\service\passport
  26. */
  27. class MailCaptcha extends BaseService
  28. {
  29. // 最大发送次数,默认10次
  30. protected int $sendTimes = 10;
  31. // 发送限制间隔时间,默认24小时
  32. protected int $safeTime = 86400;
  33. //验证码过期时间
  34. protected int $expireTime = 300;
  35. //可重复使用次数
  36. protected int $checkTimes = 5;
  37. /**
  38. * 发送邮件验证码
  39. * @param array $data
  40. * @return bool
  41. * @throws BaseException
  42. */
  43. public function handle(array $data): bool
  44. {
  45. // 数据验证
  46. $this->validate($data);
  47. // 执行发送短信
  48. if (!$this->sendCaptcha($data['mobile'])) {
  49. return false;
  50. }
  51. return true;
  52. }
  53. /**
  54. * 执行发送邮箱验证码
  55. * @param string $email
  56. * @return bool
  57. */
  58. public function sendCaptcha(string $email): bool
  59. {
  60. // 缓存发送记录并判断次数
  61. if (!$this->record($email)) {
  62. return false;
  63. }
  64. // 生成验证码
  65. //$smsCaptcha = CaptchaApi::createSMS($email);
  66. $smsCaptcha = (string)mt_rand(100000, 999999);
  67. Cache::set("captchaSMS.{$email}", ['code' => $smsCaptcha, 'times' => $this->checkTimes], $this->expireTime);
  68. $mail = new PHPMailer(true);
  69. //dd(config('smtp'));
  70. try {
  71. //Server settings
  72. $mail->SMTPDebug = SMTP::DEBUG_OFF;//DEBUG_OFF,DEBUG_SERVER //Enable verbose debug output
  73. $mail->SMTPOptions = array(
  74. 'ssl' => array(
  75. 'verify_peer' => false,
  76. 'verify_peer_name' => false,
  77. 'allow_self_signed' => true
  78. )
  79. );
  80. $mail->isSMTP(); //Send using SMTP
  81. $mail->Host = config('smtp.host'); //Set the SMTP server to send through
  82. $mail->SMTPAuth = true; //Enable SMTP authentication
  83. $mail->Username = config('smtp.username'); //SMTP username
  84. $mail->Password = config('smtp.password'); //SMTP password
  85. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  86. $mail->Port = config('smtp.port'); //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  87. //Recipients
  88. $mail->setFrom(config('smtp.from_address'), config('smtp.from_name'));
  89. $mail->addAddress($email, 'FSV'); //Add a recipient
  90. //$mail->addAddress('ellen@example.com'); //Name is optional
  91. //$mail->addReplyTo('info@example.com', 'Information');
  92. //$mail->addCC('cc@example.com');
  93. //$mail->addBCC('bcc@example.com');
  94. //Attachments
  95. //$mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
  96. //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
  97. //Content
  98. //$mail->isHTML(true); //Set email format to HTML
  99. $mail->Subject = 'Password';
  100. $mail->Body = 'Your code is ' . $smsCaptcha . '.Please use it in 15 minutes';
  101. $mail->AltBody = 'This is the Your Code for Free Shipping Vapes';
  102. $mail->send();
  103. //echo 'Message has been sent';
  104. } catch (Exception $e) {
  105. //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  106. Log::error(__CLASS__ . ':' . __METHOD__ . $e->getMessage() . '---' . $mail->ErrorInfo);
  107. Log::error(__CLASS__ . ':' . __METHOD__ . ',error:' . $e->getMessage() . ',mailError:' . $mail->ErrorInfo);
  108. return false;
  109. }
  110. return true;
  111. }
  112. /**
  113. * 发送营销文本邮件
  114. * @param string $email
  115. * @param string $subject
  116. * @param string $body
  117. * @param string $altBody
  118. * @param bool $isHtml
  119. * @param string $name
  120. * @return bool
  121. */
  122. public function sendText(string $email, string $subject = '', string $body = '', string $altBody = '', bool $isHtml = false, string $name = 'vip'): bool
  123. {
  124. $mail = new PHPMailer(true);
  125. try {
  126. //Server settings
  127. $mail->SMTPDebug = SMTP::DEBUG_OFF; //Enable verbose debug output
  128. $mail->SMTPOptions = array(
  129. 'ssl' => array(
  130. 'verify_peer' => false,
  131. 'verify_peer_name' => false,
  132. 'allow_self_signed' => true
  133. )
  134. );
  135. $mail->isSMTP(); //Send using SMTP //SMTP password
  136. $mail->Host = config('smtp.host'); //Set the SMTP server to send through
  137. $mail->SMTPAuth = true; //Enable SMTP authentication
  138. $mail->Username = config('smtp.username'); //SMTP username
  139. $mail->Password = config('smtp.password');
  140. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  141. $mail->Port = config('smtp.port'); //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  142. //Recipients
  143. $mail->setFrom(config('smtp.from_address'), config('smtp.from_name'));
  144. $mail->addAddress($email, $name); //Add a recipient
  145. //Content
  146. if ($isHtml) {
  147. $mail->isHTML(true); //Set email format to HTML
  148. }
  149. $mail->Subject = $subject;
  150. $mail->Body = $body;
  151. if (!empty($altBody)) {
  152. $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  153. }
  154. $mail->send();
  155. //echo 'Message has been sent';
  156. } catch (Exception $e) {
  157. //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  158. Log::error(__CLASS__ . ':' . __METHOD__ . ',error:' . $e->getMessage() . ',mailError:' . $mail->ErrorInfo);
  159. return false;
  160. }
  161. return true;
  162. }
  163. /**
  164. * 记录短信验证码发送记录并判断是否超出发送限制
  165. * @param string $mobile
  166. * @return bool
  167. */
  168. private function record(string $email): bool
  169. {
  170. // 获取发送记录缓存
  171. $record = Cache::get("sendCaptchaEmail.$email");
  172. // 写入缓存:记录剩余发送次数
  173. if (empty($record)) {
  174. Cache::set("sendCaptchaEmail.$email", ['times' => $this->sendTimes - 1], $this->safeTime);
  175. return true;
  176. }
  177. // 判断发送次数是否合法
  178. if ($record['times'] <= 0) {
  179. $this->error = 'Sorry,up to the limit today.';
  180. return false;
  181. }
  182. // 发送次数递减
  183. Cache::update("sendCaptchaEmail.$email", ['times' => $record['times'] - 1]);
  184. return true;
  185. }
  186. /**
  187. * 数据验证
  188. * @param array $data
  189. * @throws BaseException
  190. */
  191. public function validate(array $data)
  192. {
  193. // 数据验证
  194. $validate = new ValidateEmailCaptcha;
  195. if (!$validate->check($data)) {
  196. throwError($validate->getError());
  197. }
  198. // 验证图形验证码
  199. // if (!CaptchaApi::check($data['captchaCode'], $data['captchaKey'])) {
  200. // throwError('很抱歉,图形验证码不正确');
  201. // }
  202. }
  203. public function checkCaptcha($captchaCode = '', $email = '')
  204. {
  205. //todo
  206. if (config('smtp.app_debug') && $captchaCode == '888888') {
  207. return true;
  208. }
  209. $localCode = Cache::get('captchaSMS.' . $email);
  210. if (empty($localCode) || empty($localCode['code']) || $localCode['code'] != $captchaCode) {
  211. throwError('Sorry, the code is invalid!');
  212. }
  213. return true;
  214. }
  215. }