Sms.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace app\api\controller;
  3. use app\api\ApiBaseController;
  4. use app\common\model\SmsAuthModel;
  5. use app\common\model\SmsLogModel;
  6. use app\common\model\SmsTemplateModel;
  7. use app\common\service\SmsService;
  8. use think\facade\Log;
  9. class Sms extends ApiBaseController
  10. {
  11. private $ip;
  12. private $token;
  13. public function _init()
  14. {
  15. //权限校验
  16. $token = $this->request->header('token');
  17. $ip = $this->request->ip();
  18. if (empty($token)) {
  19. ajax_success();
  20. }
  21. $auth = SmsAuthModel::where('token', $token)->find();
  22. if (empty($auth)) {
  23. Log::error("无权限token访问,token:{$token},ip:{$ip}");
  24. ajax_success();
  25. }
  26. if ($auth['ip'] != $ip) {
  27. Log::error("无权限ip访问,token:{$token},ip:{$ip}");
  28. ajax_success();
  29. }
  30. $this->ip = $ip;
  31. $this->token = $token;
  32. }
  33. public function send()
  34. {
  35. //接收短信参数
  36. $type = input('post.type', '');
  37. $mobile = input('post.mobile', '');
  38. $template_code = input('post.template_code', '');
  39. $template_param = input('post.template_param', []);
  40. if (empty($mobile) || empty($template_code) || empty($template_param)) {
  41. ajax_error('手机号或模板号或模板参数不能为空!');
  42. }
  43. //短信内容
  44. $template = SmsTemplateModel::where('code', $template_code)->find();
  45. if (empty($template)) {
  46. ajax_error('模板不存在!');
  47. }
  48. $content = $template['content'];
  49. if (!empty($template_param)) {
  50. foreach ($template_param as $k => $v) {
  51. $content = str_replace('${' . $k . '}', $v, $content);
  52. }
  53. }
  54. $res = SmsService::apiSend($mobile, $content, $type, $template, $template_param);
  55. //记录日志
  56. $log = [
  57. 'ip' => $this->ip,
  58. 'token' => $this->token,
  59. 'mobile' => $mobile,
  60. 'content' => $content,
  61. 'template_code' => $template_code,
  62. 'template_param' => json_encode($template_param),
  63. 'status' => $res['code'] ? 2 : 1,
  64. 'error' => $res['code'] ? $res['msg'] : '',
  65. ];
  66. SmsLogModel::create($log);
  67. //返回结果
  68. if ($res['code']) {
  69. ajax_error($res['msg']);
  70. }
  71. ajax_success();
  72. }
  73. public function getTemplateList()
  74. {
  75. $map = $this->dealLikeInput(['code']);
  76. $list = SmsTemplateModel::field(['code','content','comment'])
  77. ->where($map)
  78. ->limit(input('limit',10))
  79. ->page(input('page',1))
  80. ->select();
  81. $count = SmsTemplateModel::where($map)->count();
  82. ajax_success(['list'=>$list,'count'=>$count]);
  83. }
  84. }