sms.php 2.7 KB

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