sms.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace common\components;
  3. use biz\merchant\services\MerchantAssetService;
  4. use biz\weixin\services\WxOpenService;
  5. use Yii;
  6. /**
  7. * 短信接口
  8. *
  9. 平台发短信
  10. 考虑短信总数是否足够
  11. 商家发短信
  12. 考虑总条数
  13. 考虑商家短信是否充值
  14. 商家系统发短信息不需要限制IP和数量
  15. 商家的客户发短信需要限制IP和数量
  16. *
  17. */
  18. class sms
  19. {
  20. //短信服务帐号
  21. const ACCOUNT = 'N2890342';
  22. //短信服务密码
  23. const PASSWORD = 'abc178c7';
  24. //一个用户一天同个IP申请的短信条数
  25. const LIMIT = 10;
  26. //商家发短信 shish 2019.12.24
  27. public static function merchantSend($mobile, $msg, $merchant)
  28. {
  29. $merchantId = $merchant['id'];
  30. $asset = MerchantAssetService::getByMerchantId($merchantId, true);
  31. $remainSmsNum = $asset->remainSmsNum;
  32. if ($remainSmsNum <= 0) {
  33. Yii::info($merchant['merchantName'] . '短信余额不足');
  34. return false;
  35. }
  36. $asset->remainSmsNum = --$remainSmsNum;
  37. $asset->save();
  38. self::freeSend($mobile, $msg, $merchant);
  39. }
  40. //自由发短,无ip和数量限制 shish 2019.12.24
  41. public static function freeSend($mobile, $msg, $merchant = null)
  42. {
  43. $open = WxOpenService::getById(1);
  44. $openName = $open['openName'];
  45. $sms = new chuanglanSMS(self::ACCOUNT, self::PASSWORD);
  46. $sign = isset($merchant) == true ? "【{$merchant['merchantName']}】" : "【{$openName}】";
  47. $msg .= $sign;
  48. $sms->send($mobile, $msg);
  49. }
  50. //发短信,有ip和用户数量限制 shish 2020.2.27
  51. public static function send($mobile, $msg, $merchant = null)
  52. {
  53. $open = WxOpenService::getById(1);
  54. $openName = $open['openName'];
  55. $sms = new chuanglanSMS(self::ACCOUNT, self::PASSWORD);
  56. $sign = isset($merchant) == true ? "【{$merchant['merchantName']}】" : "【{$openName}】";
  57. $msg .= $sign;
  58. //验证是否有权限发短信
  59. $uniqueId = isset($merchant['id']) ? $merchant['id'] : 1;
  60. $ip = httpUtil::ip();
  61. $statusKey = 'SMS_STATUS_' . $uniqueId . '_' . $ip;
  62. $hasSend = Yii::$app->redis->executeCommand('GET', [$statusKey]);
  63. if (!empty($hasSend)) {
  64. util::fail('请60秒后再操作');
  65. }
  66. $todayKey = 'SMS_NUM_' . date("Ymd") . '_' . $uniqueId . '_' . $ip;
  67. $num = Yii::$app->redis->executeCommand('GET', [$todayKey]);
  68. $num = is_numeric($num) ? $num : 0;
  69. if ($num > self::LIMIT) {
  70. util::fail('您今天申请的短信条数达到上限');
  71. }
  72. Yii::$app->redis->executeCommand('SETEX', [$statusKey, 60, 'hasSend']);
  73. Yii::$app->redis->executeCommand('SETEX', [$todayKey, 86400, ++$num]);
  74. $sms->send($mobile, $msg);
  75. }
  76. }