MailCaptcha.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 = 900;
  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. $this->error = 'Invalid email address.';
  50. return false;
  51. }
  52. return true;
  53. }
  54. /**
  55. * 执行发送邮箱验证码
  56. * @param string $email
  57. * @return bool
  58. */
  59. public function sendCaptcha(string $email): bool
  60. {
  61. // 缓存发送记录并判断次数
  62. if (!$this->record($email)) {
  63. return false;
  64. }
  65. // 生成验证码
  66. //$smsCaptcha = CaptchaApi::createSMS($email);
  67. $smsCaptcha = (string)mt_rand(100000, 999999);
  68. Cache::set("captchaSMS.{$email}", ['code' => $smsCaptcha, 'times' => $this->checkTimes], $this->expireTime);
  69. $mail = new PHPMailer(true);
  70. //dd(config('smtp'));
  71. try {
  72. //Server settings
  73. $mail->SMTPDebug = SMTP::DEBUG_OFF;//DEBUG_OFF,DEBUG_SERVER //Enable verbose debug output
  74. $mail->SMTPOptions = array(
  75. 'ssl' => array(
  76. 'verify_peer' => false,
  77. 'verify_peer_name' => false,
  78. 'allow_self_signed' => true
  79. )
  80. );
  81. /* $mail->isSMTP(); //Send using SMTP
  82. $mail->Host = config('smtp.host'); //Set the SMTP server to send through
  83. $mail->SMTPAuth = true; //Enable SMTP authentication
  84. $mail->Username = config('smtp.username'); //SMTP username
  85. $mail->Password = config('smtp.password'); //SMTP password
  86. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  87. $mail->Port = config('smtp.port'); */ //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  88. //Recipients
  89. //$mail->setFrom(config('smtp.from_address'), config('smtp.from_name'));
  90. $mail->isSMTP(); //Send using SMTP
  91. $mail->Host = 'tls://smtp.office365.com';//config('smtp.host'); //Set the SMTP server to send through
  92. $mail->SMTPAuth = true; //Enable SMTP authentication
  93. $mail->Username = 'register@freeshippingvapes.com';//config('smtp.username'); //SMTP username
  94. $mail->Password = 'Iloveyou1@#';//config('smtp.password'); //SMTP password
  95. $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable implicit TLS encryption
  96. $mail->Port = 587;//;config('smtp.port');
  97. $mail->setFrom('register@freeshippingvapes.com', 'Free Shipping Vps');
  98. $mail->addAddress($email, 'FSV'); //Add a recipient
  99. //$mail->addAddress('ellen@example.com'); //Name is optional
  100. //$mail->addReplyTo('info@example.com', 'Information');
  101. //$mail->addCC('cc@example.com');
  102. //$mail->addBCC('bcc@example.com');
  103. //Attachments
  104. //$mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
  105. //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
  106. //Content
  107. //$mail->isHTML(true); //Set email format to HTML
  108. $mail->Subject = 'Code';
  109. $mail->Body = 'Your code is ' . $smsCaptcha . '. Please use it in 15 minutes';
  110. $mail->AltBody = 'This is the Your Code for FreeShippingV';
  111. $mail->send();
  112. //echo 'Message has been sent';
  113. } catch (Exception $e) {
  114. //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  115. Log::error(__CLASS__ . ':' . __METHOD__ . $e->getMessage() . '---' . $mail->ErrorInfo);
  116. Log::error(__CLASS__ . ':' . __METHOD__ . ',error:' . $e->getMessage() . ',mailError:' . $mail->ErrorInfo);
  117. return false;
  118. }
  119. return true;
  120. }
  121. /**
  122. * 发送营销文本邮件
  123. * @param string $email
  124. * @param string $subject
  125. * @param string $body
  126. * @param string $altBody
  127. * @param bool $isHtml
  128. * @param string $name
  129. * @return bool
  130. */
  131. public function sendText(string $email, string $subject = '', string $body = '', string $altBody = '', bool $isHtml = false, string $name = 'vip'): bool
  132. {
  133. $mail = new PHPMailer(true);
  134. try {
  135. //Server settings
  136. $mail->SMTPDebug = SMTP::DEBUG_OFF; //Enable verbose debug output
  137. $mail->SMTPOptions = array(
  138. 'ssl' => array(
  139. 'verify_peer' => false,
  140. 'verify_peer_name' => false,
  141. 'allow_self_signed' => true
  142. )
  143. );
  144. $mail->isSMTP(); //Send using SMTP //SMTP password
  145. $mail->Host = config('smtp.host'); //Set the SMTP server to send through
  146. $mail->SMTPAuth = true; //Enable SMTP authentication
  147. $mail->Username = config('smtp.username'); //SMTP username
  148. $mail->Password = config('smtp.password');
  149. $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable implicit TLS encryption
  150. $mail->Port = config('smtp.port'); //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  151. //Recipients
  152. $mail->setFrom(config('smtp.from_address'), config('smtp.from_name'));
  153. $mail->addAddress($email, $name); //Add a recipient
  154. //Content
  155. if ($isHtml) {
  156. $mail->isHTML(true); //Set email format to HTML
  157. }
  158. $mail->Subject = $subject;
  159. $mail->Body = $body;
  160. if (!empty($altBody)) {
  161. $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  162. }
  163. $mail->send();
  164. //echo 'Message has been sent';
  165. } catch (Exception $e) {
  166. //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  167. Log::error(__CLASS__ . ':' . __METHOD__ . ',error:' . $e->getMessage() . ',mailError:' . $mail->ErrorInfo);
  168. return false;
  169. }
  170. return true;
  171. }
  172. /**
  173. * 记录短信验证码发送记录并判断是否超出发送限制
  174. * @param string $mobile
  175. * @return bool
  176. */
  177. private function record(string $email): bool
  178. {
  179. // 获取发送记录缓存
  180. $record = Cache::get("sendCaptchaEmail.$email");
  181. // 写入缓存:记录剩余发送次数
  182. if (empty($record)) {
  183. Cache::set("sendCaptchaEmail.$email", ['times' => $this->sendTimes - 1], $this->safeTime);
  184. return true;
  185. }
  186. // 判断发送次数是否合法
  187. if ($record['times'] <= 0) {
  188. $this->error = 'Sorry,up to the limit today.';
  189. return false;
  190. }
  191. // 发送次数递减
  192. Cache::update("sendCaptchaEmail.$email", ['times' => $record['times'] - 1]);
  193. return true;
  194. }
  195. /**
  196. * 数据验证
  197. * @param array $data
  198. * @throws BaseException
  199. */
  200. public function validate(array $data)
  201. {
  202. // 数据验证
  203. $validate = new ValidateEmailCaptcha;
  204. if (!$validate->check($data)) {
  205. throwError($validate->getError());
  206. }
  207. // 验证图形验证码
  208. // if (!CaptchaApi::check($data['captchaCode'], $data['captchaKey'])) {
  209. // throwError('很抱歉,图形验证码不正确');
  210. // }
  211. }
  212. public function checkCaptcha($captchaCode = '', $email = '')
  213. {
  214. log_record('captchaCode:' . $captchaCode.',email:' . $email,'info');
  215. //todo
  216. if (config('smtp.app_debug') && $captchaCode == '888888') {
  217. return true;
  218. }
  219. $localCode = Cache::get('captchaSMS.' . $email);
  220. if (empty($localCode) || empty($localCode['code']) || $localCode['code'] != $captchaCode) {
  221. throwError('Sorry, the code is invalid!');
  222. }
  223. return true;
  224. }
  225. }