MailCaptcha.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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__, ['errMsg' => $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->isSMTP(); //Send using SMTP //SMTP password
  129. $mail->Host = config('smtp.host'); //Set the SMTP server to send through
  130. $mail->SMTPAuth = true; //Enable SMTP authentication
  131. $mail->Username = config('smtp.username'); //SMTP username
  132. $mail->Password = config('smtp.password');
  133. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  134. $mail->Port = config('smtp.port'); //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  135. //Recipients
  136. $mail->setFrom(config('smtp.from_address'), config('smtp.from_name'));
  137. $mail->addAddress($email, $name); //Add a recipient
  138. //Content
  139. if ($isHtml) {
  140. $mail->isHTML(true); //Set email format to HTML
  141. }
  142. $mail->Subject = $subject;
  143. $mail->Body = $body;
  144. if (!empty($altBody)) {
  145. $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  146. }
  147. $mail->send();
  148. //echo 'Message has been sent';
  149. } catch (Exception $e) {
  150. //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  151. Log::error(__CLASS__ . ':' . __METHOD__ . ',error:' . $e->getMessage() . ',mailError:' . $mail->ErrorInfo);
  152. return false;
  153. }
  154. return true;
  155. }
  156. /**
  157. * 记录短信验证码发送记录并判断是否超出发送限制
  158. * @param string $mobile
  159. * @return bool
  160. */
  161. private function record(string $email): bool
  162. {
  163. // 获取发送记录缓存
  164. $record = Cache::get("sendCaptchaEmail.$email");
  165. // 写入缓存:记录剩余发送次数
  166. if (empty($record)) {
  167. Cache::set("sendCaptchaEmail.$email", ['times' => $this->sendTimes - 1], $this->safeTime);
  168. return true;
  169. }
  170. // 判断发送次数是否合法
  171. if ($record['times'] <= 0) {
  172. $this->error = 'Sorry,up to the limit today.';
  173. return false;
  174. }
  175. // 发送次数递减
  176. Cache::update("sendCaptchaEmail.$email", ['times' => $record['times'] - 1]);
  177. return true;
  178. }
  179. /**
  180. * 数据验证
  181. * @param array $data
  182. * @throws BaseException
  183. */
  184. public function validate(array $data)
  185. {
  186. // 数据验证
  187. $validate = new ValidateEmailCaptcha;
  188. if (!$validate->check($data)) {
  189. throwError($validate->getError());
  190. }
  191. // 验证图形验证码
  192. // if (!CaptchaApi::check($data['captchaCode'], $data['captchaKey'])) {
  193. // throwError('很抱歉,图形验证码不正确');
  194. // }
  195. }
  196. public function checkCaptcha($captchaCode = '', $email = '')
  197. {
  198. // if ($captchaCode == '888888') {
  199. // return true;
  200. // }
  201. $localCode = Cache::get('captchaSMS.' . $email);
  202. if (empty($localCode) || empty($localCode['code']) || $localCode['code'] != $captchaCode) {
  203. throwError('Sorry, the code is invalid!');
  204. }
  205. return true;
  206. }
  207. }