Product.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. namespace addons\unishop\controller;
  3. use addons\unishop\extend\Hashids;
  4. use addons\unishop\model\Config;
  5. use addons\unishop\model\Evaluate;
  6. use addons\unishop\model\Favorite;
  7. use addons\unishop\model\Product as productModel;
  8. use addons\unishop\model\Coupon;
  9. use think\Exception;
  10. /**
  11. * 商品
  12. */
  13. class Product extends Base
  14. {
  15. protected $noNeedLogin = ['detail', 'lists'];
  16. protected $frequently = ['detail', 'lists'];
  17. /**
  18. * @ApiTitle (产品详情)
  19. * @ApiSummary (产品详情)
  20. * @ApiMethod (GET)
  21. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  22. * @ApiParams (name="id", type="string", required=true, description="商品id")
  23. * @ApiReturn ({"code":1,"msg":"","data":{}})
  24. *
  25. * @ApiReturnParams (name="category_id", type="integer", description="分类id")
  26. * @ApiReturnParams (name="title", type="string", description="商品名称")
  27. * @ApiReturnParams (name="image", type="string", description="商品图片")
  28. * @ApiReturnParams (name="images_text", type="array", description="商品图片组")
  29. * @ApiReturnParams (name="desc", type="string", description="商品详情")
  30. * @ApiReturnParams (name="sales", type="integer", description="销量")
  31. * @ApiReturnParams (name="sales_price", type="string", description="销售价钱")
  32. * @ApiReturnParams (name="market_price", type="string", description="市场价钱")
  33. * @ApiReturnParams (name="product_id", type="string", description="商品id")
  34. * @ApiReturnParams (name="stock", type="integer", description="库存")
  35. * @ApiReturnParams (name="look", type="integer", description="观看量")
  36. * @ApiReturnParams (name="use_spec", type="integer", description="是否使用规格")
  37. * @ApiReturnParams (name="server", type="string", description="支持的服务")
  38. * @ApiReturnParams (name="favorite", type="integer", description="是否已收藏")
  39. * @ApiReturnParams (name="evaluate_data", type="json", description="{count:'评论数据',avg:'好评平均值'}")
  40. * @ApiReturnParams (name="coupon", type="array", description="可用优惠券")
  41. * @ApiReturnParams (name="cart_num", type="integer", description="购物车数量")
  42. * @ApiReturnParams (name="spec_list", type="array", description="规格键值数据")
  43. * @ApiReturnParams (name="spec_table_list", type="array", description="规格值数据")
  44. *
  45. */
  46. public function detail()
  47. {
  48. $productId = input('id');
  49. $productId = \addons\unishop\extend\Hashids::decodeHex($productId);
  50. try {
  51. $productModel = new productModel();
  52. $data = $productModel->where(['id' => $productId])->cache(10)->find();
  53. if (!$data) {
  54. $this->error(__('Goods not exist'));
  55. }
  56. if ($data['switch'] == productModel::SWITCH_OFF) {
  57. $this->error(__('Goods are off the shelves'));
  58. }
  59. // 真实浏览量加一
  60. $data->real_look++;
  61. $data->look++;
  62. $data->save();
  63. //服务
  64. /*$server = explode(',', $data->server);
  65. $configServer = json_decode(Config::getByName('server')['value'],true);
  66. $serverValue = [];
  67. foreach ($server as $k => $v) {
  68. if (isset($configServer[$v])) {
  69. $serverValue[] = $configServer[$v];
  70. }
  71. }
  72. $data->server = count($serverValue) ? implode(' · ', $serverValue) : '';*/
  73. // 默认没有收藏
  74. $data->favorite = false;
  75. // 评价
  76. $data['evaluate_data'] = (new Evaluate)->where(['product_id' => $productId])
  77. ->field('COUNT(*) as count, IFNULL(CEIL(AVG(rate)/5*100),0) as avg')
  78. ->cache(10)->find();
  79. //优惠券
  80. $data->coupon = (new Coupon)->where('endtime', '>', time())
  81. ->where(['switch' => Coupon::SWITCH_ON])->cache(10)->order('weigh DESC')->select();
  82. // 是否已收藏
  83. if ($this->auth->id) {
  84. $data->favorite = (new Favorite)->where(['user_id' => $this->auth->id, 'product_id' => $productId])->count();
  85. }
  86. // 购物车数量
  87. $data->cart_num = (new \addons\unishop\model\Cart)->where(['user_id' => $this->auth->id])->count();
  88. // 评价信息
  89. $evaluate = (new Evaluate)->alias('e')
  90. ->join('user u', 'e.user_id = u.id')
  91. ->where(['e.product_id' => $productId, 'toptime' => ['>', Evaluate::TOP_OFF]])
  92. ->field('u.username,u.avatar,e.*')
  93. ->order(['toptime' => 'desc', 'createtime' => 'desc'])->select();
  94. if ($evaluate) {
  95. $data->evaluate_list = collection($evaluate)->append(['createtime_text'])->toArray();
  96. }
  97. $data = $data->append(['images_text','videothumb', 'spec_list', 'spec_table_list'])->toArray();
  98. unset($data['switch']);
  99. } catch (Exception $e) {
  100. $this->error($e->getMessage());
  101. }
  102. $this->success('', $data);
  103. }
  104. /**
  105. * @ApiTitle (产品列表)
  106. * @ApiSummary (产品列表)
  107. * @ApiMethod (GET)
  108. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  109. * @ApiParams (name="sid", type="integer", required=false, description="二级分类id")
  110. * @ApiParams (name="fid", type="integer", required=true, description="一级分类id")
  111. * @ApiParams (name="page", type="integer", required=true, description="页面")
  112. * @ApiParams (name="pagesize", type="integer", required=true, description="每页数量")
  113. * @ApiParams (name="by", type="string", required=true, description="排序字段")
  114. * @ApiParams (name="desc", type="string", required=true, description="排序desc,asc")
  115. * @ApiReturn ({"code":1,"msg":"","data":[]})
  116. * @ApiReturnParams (name="title", type="string", description="商品名称")
  117. * @ApiReturnParams (name="image", type="string", description="商品图片")
  118. * @ApiReturnParams (name="sales", type="integer", description="销量")
  119. * @ApiReturnParams (name="sales_price", type="string", description="销售价钱")
  120. * @ApiReturnParams (name="product_id", type="string", description="商品id")
  121. */
  122. public function lists()
  123. {
  124. $page = input('page', 1);
  125. $pagesize = input('pagesize', 20);
  126. $by = input('by', 'weigh');
  127. $desc = input('desc', 'desc');
  128. // $sid = input('sid'); // 二级分类Id
  129. $fid = input('fid'); // 一级分类Id
  130. $keyword = input('keyword','');//搜索
  131. $productModel = new productModel();
  132. /* if ($fid && !$sid) {
  133. $categoryModel = new \addons\unishop\model\Category();
  134. $sArr = $categoryModel->where('pid', $fid)->field('id')->select();
  135. $sArr = array_column($sArr, 'id');
  136. array_push($sArr, $fid);
  137. $productModel->where('category_id', 'in', $sArr);
  138. } else {
  139. $sid && $productModel->where(['category_id' => $sid]);
  140. }*/
  141. $fid && $productModel->where(['category_id' => $fid]);
  142. if(!empty($keyword)){
  143. $productModel->where('title', 'LIKE', '%'.$keyword.'%');
  144. }
  145. $result = $productModel
  146. ->where(['switch' => productModel::SWITCH_ON])
  147. ->page($page, $pagesize)
  148. ->order($by, $desc)
  149. ->field('id,title,image,sales_price')
  150. ->select();
  151. if ($result) {
  152. $result = collection($result)->toArray();
  153. } else {
  154. $result = [];
  155. }
  156. $this->success('', $result);
  157. }
  158. //腾讯云拍照识别商品
  159. //{"Response":{"Products":[{"Name":"按摩椅","Parents":"家用电器-个护健康","Confidence":99,"XMin":107,"YMin":59,"XMax":447,"YMax":366}],"RequestId":"187745fc-0497-441e-88f5-f3f17d854016"}}
  160. private function search_by_image($image){
  161. $image = $image.'?imageMogr2/thumbnail/800x800';
  162. $tencent_yun = config('tencent_yun');
  163. $secret_id = $tencent_yun['secret_id'];
  164. $secret_key = $tencent_yun['secret_key'];
  165. $token = "";
  166. $service = "tiia";
  167. $host = "tiia.tencentcloudapi.com";
  168. $req_region = "ap-beijing";
  169. $version = "2019-05-29";
  170. $action = "DetectProduct";
  171. $payload = json_encode(['ImageUrl' => localpath_to_netpath($image)]);
  172. $endpoint = "https://tiia.tencentcloudapi.com";
  173. $algorithm = "TC3-HMAC-SHA256";
  174. $timestamp = time();
  175. $date = gmdate("Y-m-d", $timestamp);
  176. // ************* 步骤 1:拼接规范请求串 *************
  177. $http_request_method = "POST";
  178. $canonical_uri = "/";
  179. $canonical_querystring = "";
  180. $ct = "application/json; charset=utf-8";
  181. $canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
  182. $signed_headers = "content-type;host;x-tc-action";
  183. $hashed_request_payload = hash("sha256", $payload);
  184. $canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";
  185. // ************* 步骤 2:拼接待签名字符串 *************
  186. $credential_scope = "$date/$service/tc3_request";
  187. $hashed_canonical_request = hash("sha256", $canonical_request);
  188. $string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";
  189. // ************* 步骤 3:计算签名 *************
  190. $secret_date = hash_hmac("sha256", $date, "TC3".$secret_key, true);
  191. $secret_service = hash_hmac("sha256", $service, $secret_date, true);
  192. $secret_signing = hash_hmac("sha256", "tc3_request", $secret_service, true);
  193. $signature = hash_hmac("sha256", $string_to_sign, $secret_signing);
  194. // ************* 步骤 4:拼接 Authorization *************
  195. $authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";
  196. // ************* 步骤 5:构造并发起请求 *************
  197. $headers = [
  198. "Authorization" => $authorization,
  199. "Content-Type" => "application/json; charset=utf-8",
  200. "Host" => $host,
  201. "X-TC-Action" => $action,
  202. "X-TC-Timestamp" => $timestamp,
  203. "X-TC-Version" => $version
  204. ];
  205. if ($req_region) {
  206. $headers["X-TC-Region"] = $req_region;
  207. }
  208. if ($token) {
  209. $headers["X-TC-Token"] = $token;
  210. }
  211. $headers = array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers);
  212. try {
  213. $timeOut = 3;
  214. $ch = curl_init();
  215. curl_setopt($ch, CURLOPT_URL, $endpoint);
  216. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  217. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  218. curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
  219. curl_setopt($ch, CURLOPT_HEADER, 0);
  220. curl_setopt($ch, CURLOPT_POST, 1);
  221. curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
  222. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  223. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  224. $response = curl_exec($ch);
  225. curl_close($ch);
  226. //return $response;
  227. $response = json_decode($response,true);
  228. if(is_array($response) && isset($response['Response']['Products'][0]['Name'])){
  229. $searchname = $response['Response']['Products'][0]['Name'];
  230. if(!empty($searchname)){
  231. return $searchname;
  232. }
  233. }
  234. return '';
  235. } catch (Exception $err) {
  236. //echo $err->getMessage();
  237. return '';
  238. }
  239. }
  240. /**
  241. * @ApiTitle (收藏/取消)
  242. * @ApiSummary (收藏/取消)
  243. * @ApiMethod (GET)
  244. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  245. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  246. * @ApiParams (name="id", type="string", required=true, description="商品id")
  247. * @ApiReturn ({"code":1,"msg":"","data":true})
  248. */
  249. public function favorite()
  250. {
  251. $id = input('id', 0);
  252. $id = \addons\unishop\extend\Hashids::decodeHex($id);
  253. $user_id = $this->auth->id;
  254. $favoriteModel = Favorite::get(function ($query) use ($id, $user_id) {
  255. $query->where(['user_id' => $user_id, 'product_id' => $id]);
  256. });
  257. if ($favoriteModel) {
  258. Favorite::destroy($favoriteModel->id);
  259. } else {
  260. $product = productModel::withTrashed()->where(['id' => $id, 'switch' => productModel::SWITCH_ON])->find();
  261. if (!$product) {
  262. $this->error('参数错误');
  263. }
  264. $favoriteModel = new Favorite();
  265. $favoriteModel->user_id = $user_id;
  266. $favoriteModel->product_id = $id;
  267. $product = $product->getData();
  268. $data['image'] = $product['image'];
  269. $data['market_price'] = $product['market_price'];
  270. $data['product_id'] = Hashids::encodeHex($product['id']);
  271. $data['sales_price'] = $product['sales_price'];
  272. $data['title'] = $product['title'];
  273. $favoriteModel->snapshot = json_encode($data);
  274. $favoriteModel->save();
  275. }
  276. $this->success('', true);
  277. }
  278. /**
  279. * @ApiTitle (收藏列表)
  280. * @ApiSummary (收藏列表)
  281. * @ApiMethod (GET)
  282. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  283. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  284. * @ApiParams (name="page", type="integer", required=true, description="页面")
  285. * @ApiParams (name="pagesize", type="integer", required=true, description="每页数量")
  286. * @ApiReturn ({"code":1,"msg":"","data":[]})
  287. *
  288. * @ApiReturnParams (name="id", type="integer", description="收藏id")
  289. * @ApiReturnParams (name="user_id", type="integer", description="用户id")
  290. * @ApiReturnParams (name="product.image", type="string", description="商品图片")
  291. * @ApiReturnParams (name="product.title", type="string", description="商品名称")
  292. * @ApiReturnParams (name="product.sales_price", type="string", description="商品销售价钱")
  293. * @ApiReturnParams (name="product.market_price", type="string", description="商品市场价钱")
  294. * @ApiReturnParams (name="product.product_id", type="string", description="商品id")
  295. * @ApiReturnParams (name="status", type="integer", description="是否还有效")
  296. *
  297. */
  298. public function favoriteList()
  299. {
  300. $page = input('page', 1);
  301. $pageSize = input('pagesize', 20);
  302. $list = (new Favorite)->where(['user_id' => $this->auth->id])->with(['product'])->page($page, $pageSize)->select();
  303. $list = collection($list)->toArray();
  304. foreach ($list as &$item) {
  305. if (!empty($item['product'])) {
  306. $item['status'] = 1;
  307. } else {
  308. $item['status'] = 0;
  309. $item['product'] = json_decode($item['snapshot'],true);
  310. $image = $item['product']['image'];
  311. $item['product']['image'] = Config::getImagesFullUrl($image);
  312. }
  313. unset($item['snapshot']);
  314. }
  315. $this->success('', $list);
  316. }
  317. /**
  318. * @ApiTitle (商品评论)
  319. * @ApiSummary (商品评论)
  320. * @ApiMethod (GET)
  321. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  322. * @ApiParams (name="product_id", type="string", required=true, description="商品id")
  323. * @ApiParams (name="page", type="integer", required=true, description="页面")
  324. * @ApiParams (name="pagesize", type="integer", required=true, description="每页数量")
  325. * @ApiReturn ({"code":1,"msg":"","data":[]})
  326. *
  327. * @ApiReturnParams (name="id", type="integer", description="评论id")
  328. * @ApiReturnParams (name="username", type="string", description="评论人名称")
  329. * @ApiReturnParams (name="avatar", type="string", description="评论人头像")
  330. * @ApiReturnParams (name="product_id", type="string", description="商品id")
  331. * @ApiReturnParams (name="comment", type="string", description="评论内容")
  332. * @ApiReturnParams (name="rate", type="integer", description="星星")
  333. * @ApiReturnParams (name="order_id", type="string", description="订单id")
  334. * @ApiReturnParams (name="spec", type="string", description="评论的规格")
  335. * @ApiReturnParams (name="anonymous", type="integer", description="是否匿名")
  336. * @ApiReturnParams (name="toptime", type="integer", description="是否置顶")
  337. * @ApiReturnParams (name="createtime_text", type="string", description="评论时间")
  338. *
  339. */
  340. public function evaluate()
  341. {
  342. $page = input('page', 1);
  343. $pageSize = input('pagesize', 20);
  344. $productId = input('product_id');
  345. $productId = \addons\unishop\extend\Hashids::decodeHex($productId);
  346. // 评价信息
  347. $evaluate = (new Evaluate)->alias('e')
  348. ->join('user u', 'e.user_id = u.id')
  349. ->where(['e.product_id' => $productId])
  350. ->field('u.username,u.avatar,e.*')
  351. ->order(['toptime' => 'desc', 'createtime' => 'desc'])
  352. ->page($page, $pageSize)
  353. ->select();
  354. if ($evaluate) {
  355. $evaluate = collection($evaluate)->append(['createtime_text'])->toArray();
  356. }
  357. $this->success('', $evaluate);
  358. }
  359. }