sms.php 3.1 KB

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