Product.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. //图片搜索
  132. $image = input('image','');
  133. if(!empty($image)){
  134. $keyword = $this->search_by_image($image);
  135. //dump($keyword);
  136. if(empty($keyword)){
  137. $this->success('', []);
  138. }
  139. }
  140. $productModel = new productModel();
  141. /* if ($fid && !$sid) {
  142. $categoryModel = new \addons\unishop\model\Category();
  143. $sArr = $categoryModel->where('pid', $fid)->field('id')->select();
  144. $sArr = array_column($sArr, 'id');
  145. array_push($sArr, $fid);
  146. $productModel->where('category_id', 'in', $sArr);
  147. } else {
  148. $sid && $productModel->where(['category_id' => $sid]);
  149. }*/
  150. $fid && $productModel->where(['category_id' => $fid]);
  151. if(!empty($keyword)){
  152. $productModel->where('title', 'LIKE', '%'.$keyword.'%');
  153. }
  154. $result = $productModel
  155. ->where(['switch' => productModel::SWITCH_ON])
  156. ->page($page, $pagesize)
  157. ->order($by, $desc)
  158. ->field('id,title,info,image,sales_price,sales,real_sales')
  159. ->select();
  160. if ($result) {
  161. $result = collection($result)->toArray();
  162. } else {
  163. $result = [];
  164. }
  165. $this->success('', $result);
  166. }
  167. //腾讯云拍照识别商品
  168. //{"Response":{"Products":[{"Name":"按摩椅","Parents":"家用电器-个护健康","Confidence":99,"XMin":107,"YMin":59,"XMax":447,"YMax":366}],"RequestId":"187745fc-0497-441e-88f5-f3f17d854016"}}
  169. private function search_by_image($image){
  170. $image = $image.'?imageMogr2/thumbnail/800x800';
  171. $tencent_yun = config('tencent_yun');
  172. $secret_id = $tencent_yun['secret_id'];
  173. $secret_key = $tencent_yun['secret_key'];
  174. $token = "";
  175. $service = "tiia";
  176. $host = "tiia.tencentcloudapi.com";
  177. $req_region = "ap-beijing";
  178. $version = "2019-05-29";
  179. $action = "DetectProduct";
  180. $payload = json_encode(['ImageUrl' => localpath_to_netpath($image)]);
  181. $endpoint = "https://tiia.tencentcloudapi.com";
  182. $algorithm = "TC3-HMAC-SHA256";
  183. $timestamp = time();
  184. $date = gmdate("Y-m-d", $timestamp);
  185. // ************* 步骤 1:拼接规范请求串 *************
  186. $http_request_method = "POST";
  187. $canonical_uri = "/";
  188. $canonical_querystring = "";
  189. $ct = "application/json; charset=utf-8";
  190. $canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
  191. $signed_headers = "content-type;host;x-tc-action";
  192. $hashed_request_payload = hash("sha256", $payload);
  193. $canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";
  194. // ************* 步骤 2:拼接待签名字符串 *************
  195. $credential_scope = "$date/$service/tc3_request";
  196. $hashed_canonical_request = hash("sha256", $canonical_request);
  197. $string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";
  198. // ************* 步骤 3:计算签名 *************
  199. $secret_date = hash_hmac("sha256", $date, "TC3".$secret_key, true);
  200. $secret_service = hash_hmac("sha256", $service, $secret_date, true);
  201. $secret_signing = hash_hmac("sha256", "tc3_request", $secret_service, true);
  202. $signature = hash_hmac("sha256", $string_to_sign, $secret_signing);
  203. // ************* 步骤 4:拼接 Authorization *************
  204. $authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";
  205. // ************* 步骤 5:构造并发起请求 *************
  206. $headers = [
  207. "Authorization" => $authorization,
  208. "Content-Type" => "application/json; charset=utf-8",
  209. "Host" => $host,
  210. "X-TC-Action" => $action,
  211. "X-TC-Timestamp" => $timestamp,
  212. "X-TC-Version" => $version
  213. ];
  214. if ($req_region) {
  215. $headers["X-TC-Region"] = $req_region;
  216. }
  217. if ($token) {
  218. $headers["X-TC-Token"] = $token;
  219. }
  220. $headers = array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers);
  221. try {
  222. $timeOut = 3;
  223. $ch = curl_init();
  224. curl_setopt($ch, CURLOPT_URL, $endpoint);
  225. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  226. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  227. curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
  228. curl_setopt($ch, CURLOPT_HEADER, 0);
  229. curl_setopt($ch, CURLOPT_POST, 1);
  230. curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
  231. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  232. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  233. $response = curl_exec($ch);
  234. curl_close($ch);
  235. //return $response;
  236. $response = json_decode($response,true);
  237. if(is_array($response) && isset($response['Response']['Products'][0]['Name'])){
  238. $searchname = $response['Response']['Products'][0]['Name'];
  239. if(!empty($searchname)){
  240. return $searchname;
  241. }
  242. }
  243. return '';
  244. } catch (Exception $err) {
  245. //echo $err->getMessage();
  246. return '';
  247. }
  248. }
  249. /**
  250. * @ApiTitle (收藏/取消)
  251. * @ApiSummary (收藏/取消)
  252. * @ApiMethod (GET)
  253. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  254. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  255. * @ApiParams (name="id", type="string", required=true, description="商品id")
  256. * @ApiReturn ({"code":1,"msg":"","data":true})
  257. */
  258. public function favorite()
  259. {
  260. $id = input('id', 0);
  261. $id = \addons\unishop\extend\Hashids::decodeHex($id);
  262. $user_id = $this->auth->id;
  263. $favoriteModel = Favorite::get(function ($query) use ($id, $user_id) {
  264. $query->where(['user_id' => $user_id, 'product_id' => $id]);
  265. });
  266. if ($favoriteModel) {
  267. Favorite::destroy($favoriteModel->id);
  268. } else {
  269. $product = productModel::withTrashed()->where(['id' => $id, 'switch' => productModel::SWITCH_ON])->find();
  270. if (!$product) {
  271. $this->error('参数错误');
  272. }
  273. $favoriteModel = new Favorite();
  274. $favoriteModel->user_id = $user_id;
  275. $favoriteModel->product_id = $id;
  276. $product = $product->getData();
  277. $data['image'] = $product['image'];
  278. $data['market_price'] = $product['market_price'];
  279. $data['product_id'] = Hashids::encodeHex($product['id']);
  280. $data['sales_price'] = $product['sales_price'];
  281. $data['title'] = $product['title'];
  282. $favoriteModel->snapshot = json_encode($data);
  283. $favoriteModel->save();
  284. }
  285. $this->success('', true);
  286. }
  287. /**
  288. * @ApiTitle (收藏列表)
  289. * @ApiSummary (收藏列表)
  290. * @ApiMethod (GET)
  291. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  292. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  293. * @ApiParams (name="page", type="integer", required=true, description="页面")
  294. * @ApiParams (name="pagesize", type="integer", required=true, description="每页数量")
  295. * @ApiReturn ({"code":1,"msg":"","data":[]})
  296. *
  297. * @ApiReturnParams (name="id", type="integer", description="收藏id")
  298. * @ApiReturnParams (name="user_id", type="integer", description="用户id")
  299. * @ApiReturnParams (name="product.image", type="string", description="商品图片")
  300. * @ApiReturnParams (name="product.title", type="string", description="商品名称")
  301. * @ApiReturnParams (name="product.sales_price", type="string", description="商品销售价钱")
  302. * @ApiReturnParams (name="product.market_price", type="string", description="商品市场价钱")
  303. * @ApiReturnParams (name="product.product_id", type="string", description="商品id")
  304. * @ApiReturnParams (name="status", type="integer", description="是否还有效")
  305. *
  306. */
  307. public function favoriteList()
  308. {
  309. $page = input('page', 1);
  310. $pageSize = input('pagesize', 20);
  311. $list = (new Favorite)->where(['user_id' => $this->auth->id])->with(['product'])->page($page, $pageSize)->select();
  312. $list = collection($list)->toArray();
  313. foreach ($list as &$item) {
  314. if (!empty($item['product'])) {
  315. $item['status'] = 1;
  316. } else {
  317. $item['status'] = 0;
  318. $item['product'] = json_decode($item['snapshot'],true);
  319. $image = $item['product']['image'];
  320. $item['product']['image'] = Config::getImagesFullUrl($image);
  321. }
  322. unset($item['snapshot']);
  323. }
  324. $this->success('', $list);
  325. }
  326. /**
  327. * @ApiTitle (商品评论)
  328. * @ApiSummary (商品评论)
  329. * @ApiMethod (GET)
  330. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  331. * @ApiParams (name="product_id", type="string", required=true, description="商品id")
  332. * @ApiParams (name="page", type="integer", required=true, description="页面")
  333. * @ApiParams (name="pagesize", type="integer", required=true, description="每页数量")
  334. * @ApiReturn ({"code":1,"msg":"","data":[]})
  335. *
  336. * @ApiReturnParams (name="id", type="integer", description="评论id")
  337. * @ApiReturnParams (name="username", type="string", description="评论人名称")
  338. * @ApiReturnParams (name="avatar", type="string", description="评论人头像")
  339. * @ApiReturnParams (name="product_id", type="string", description="商品id")
  340. * @ApiReturnParams (name="comment", type="string", description="评论内容")
  341. * @ApiReturnParams (name="rate", type="integer", description="星星")
  342. * @ApiReturnParams (name="order_id", type="string", description="订单id")
  343. * @ApiReturnParams (name="spec", type="string", description="评论的规格")
  344. * @ApiReturnParams (name="anonymous", type="integer", description="是否匿名")
  345. * @ApiReturnParams (name="toptime", type="integer", description="是否置顶")
  346. * @ApiReturnParams (name="createtime_text", type="string", description="评论时间")
  347. *
  348. */
  349. public function evaluate()
  350. {
  351. $page = input('page', 1);
  352. $pageSize = input('pagesize', 20);
  353. $productId = input('product_id');
  354. $productId = \addons\unishop\extend\Hashids::decodeHex($productId);
  355. // 评价信息
  356. $evaluate = (new Evaluate)->alias('e')
  357. ->join('user u', 'e.user_id = u.id')
  358. ->where(['e.product_id' => $productId])
  359. ->field('u.username,u.avatar,e.*')
  360. ->order(['toptime' => 'desc', 'createtime' => 'desc'])
  361. ->page($page, $pageSize)
  362. ->select();
  363. if ($evaluate) {
  364. $evaluate = collection($evaluate)->append(['createtime_text'])->toArray();
  365. }
  366. $this->success('', $evaluate);
  367. }
  368. }