Product.php 18 KB

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