UserCoupons.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\Exception;
  6. class UserCoupons extends Api
  7. {
  8. protected $noNeedLogin = [];
  9. protected $noNeedRight = '*';
  10. protected $model = null;
  11. public function _initialize()
  12. {
  13. parent::_initialize();
  14. $this->model = Db::name('user_coupons');
  15. }
  16. /**
  17. * 列表
  18. * @return void
  19. */
  20. public function getList()
  21. {
  22. try {
  23. $status = $this->request->param('status',1);//状态:1待使用,2已失效
  24. $userId = $this->auth->id;
  25. $companyId = $this->auth->company_id;
  26. $field = 'id,coupon_name,coupon_info,endtime,number,remain';
  27. $where['user_id'] = $userId;
  28. $where['company_id'] = $companyId;
  29. $whereOr = [];
  30. if ($status == 1) {
  31. $where['remain'] = ['gt',0];
  32. } else {
  33. $whereOr['remain'] = ['elt',0];
  34. $whereOr['endtime'] = ['lt',time()];
  35. }
  36. $result = $this->model->field($field)->where($where)->where(function($query) use ($whereOr){
  37. $query->whereOr($whereOr);
  38. })->order('createtime desc')->autopage()->select();
  39. if (!empty($result)) {
  40. foreach ($result as $key => &$value) {
  41. !empty($value['endtime']) && $value['endtime'] = date('Y.m.d H:i:s',$value['endtime']);
  42. }
  43. }
  44. $this->success('获取成功',$result);
  45. } catch (Exception $e) {
  46. $this->error($e->getMessage());
  47. }
  48. }
  49. /**
  50. * 核销码
  51. * @return void
  52. */
  53. public function writeOff()
  54. {
  55. try {
  56. $id = $this->request->param('id',0);
  57. $companyId = $this->auth->company_id;
  58. $userId = $this->auth->id;
  59. $where['id'] = $id;
  60. $where['company_id'] = $companyId;
  61. $where['user_id'] = $userId;
  62. $where['remain'] = ['gt',0];
  63. $modelData = $this->model->where($where)->find();
  64. if (empty($modelData)) {
  65. throw new Exception('未找到相关信息');
  66. }
  67. //验证
  68. if ($modelData['endtime'] < time() || $modelData['remain'] < 1) {
  69. throw new Exception('该券已无法使用');
  70. }
  71. $text = 'hexiaocoupon_'.$id;
  72. $logo = '';
  73. $filRoute = '/uploads/temp/';
  74. $saveDir = ROOT_PATH.'public\uploads\temp'.DS;
  75. $fileStr = md5('coupon_'.$id);
  76. $localpng = $saveDir.$fileStr.'.png';
  77. //验证存在直接返回
  78. $userCouponsUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$filRoute.$fileStr.'.png';
  79. if (!file_exists($localpng)) {
  80. build_qrcode($text, $logo, $saveDir,$fileStr);
  81. }
  82. $result = [
  83. 'url' => $userCouponsUrl,
  84. ];
  85. $this->success('获取成功',$result);
  86. } catch (Exception $e) {
  87. $this->error($e->getMessage());
  88. }
  89. }
  90. }