OrderController.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913
  1. <?php
  2. namespace mall\controllers;
  3. use biz\product\classes\ProductClass;
  4. use biz\shop\classes\ShopClass;
  5. use biz\wx\classes\WxMessageClass;
  6. use bizHd\custom\classes\HdClass;
  7. use bizHd\express\classes\HdDeliveryOrderClass;
  8. use bizHd\hb\classes\HbClass;
  9. use bizHd\homePageConfig\classes\HomePageModuleClass;
  10. use bizHd\order\classes\ScanPayClass;
  11. use bizHd\wx\classes\WxOpenClass;
  12. use bizMall\custom\classes\CustomClass;
  13. use bizMall\goods\classes\GoodsClass;
  14. use bizMall\order\classes\OrderClass;
  15. use bizMall\order\classes\OrderForwardClass;
  16. use bizMall\order\classes\OrderItemClass;
  17. use bizMall\order\services\OrderService;
  18. use bizMall\promote\services\CouponService;
  19. use bizMall\saas\services\RegionService;
  20. use bizMall\shop\classes\ShopExtClass;
  21. use bizMall\user\services\UserService;
  22. use common\components\dateUtil;
  23. use common\components\delivery\util\DeliveryQuoteUtil;
  24. use common\components\dict;
  25. use common\components\imgUtil;
  26. use common\components\noticeUtil;
  27. use common\components\orderSn;
  28. use common\components\stringUtil;
  29. use Yii;
  30. use common\components\util;
  31. use common\components\lakala\Lakala;
  32. use common\components\IntraCityExpress;
  33. class OrderController extends BaseController
  34. {
  35. //二维码收款使用
  36. public $guestAccess = ['order-relate', 'fast-pay'];
  37. public function actionInform()
  38. {
  39. $get = Yii::$app->request->get();
  40. $hdId = $get['hdId'] ?? 0;
  41. $account = $get['account'] ?? 0;
  42. $page = $get['page'] ?? '';
  43. $userId = $this->userId;
  44. noticeUtil::push("零售客户下单报错 hdId:{$hdId} account:{$account} userId:{$userId} page:{$page}", '15280215347');
  45. }
  46. //记账单列表 ssh 20250627
  47. public function actionDebtList()
  48. {
  49. $get = Yii::$app->request->get();
  50. $id = $get['id'] ?? 0;
  51. $where = [];
  52. $where['userId'] = $this->userId;
  53. if (!empty($id)) {
  54. $hd = \bizMall\hd\classes\HdClass::getById($id, true);
  55. if (empty($hd)) {
  56. util::fail('无效的花店');
  57. }
  58. $where['hdId'] = $id;
  59. }
  60. $where['debt'] = 1;
  61. $searchTime = $get['searchTime'] ?? '';
  62. if (!empty($searchTime)) {
  63. $startTime = $get['startTime'] ?? '';
  64. $endTime = $get['endTime'] ?? '';
  65. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  66. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  67. }
  68. $respond = OrderClass::getDebtList($where);
  69. util::success($respond);
  70. }
  71. //新计算运费
  72. public function actionNewFreight()
  73. {
  74. $post = Yii::$app->request->post();
  75. $hasMap = dict::getDict('hasMap');
  76. if ($hasMap == 0) {
  77. util::fail('暂不支持跑腿功能');
  78. }
  79. $mainData = $this->main;
  80. $wxStoreId = $mainData->wxStoreId ?? '';
  81. if (empty($wxStoreId)) {
  82. util::fail('商家还没有开通跑腿');
  83. }
  84. $cargoName = $post['cargo_name']; // 商品名称
  85. $cargo = [
  86. 'cargo_name' => $cargoName, // 商品名称
  87. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克 ---- 重量(用户未知)-- 大概
  88. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  89. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  90. 'cargo_num' => intval($post['package_num'])
  91. ];
  92. $originalLng = doubleval($post['user_lng']);
  93. $originalLat = doubleval($post['user_lat']);
  94. $userName = !empty($post['user_name']) ? $post['user_name'] : '游客';
  95. $orderData = [
  96. 'wx_store_id' => $wxStoreId,
  97. 'user_name' => $userName,
  98. 'user_phone' => $post['user_phone'],
  99. 'user_lng' => $originalLng,
  100. 'user_lat' => $originalLat,
  101. 'user_address' => $post['user_address'],
  102. 'cargo' => $cargo,
  103. ];
  104. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  105. $result = IntraCityExpress::preAddOrder($orderData);
  106. if ($result['errcode'] === 0) {
  107. util::success($result, "查询成功");
  108. } else {
  109. Yii::error("运费查询失败:" . json_encode($result));
  110. $errMsg = $result['errmsg'] ?? '';
  111. $errCode = $result['errcode'] ?? '';
  112. noticeUtil::push("运费查询失败,原因:" . $errMsg . ",编号:" . $errCode, '15280215347');
  113. util::fail('运费查询失败,请确认是否超过20公斤,编号896');
  114. }
  115. }
  116. //计算运费,请搜索关键词calc_freight,二个方法要合一起 ssh 20221014
  117. public function actionFreight()
  118. {
  119. $get = Yii::$app->request->get();
  120. $shop = $this->shop;
  121. $shopLat = isset($shop->lat) ? $shop->lat : '';
  122. $shopLong = isset($shop->long) ? $shop->long : '';
  123. // 判断地图功能是否正常。0 表示地图定位不可用,全部经纬度数据失效
  124. if (dict::getDict('hasMap') == 0) {
  125. $shopLat = '';
  126. $shopLong = '';
  127. }
  128. if (empty($shopLat) || empty($shopLong)) {
  129. util::success([
  130. 'distance' => 0,
  131. 'showDistance' => 0,
  132. 'fee' => 0,
  133. 'hasMap' => dict::getDict('hasMap'),
  134. 'shop' => 'fail' //门店引起的失败
  135. ]);
  136. }
  137. $userLat = $get['lat'] ?? '';
  138. $userLong = $get['long'] ?? '';
  139. if (empty($userLat) || empty($userLong)) {
  140. util::success([
  141. 'distance' => 0,
  142. 'showDistance' => 0,
  143. 'fee' => 0,
  144. 'hasMap' => dict::getDict('hasMap'),
  145. 'client' => 'fail' //用户端定位失败
  146. ]);
  147. }
  148. $weight = $get['weight'] ?? 0;
  149. if (empty($weight)) {
  150. util::success([
  151. 'distance' => 0,
  152. 'showDistance' => 0,
  153. 'fee' => 0,
  154. 'hasMap' => dict::getDict('hasMap'),
  155. 'weight' => 'fail' //重量不对
  156. ]);
  157. }
  158. //data: {distance: "321", showDistance: "0.3", fee: "12.00"}
  159. $respond = OrderClass::getDistanceFee($userLat, $userLong, $shopLat, $shopLong, $weight);
  160. util::success($respond);
  161. }
  162. // 零售商的限购花材信息(与批发端 PurchaseController::actionLimitBuyInfo 对应,按花店客户与 hd_limit_buy Redis)
  163. public function actionLimitBuyInfo()
  164. {
  165. $post = Yii::$app->request->post();
  166. $list = $post['list'] ?? [];
  167. if (empty($list) || !is_array($list)) {
  168. util::fail('请选择花材');
  169. }
  170. $hd = $this->hd;
  171. if (empty($hd)) {
  172. util::fail('没有找到花店');
  173. }
  174. if ($hd->shopId != $this->shopId) {
  175. util::fail('不是你的花店');
  176. }
  177. $hdCustomId = $hd->customId ?? 0;
  178. if (empty($hdCustomId)) {
  179. util::fail('没有找到客户');
  180. }
  181. $respond = \bizHd\product\classes\ProductClass::getLimitBuyInfoByList($list, $hdCustomId);
  182. util::success($respond);
  183. }
  184. //购买花材 ssh 20220511
  185. public function actionBuyItem()
  186. {
  187. $post = Yii::$app->request->post();
  188. $post['sjId'] = $this->sjId;
  189. $post['shopId'] = $this->shopId;
  190. $post['payWay'] = 0;
  191. $post['mainId'] = $this->mainId ?? 0;
  192. $post['userId'] = $this->userId ?? 0;
  193. //避免重复提交
  194. $userId = $this->userId;
  195. util::checkRepeatCommit($userId, 3);
  196. $shop = $this->shop;
  197. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  198. if ($openShop == 0) {
  199. util::fail('已休店');
  200. }
  201. //普莲花艺、叶上花、丰行、小武鲜花、九江云朵、源花汇、紫荆不能在花卉宝下单,多处要同步修改,关键词ls_mall_not_open
  202. $mainId = $this->mainId;
  203. if (getenv('YII_ENV') == 'production') {
  204. if (in_array($mainId, [40057, 7779, 42940, 26374, 10536, 65381])) {
  205. util::fail('暂时无法访问');
  206. }
  207. } else {
  208. if (in_array($mainId, [0, 1])) {
  209. util::fail('暂时无法访问');
  210. }
  211. }
  212. $hdId = $post['hdId'] ?? 0;
  213. $hd = HdClass::getById($hdId, true);
  214. if (empty($hd)) {
  215. util::fail('没有找到花店');
  216. }
  217. if ($hd->shopId != $this->shopId) {
  218. util::fail('不是你的花店');
  219. }
  220. $post['hdName'] = $hd->name ?? '';
  221. $hdCustomId = $hd->customId ?? 0;
  222. $custom = CustomClass::getById($hdCustomId, true);
  223. if (empty($custom)) {
  224. util::fail('没有找到客户');
  225. }
  226. $customName = $custom->name ?? '';
  227. $post['customId'] = $hdCustomId;
  228. $post['customName'] = $customName;
  229. $post['customNamePy'] = stringUtil::py($customName);
  230. $now = time();
  231. //订单30分钟后过期
  232. $expireTime = $now + 1800;
  233. $post['deadline'] = $expireTime;
  234. //商城
  235. $post['fromType'] = dict::getDict('fromType', 'mall');
  236. $productJson = $post['product'] ?? '';
  237. if (empty($productJson) && empty($groupId)) {
  238. util::fail('请选择商品');
  239. }
  240. $productList = json_decode($productJson, true);
  241. if (empty($productList)) {
  242. util::fail('请选择商品');
  243. }
  244. $ids = array_unique(array_filter(array_column($productList, 'productId')));
  245. $productInfoList = productClass::getByIds($ids, null, 'id');
  246. if (!empty($productInfoList)) {
  247. $presellData = [];
  248. $nowTime = strtotime(date("Y-m-d"));
  249. foreach ($productInfoList as $currentInfo) {
  250. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $this->mainId) {
  251. util::fail('只能选一家的商品,请清空重新选呢');
  252. }
  253. $presell = $currentInfo['presell'] ?? 0;
  254. $presellData[] = $presell;
  255. if ($presell == 1) {
  256. if (empty($post['reachDate'])) {
  257. util::fail('请选择配送或取货日期');
  258. }
  259. $sendTimeWant = $post['reachDate'];
  260. if (strtotime($sendTimeWant) < $nowTime) {
  261. util::fail('不能选择过去时间');
  262. }
  263. $hasDateStr = $currentInfo['presellDate'] ?? [];
  264. $hasDate = explode(',', trim($hasDateStr));
  265. if (empty($hasDate)) {
  266. util::fail('预售日期有问题,请提醒门店');
  267. }
  268. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  269. util::fail("有预售花材在{$sendTimeWant}没到货");
  270. }
  271. $post['presell'] = 1;
  272. }
  273. }
  274. if (count($productInfoList) != count($ids)) {
  275. util::fail('存在无效商品');
  276. }
  277. $presellData = array_unique($presellData);
  278. if (count($presellData) > 1) {
  279. util::fail('预售和非预售花材不能一起下单');
  280. }
  281. } else {
  282. util::fail('花材不存在');
  283. }
  284. $connection = Yii::$app->db;
  285. $transaction = $connection->beginTransaction();
  286. $transactionFinished = false;
  287. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  288. if ($transactionFinished) {
  289. return;
  290. }
  291. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  292. if ($transaction->isActive) {
  293. $transaction->rollBack();
  294. }
  295. });
  296. try {
  297. $orderValidTime = !getenv('ORDER_VALID_TIME') ? 600 : getenv('ORDER_VALID_TIME');
  298. $post['deadline'] = time() + $orderValidTime;
  299. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  300. $post['needPrint'] = dict::getDict('needPrint', 'need');
  301. $user = $this->user;
  302. $post['bookMobile'] = $user->mobile ?? '';
  303. $post['bookName'] = $user->name ?? '';
  304. $hasPay = 0;
  305. $modifyPrice = 0;
  306. //各个等级对应的price addPrice字段
  307. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  308. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  309. $totalWeight = 0;
  310. $totalNum = 0;
  311. $totalReachDiscount = 0;
  312. foreach ($productList as $eleKey => $element) {
  313. $level = 0;
  314. $productId = $element['productId'];
  315. $product = $productInfoList[$productId];
  316. if (empty($product)) {
  317. util::fail('有商品信息没有找到');
  318. }
  319. $num = $element['num'] ?? 0; // 此次购买数量
  320. $limitKey = \bizHd\product\classes\ProductClass::LIMIT_BUY_KEY . $productId;
  321. $hasBuyNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $hdCustomId]);
  322. $hasBuyNum = $num + ($hasBuyNum == null ? 0 : $hasBuyNum); // 已购买总数量
  323. $price = \bizGhs\product\classes\ProductClass::getFinalPrice($product, $level, $priceMap, $addPriceMap, 0, $num, $hasBuyNum);
  324. $reachNum = $product['reachNum'] ?? 0;
  325. $reachNumDiscount = $product['reachNumDiscount'] ?? 0;
  326. if ($reachNum > 0 && $num >= $reachNum && $reachNumDiscount > 0) {
  327. $currentReachDiscount = bcmul($reachNumDiscount, $num, 2);
  328. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  329. }
  330. $currentTotal = bcmul($price, $num, 2);
  331. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  332. $productList[$eleKey]['unitPrice'] = $price;
  333. $weight = $product['weight'] ?? 0;
  334. $currentWeight = bcmul($num, $weight, 2);
  335. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  336. $totalNum = bcadd($totalNum, $num);
  337. if ($product['limitBuy'] > 0) {
  338. $product['productId'] = $productId;
  339. \bizHd\product\classes\ProductClass::handleLimitBuy($product, $hdCustomId, floatval($num));
  340. }
  341. }
  342. $post['product'] = $productList;
  343. $post['reachDiscountPrice'] = $totalReachDiscount;
  344. //不能前端传运费过来,只能通过跑腿接口计算出来
  345. unset($post['sendCost']);
  346. $mapSet = ShopClass::hasIntraCity($this->shop);
  347. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  348. if (isset($post['sendType']) && $post['sendType'] == 2 && $openIntraCity != 0) {
  349. if ($openIntraCity == 2) {
  350. util::fail('不能使用跑腿');
  351. }
  352. $cargoName = '花材'; // 商品名称
  353. $cargo = [
  354. 'cargo_name' => $cargoName, // 商品名称
  355. 'cargo_weight' => intval($totalWeight * 1000), // 单位:克 -- 把千克转换为克 ---- 重量(用户未知)-- 大概
  356. 'cargo_price' => intval($modifyPrice * 100), // 单位:分 -- 把元转换为分
  357. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  358. 'cargo_num' => $totalNum
  359. ];
  360. $customName = $custom->name;
  361. $customMobile = $custom->mobile;
  362. if (empty($post['long']) || empty($post['lat'])) {
  363. util::fail('位置错误');
  364. }
  365. // $originalLng = doubleval($post['long']);
  366. // $originalLat = doubleval($post['lat']);
  367. // $city = $post['city'] ?? '';
  368. // $dist = $post['dist'] ?? '';
  369. // $address = $post['address'] ?? '';
  370. // $showAddress = $post['showAddress'] ?? '';
  371. // $userAddress = $city . $dist . $address . "({$showAddress})";
  372. // $main = $this->main;
  373. $shop = $this->shop;
  374. $shopLat = $shop->lat ?? '';
  375. $shopLong = $shop->long ?? '';
  376. if (empty($shopLat) || empty($shopLong)) {
  377. util::fail('商家门店地址定位未设置,编号263');
  378. }
  379. // $wxStoreId = $main->wxStoreId ?? 0;
  380. // if (empty($wxStoreId)) {
  381. // util::fail('商家还没有开通跑腿功能');
  382. // }
  383. // $orderData = [
  384. // 'wx_store_id' => $wxStoreId,
  385. // 'user_name' => $customName,
  386. // 'user_phone' => $customMobile,
  387. // 'user_lng' => $originalLng,
  388. // 'user_lat' => $originalLat,
  389. // 'user_address' => $userAddress,
  390. // 'cargo' => $cargo,
  391. // ];
  392. // //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  393. // $result = IntraCityExpress::preAddOrder($orderData);
  394. // $errCode = $result['errcode'] ?? 1;
  395. // if ($errCode != 0) {
  396. // $errMsg = $result['errmsg'] ?? '';
  397. // util::fail('获取运费错误:' . $errMsg);
  398. // }
  399. // $fee = $result['est_fee'] ?? 0;
  400. // $distance = $result['distance'] ?? 0;
  401. // $sendCost = bcdiv($fee, 100, 2);
  402. $distance = 0;
  403. $sendCost = 0;
  404. //生成随机订单号,不要跟原来的混起来,跑腿-销售单-
  405. $prefix = 'PT-XSD-' . $this->mainId . '-';
  406. $orderSn = $prefix . round(microtime(true) * 1000);
  407. $ghsInfo = ['mainId' => $this->mainId, 'shopId' => $this->shopId];
  408. // 这儿要调用跑腿接口计算运费和距离
  409. try {
  410. if (empty($post['deliveryPlatform'])) {
  411. util::fail('请选择跑腿');
  412. }
  413. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  414. 'productList' => $productList,
  415. 'deliveryPlatform' => $post['deliveryPlatform'],
  416. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  417. 'ghsInfo' => $ghsInfo,
  418. 'custom' => $this->user, // $custom 数据有问题,要是 user
  419. 'order' => [
  420. 'orderSn' => $orderSn,
  421. 'goodsType' => 1, //商品类型:0花束 1花材
  422. 'itemTotalAmount' => $modifyPrice,
  423. 'remark' => $post['remark'] ?? '',
  424. ],
  425. 'mainId' => $this->mainId,
  426. 'productCount' => $totalNum,
  427. ]);
  428. $sendCost = $quoteResult['sendCost'];
  429. $distance = $quoteResult['sendDistance'];
  430. } catch (\Exception $e) {
  431. util::fail($e->getMessage());
  432. }
  433. $post['sendCost'] = $sendCost;
  434. $post['sendDistance'] = $distance;
  435. //noticeUtil::push("零售订单(花材),获取运费:{$sendCost} 重量:{$totalWeight} 距离:{$distance}m 姓名:{$customName} 手机号 {$customMobile} 金额:{$modifyPrice} 数量:{$totalNum}", '15280215347');
  436. $modifyPrice = bcadd($modifyPrice, $sendCost, 2);
  437. }
  438. //红包使用,多有处,关键词 use_hb_action
  439. $hbId = $post['hbId'] ?? 0;
  440. $hb = null;
  441. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  442. $hb = HbClass::getById($hbId, true);
  443. if (!empty($hb)) {
  444. if ($hb->customId != $hdCustomId) {
  445. util::fail('不是你的红包');
  446. }
  447. if ($hb->amount != $post['hbAmount']) {
  448. util::fail('红包金额不相等'); //红包数据可能被串改
  449. }
  450. if ($hb->status == 1) {
  451. util::fail('红包已使用');
  452. }
  453. if ($hb->status == -1) {
  454. util::fail('红包已作废');
  455. }
  456. if ($hb->endTime < time()) {
  457. $hb->status = -1;
  458. $hb->save();
  459. util::fail('红包已失效');
  460. }
  461. if ($hb->beginTime > time()) {
  462. util::fail('红包可使用期未到');
  463. }
  464. if (bccomp($modifyPrice, $hb->minConsume) == -1) {
  465. util::fail("不满足最低消费金额{$hb->minConsume}元");
  466. }
  467. if ($this->shop->rechargeWeal == 3) {
  468. if (bccomp($custom->balance, $modifyPrice) == -1) {
  469. //不要限制提交
  470. //util::fail('此红包非余额支付不可用(您的余额不足)');
  471. }
  472. }
  473. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);//扣减红包
  474. } else {
  475. Yii::error('没有找到红包,hbId', $hbId . ' ' . __METHOD__);
  476. util::fail('红包无效');
  477. }
  478. }
  479. $post['bigNum'] = $totalNum;
  480. $post['modifyPrice'] = $modifyPrice;
  481. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  482. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  483. if (!empty($hb)) {
  484. $hb->status = 1;
  485. $hb->orderId = $return->id;
  486. $hb->save();
  487. }
  488. if (isset($return->shopId)) {
  489. if ($return->shopId == 7610) {
  490. if ($return->actPrice < 200) {
  491. if ($return->sendType == 0) {
  492. util::fail('满200元支持送货上门');
  493. }
  494. }
  495. }
  496. }
  497. if ($return->sendType == 2) {
  498. $ext = ShopExtClass::getByCondition(['shopId' => $return->shopId], true, null, 'id,shopId,thirdSend');
  499. if ($ext->thirdSend == 1) {
  500. util::fail('本店暂不能使用跑腿呢');
  501. }
  502. }
  503. $transaction->commit();
  504. $transactionFinished = true;
  505. \bizHd\product\classes\ProductClass::clearLimitBuyRollbackSnapshot();
  506. $orderSn = $return->orderSn ?? '';
  507. $orderPrice = $return->orderPrice ?? 0;
  508. $id = $return->id ?? 0;
  509. $getPayType = dict::getDict('getPayType');
  510. util::success(['orderSn' => $orderSn, 'totalPrice' => $orderPrice, 'couponId' => 0, 'id' => $id, 'getPayType' => $getPayType]);
  511. } catch (\Exception $e) {
  512. $transaction->rollBack();
  513. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  514. $transactionFinished = true;
  515. Yii::error("失败原因:" . $e->getMessage());
  516. util::fail('下单失败');
  517. }
  518. }
  519. //商城下单操作 ssh 2019.12.3
  520. public function actionCreateOrder()
  521. {
  522. $post = Yii::$app->request->post();
  523. //避免重复提交
  524. $userId = $this->userId;
  525. util::checkRepeatCommit($userId, 3);
  526. $shop = $this->shop;
  527. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  528. if ($openShop == 0) {
  529. util::fail('已休店');
  530. }
  531. $goodsId = $post['goodsId'] ?? 0;
  532. $specGoodsId = (int)($post['specGoodsId'] ?? 0);
  533. $goodsNum = isset($post['goodsNum']) && $post['goodsNum'] > 0 ? $post['goodsNum'] : 1;
  534. $sendType = $post['sendType'] ?? dict::getDict('sendType', 'thirdSend');
  535. if (empty($goodsId)) {
  536. util::fail('请选择商品');
  537. }
  538. $mainId = $this->mainId;
  539. $goodsInfo = GoodsClass::getById($goodsId, true);
  540. if (empty($goodsInfo)) {
  541. util::fail('没有找到商品');
  542. }
  543. if ($goodsInfo->mainId != $mainId) {
  544. util::fail('不是你的商品');
  545. }
  546. if ($specGoodsId > 0) {
  547. $specGoods = GoodsClass::getById($specGoodsId, true);
  548. if (empty($specGoods) || $specGoods->mainId != $mainId || $specGoods->masterId != $goodsId || $specGoods->delStatus != 0 || $specGoods->status != 1) {
  549. util::fail('规格不可用');
  550. }
  551. $goodsInfo = $specGoods;
  552. } elseif ((int)($goodsInfo->masterId ?? 0) === 0) {
  553. $hasSpecs = GoodsClass::getByCondition(['masterId'=>$goodsId, 'delStatus'=>0], true);
  554. if (!empty($hasSpecs)) util::fail('请选择规格');
  555. }
  556. $stock = $goodsInfo->stock ?? 0;
  557. if ($stock <= 0) {
  558. util::fail('库存不足');
  559. }
  560. $saleGoodsId = $specGoodsId > 0 ? $specGoodsId : $goodsId;
  561. $activityType = strval($post['activityType'] ?? '');
  562. //事务处理
  563. $connection = Yii::$app->db;
  564. $transaction = $connection->beginTransaction();
  565. $transactionFinished = false;
  566. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  567. if ($transactionFinished) {
  568. return;
  569. }
  570. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  571. if ($transaction->isActive) {
  572. $transaction->rollBack();
  573. }
  574. });
  575. try {
  576. $custom = $this->custom;
  577. if (empty($custom)) {
  578. util::fail('个人信息缺失');
  579. }
  580. $customId = $custom->id ?? 0;
  581. $hd = $this->hd;
  582. $post['customId'] = $customId;
  583. $customName = $custom->name ?? '';
  584. $post['customName'] = $customName;
  585. $post['customNamePy'] = stringUtil::py($customName);
  586. $post['hdId'] = $hd->id ?? 0;
  587. $post['hdName'] = $hd->name ?? '';
  588. $user = $this->user;
  589. $post['bookName'] = $user->name ?? '';
  590. $bookMobile = !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  591. $bookMobile = empty($bookMobile) && !empty($user->mobile) ? $user->mobile : $bookMobile;
  592. $post['bookMobile'] = $bookMobile;
  593. $post['payWay'] = 0;
  594. $shop = $this->shop;
  595. // 秒杀商品:不信任前端传的价格,独立回查 Redis 秒杀配置核实活动状态/库存/限购后再核价
  596. $seckillRow = null;
  597. if ($activityType === 'seckill') {
  598. $seckillRow = HomePageModuleClass::getSeckillActiveRow($mainId, $saleGoodsId);
  599. if (empty($seckillRow)) {
  600. util::fail('秒杀活动已结束或商品已下架,请重新选择');
  601. }
  602. $seckillStock = floatval($seckillRow['stock'] ?? 0);
  603. $soldCount = HomePageModuleClass::getSeckillSoldCount($mainId, $saleGoodsId);
  604. if (bcadd($soldCount, $goodsNum, 2) > $seckillStock) {
  605. util::fail('秒杀库存不足,请重新选择');
  606. }
  607. $seckillLimit = floatval($seckillRow['limit'] ?? 0);
  608. if ($seckillLimit > 0) {
  609. $boughtCount = HomePageModuleClass::getSeckillCustomBoughtCount($mainId, $saleGoodsId, $customId);
  610. if (bcadd($boughtCount, $goodsNum, 2) > $seckillLimit) {
  611. util::fail("秒杀商品每人限购{$seckillLimit}件,已超出可购买数量");
  612. }
  613. }
  614. }
  615. if ($seckillRow) {
  616. $goodsInfo->priceType = 1;
  617. $unitPrice = floatval($seckillRow['price'] ?? 0);
  618. if ($unitPrice <= 0) {
  619. util::fail('秒杀价格异常,不能下单');
  620. }
  621. // 通过校验后立即预占名额,失败/异常时随事务一起回滚(见 register_shutdown_function)
  622. HomePageModuleClass::reserveSeckillPurchase($mainId, $saleGoodsId, $customId, $goodsNum);
  623. } else {
  624. $params = [];
  625. $goodsData = $goodsInfo->attributes;
  626. $ret = \bizHd\goods\classes\GoodsClass::getFinalPrice($goodsData, $shop, $custom, $params);
  627. $goodsInfo->priceType = $ret['priceType'] ?? 0;
  628. if ($goodsInfo->priceType == 0) {
  629. util::fail('没有价格,不能下单哈');
  630. }
  631. $unitPrice = $ret['price'] ?? 0;
  632. if ($unitPrice <= 0) {
  633. util::fail('没有价格,不能下单呢');
  634. }
  635. }
  636. //计算总金额
  637. $goodsPrice = $unitPrice * $goodsNum;
  638. //计算运费
  639. $sendDistance = 0;
  640. $sendCost = 0;
  641. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  642. $receiveUserName = $post['receiveUserName'] ?? '';
  643. if (empty($receiveUserName)) {
  644. util::fail('请填写收花人名字');
  645. }
  646. $receiveMobile = $post['receiveMobile'] ?? '';
  647. if (empty($receiveMobile)) {
  648. util::fail('请填写收花人手机号');
  649. }
  650. if (!stringUtil::isMobile($receiveMobile)) {
  651. util::fail('收花人手机号错误');
  652. }
  653. }
  654. $mapSet = ShopClass::hasIntraCity($shop);
  655. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  656. if ($sendType == dict::getDict('sendType', 'thirdSend') && $openIntraCity != 0) {
  657. // if (dict::getDict('hasMap') == 0) {
  658. // util::fail('不能使用跑腿,请选其它方式');
  659. // }
  660. // $lat = $post['lat'] ?? '';
  661. // $lng = $post['long'] ?? '';
  662. // if ((empty($lat) || empty($lng))) { // 当 hasMap 为1时,经纬数据是必要的
  663. // util::fail('请填写正确地址');
  664. // }
  665. // $address = $post['address'] ?? '';
  666. // $floor = $post['floor'] ?? '';
  667. // $fullAddress = $address . $floor;
  668. // $post['fullAddress'] = $fullAddress;
  669. // $shopLat = $shop->lat ?? '';
  670. // $shopLong = $shop->long ?? '';
  671. // if (empty($shopLat) || empty($shopLong)) {
  672. // util::fail('商家门店地址定位未设置,编号8966');
  673. // }
  674. // $weight = $goodsInfo->weight ?? 0;
  675. // if ($weight <= 0) {
  676. // util::fail('商品没有重量');
  677. // }
  678. // $totalWeight = bcmul($weight, $goodsNum, 2);
  679. // $cargoName = '鲜花'; // 商品名称
  680. // $cargo = [
  681. // 'cargo_name' => $cargoName, // 商品名称
  682. // 'cargo_weight' => intval($totalWeight * 1000), // 单位:克 -- 把千克转换为克 ---- 重量(用户未知)-- 大概
  683. // 'cargo_price' => intval($goodsPrice * 100), // 单位:分 -- 把元转换为分
  684. // 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  685. // 'cargo_num' => $goodsNum
  686. // ];
  687. // $customName = $custom->name;
  688. // $customMobile = $custom->mobile;
  689. // if (empty($post['long']) || empty($post['lat'])) {
  690. // util::fail('位置错误');
  691. // }
  692. // $originalLng = doubleval($post['long']);
  693. // $originalLat = doubleval($post['lat']);
  694. // $city = $post['city'] ?? '';
  695. // $dist = $post['dist'] ?? '';
  696. // $address = $post['address'] ?? '';
  697. // $showAddress = $post['showAddress'] ?? '';
  698. // $userAddress = $city . $dist . $address . "({$showAddress})";
  699. // $main = $this->main;
  700. // $shopLat = $shop->lat ?? '';
  701. // $shopLong = $shop->long ?? '';
  702. // if (empty($shopLat) || empty($shopLong)) {
  703. // util::fail('商家门店地址定位未设置,编号6880');
  704. // }
  705. // $wxStoreId = $main->wxStoreId ?? 0;
  706. // if (empty($wxStoreId)) {
  707. // util::fail('商家还没有开通跑腿功能');
  708. // }
  709. // $orderData = [
  710. // 'wx_store_id' => $wxStoreId,
  711. // 'user_name' => $customName,
  712. // 'user_phone' => $customMobile,
  713. // 'user_lng' => $originalLng,
  714. // 'user_lat' => $originalLat,
  715. // 'user_address' => $userAddress,
  716. // 'cargo' => $cargo,
  717. // ];
  718. // //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  719. // $result = IntraCityExpress::preAddOrder($orderData);
  720. // $errCode = $result['errcode'] ?? 1;
  721. // if ($errCode != 0) {
  722. // $errMsg = $result['errmsg'] ?? '';
  723. // util::fail('获取运费错误:' . $errMsg);
  724. // }
  725. // $fee = $result['est_fee'] ?? 0;
  726. // $sendDistance = $result['distance'] ?? 0;
  727. // $sendCost = bcdiv($fee, 100, 2);
  728. // //免运费的不收运费
  729. // if ($goodsInfo->freightType == 1) {
  730. // $sendCost = 0;
  731. // }
  732. // noticeUtil::push("零售订单!获取运费:{$sendCost} 重量:{$totalWeight} 距离:{$sendDistance} 姓名:{$customName} 手机号 {$customMobile} 经纬 {$originalLng} {$originalLat} 金额:{$goodsPrice} 数量:{$goodsNum}", '15280215347');
  733. if ($openIntraCity == 2) {
  734. util::fail('不能使用跑腿');
  735. }
  736. $cutomInfo = [
  737. 'name' => $post['receiveUserName'],
  738. 'mobile' => $post['receiveMobile'],
  739. 'fullAddress' => $post['address'],
  740. 'floor' => $post['floor'],
  741. 'dist' => $post[''] ?? '',
  742. 'lat' => $post['lat'],
  743. 'long' => $post['long'],
  744. 'address' => $post['address'],
  745. 'city' => $post['city'],
  746. ];
  747. $cutomInfo = (object)$cutomInfo;
  748. // 生成随机花束订单号
  749. $prefix = 'KD_CS-' . $this->mainId . '-';
  750. $orderSn = $prefix . round(microtime(true) * 1000);
  751. // 使用 DeliveryQuoteUtil 获取配送报价
  752. try {
  753. if ($goodsInfo->weight > 5) {
  754. $goodsInfo->weight = 5;
  755. }
  756. if (empty($post['deliveryPlatform'])) {
  757. util::fail('请选择跑腿');
  758. }
  759. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  760. 'productList' => [['bigNum' => $goodsNum, 'weight' => $goodsInfo->weight]],
  761. 'deliveryPlatform' => $post['deliveryPlatform'],
  762. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  763. 'ghsInfo' => ['mainId' => $mainId, 'shopId' => $this->shopId],
  764. 'custom' => $cutomInfo,
  765. 'order' => [
  766. 'orderSn' => $orderSn,
  767. 'goodsType' => 0, //商品类型:0花束 1花材
  768. 'itemTotalAmount' => $goodsPrice,
  769. 'remark' => $post['remark'] ?? '',
  770. 'freightType' => $goodsInfo->freightType,
  771. ],
  772. 'mainId' => $this->mainId,
  773. 'productCount' => $goodsNum,
  774. ]);
  775. $sendCost = $quoteResult['sendCost'];
  776. $sendDistance = $quoteResult['sendDistance'];
  777. noticeUtil::push("零售订单(花束),获取运费:{$sendCost} 重量:{$goodsInfo->weight} 距离:{$sendDistance}m 姓名:{$customName} 金额:{$goodsPrice} 数量:{$goodsNum}");
  778. } catch (\Exception $e) {
  779. util::fail($e->getMessage());
  780. }
  781. }
  782. $post['sendDistance'] = $sendDistance;
  783. $post['sendCost'] = $sendCost;
  784. $post['sjId'] = $this->sjId;
  785. $post['shopId'] = $this->shopId;
  786. $post['mainId'] = $mainId;
  787. $post['userId'] = $this->userId;
  788. if ($goodsInfo->priceType == 0) {
  789. util::fail('没有价格,不能下单');
  790. }
  791. $modifyPrice = stringUtil::calcAdd($sendCost, $goodsPrice);
  792. //非门店订单
  793. $post['store'] = 0;
  794. //红包使用,多有处,关键词 use_hb_action
  795. $hbId = $post['hbId'] ?? 0;
  796. $hb = null;
  797. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  798. $hb = HbClass::getById($hbId, true);
  799. if (!empty($hb)) {
  800. if ($hb->customId != $customId) {
  801. util::fail('不是你的红包');
  802. }
  803. if ($hb->amount != $post['hbAmount']) {
  804. util::fail('红包金额不相等'); //红包数据可能被串改
  805. }
  806. if ($hb->status == 1) {
  807. util::fail('红包已使用');
  808. }
  809. if ($hb->status == -1) {
  810. util::fail('红包已作废');
  811. }
  812. if ($hb->endTime < time()) {
  813. $hb->status = -1;
  814. $hb->save();
  815. util::fail('红包已失效');
  816. }
  817. if ($hb->beginTime > time()) {
  818. util::fail('红包可使用期未到');
  819. }
  820. if ($modifyPrice < $hb->minConsume) {
  821. util::fail("不满足最低消费金额{$hb->minConsume}元");
  822. }
  823. if ($this->shop->rechargeWeal == 3) {
  824. if ($custom->balance < $modifyPrice) {
  825. util::fail('此红包非余额支付不可用(您的余额不足)');
  826. }
  827. }
  828. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);//扣减红包
  829. } else {
  830. Yii::error('没有找到红包,hbId', $hbId . ' ' . __METHOD__);
  831. util::fail('红包无效');
  832. }
  833. }
  834. $post['modifyPrice'] = $modifyPrice;
  835. //非自取订单考虑配送时间
  836. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  837. $sendType = $post['sendType'] ?? 0;
  838. if ($sendType != 1) {
  839. if (empty($post['reachPeriod'])) {
  840. util::fail('请选择配送时间哈');
  841. }
  842. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  843. }
  844. $now = time();
  845. $expireTime = $now + 1800;//订单30分钟后过期
  846. $post['deadline'] = $expireTime;
  847. $orderSn = orderSn::getOrderSn();
  848. $post['orderSn'] = $orderSn;
  849. $post['fromType'] = dict::getDict('fromType', 'mall');
  850. $post['cash'] = 0;
  851. $post['mainId'] = $mainId;
  852. $post['needPrint'] = dict::getDict('needPrint', 'need');
  853. $hasPay = 0;
  854. $product = [['productId' => $saleGoodsId, 'unitType' => 0, 'property' => 0, 'unitPrice' => $unitPrice, 'num' => $goodsNum]];
  855. $post['product'] = $product;
  856. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  857. //红包保存订单id
  858. if (!empty($hb)) {
  859. $hb->status = 1;
  860. $hb->orderId = $return->id;
  861. $hb->save();
  862. }
  863. $orderId = $return->id;
  864. $orderSn = $return->orderSn;
  865. $actPrice = $return->actPrice ?? 0;
  866. $transaction->commit();
  867. $transactionFinished = true;
  868. HomePageModuleClass::clearSeckillReservationSnapshot();
  869. util::success(['orderSn' => $orderSn, 'totalPrice' => $actPrice, 'couponId' => 0, 'id' => $orderId]);
  870. } catch (Exception $e) {
  871. $transaction->rollBack();
  872. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  873. $transactionFinished = true;
  874. Yii::info("失败原因:" . $e->getMessage());
  875. util::fail('下单失败');
  876. }
  877. }
  878. /**
  879. * 花束+花材合并结算下单
  880. * 复用 OrderService::createHdOrder,不改动 buy-item / create-order
  881. */
  882. public function actionCreateMixOrder()
  883. {
  884. $post = Yii::$app->request->post();
  885. $post['sjId'] = $this->sjId;
  886. $post['shopId'] = $this->shopId;
  887. $post['payWay'] = 0;
  888. $post['mainId'] = $this->mainId ?? 0;
  889. $post['userId'] = $this->userId ?? 0;
  890. $userId = $this->userId;
  891. util::checkRepeatCommit($userId, 3);
  892. $shop = $this->shop;
  893. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  894. if ($openShop == 0) {
  895. util::fail('已休店');
  896. }
  897. $mainId = $this->mainId;
  898. if (getenv('YII_ENV') == 'production') {
  899. if (in_array($mainId, [40057, 7779, 42940, 26374, 10536, 65381])) {
  900. util::fail('暂时无法访问');
  901. }
  902. }
  903. $hdId = $post['hdId'] ?? 0;
  904. $hd = HdClass::getById($hdId, true);
  905. if (empty($hd)) {
  906. util::fail('没有找到花店');
  907. }
  908. if ($hd->shopId != $this->shopId) {
  909. util::fail('不是你的花店');
  910. }
  911. $post['hdName'] = $hd->name ?? '';
  912. // 合并结算沿用花材购物车的客户身份(花店客户)
  913. $hdCustomId = $hd->customId ?? 0;
  914. $custom = CustomClass::getById($hdCustomId, true);
  915. if (empty($custom)) {
  916. util::fail('没有找到客户');
  917. }
  918. $customName = $custom->name ?? '';
  919. $post['customId'] = $hdCustomId;
  920. $post['customName'] = $customName;
  921. $post['customNamePy'] = stringUtil::py($customName);
  922. $productJson = $post['product'] ?? '';
  923. if (empty($productJson)) {
  924. util::fail('请选择商品');
  925. }
  926. $productList = json_decode($productJson, true);
  927. if (empty($productList) || !is_array($productList)) {
  928. util::fail('请选择商品');
  929. }
  930. $itemRows = [];
  931. $goodsRows = [];
  932. foreach ($productList as $idx => $row) {
  933. $property = intval($row['property'] ?? -1);
  934. if ($property === 1) {
  935. $itemRows[$idx] = $row;
  936. } elseif ($property === 0) {
  937. $goodsRows[$idx] = $row;
  938. } else {
  939. util::fail('商品类型错误');
  940. }
  941. }
  942. if (empty($itemRows) && empty($goodsRows)) {
  943. util::fail('请选择商品');
  944. }
  945. // ---- 花材校验与定价 ----
  946. $productInfoList = [];
  947. if (!empty($itemRows)) {
  948. $ids = array_unique(array_filter(array_map(function ($r) {
  949. return intval($r['productId'] ?? 0);
  950. }, $itemRows)));
  951. $productInfoList = ProductClass::getByIds($ids, null, 'id');
  952. if (empty($productInfoList)) {
  953. util::fail('花材不存在');
  954. }
  955. $presellData = [];
  956. $nowTime = strtotime(date("Y-m-d"));
  957. foreach ($productInfoList as $currentInfo) {
  958. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $this->mainId) {
  959. util::fail('只能选一家的商品,请清空重新选呢');
  960. }
  961. $presell = $currentInfo['presell'] ?? 0;
  962. $presellData[] = $presell;
  963. if ($presell == 1) {
  964. if (empty($post['reachDate'])) {
  965. util::fail('请选择配送或取货日期');
  966. }
  967. $sendTimeWant = $post['reachDate'];
  968. if (strtotime($sendTimeWant) < $nowTime) {
  969. util::fail('不能选择过去时间');
  970. }
  971. $hasDateStr = $currentInfo['presellDate'] ?? [];
  972. $hasDate = explode(',', trim($hasDateStr));
  973. if (empty($hasDate)) {
  974. util::fail('预售日期有问题,请提醒门店');
  975. }
  976. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  977. util::fail("有预售花材在{$sendTimeWant}没到货");
  978. }
  979. $post['presell'] = 1;
  980. }
  981. }
  982. if (count($productInfoList) != count($ids)) {
  983. util::fail('存在无效花材');
  984. }
  985. $presellData = array_unique($presellData);
  986. if (count($presellData) > 1) {
  987. util::fail('预售和非预售花材不能一起下单');
  988. }
  989. }
  990. $connection = Yii::$app->db;
  991. $transaction = $connection->beginTransaction();
  992. $transactionFinished = false;
  993. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  994. if ($transactionFinished) {
  995. return;
  996. }
  997. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  998. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  999. if ($transaction->isActive) {
  1000. $transaction->rollBack();
  1001. }
  1002. });
  1003. try {
  1004. $orderValidTime = !getenv('ORDER_VALID_TIME') ? 600 : getenv('ORDER_VALID_TIME');
  1005. $post['deadline'] = time() + $orderValidTime;
  1006. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  1007. $post['needPrint'] = dict::getDict('needPrint', 'need');
  1008. $post['fromType'] = dict::getDict('fromType', 'mall');
  1009. $post['store'] = 0;
  1010. $user = $this->user;
  1011. $post['bookMobile'] = $user->mobile ?? '';
  1012. $post['bookName'] = $user->name ?? '';
  1013. $hasPay = 0;
  1014. $modifyPrice = 0;
  1015. $totalWeight = 0;
  1016. $totalNum = 0;
  1017. $itemBigNum = 0;
  1018. $totalReachDiscount = 0;
  1019. $resolvedProduct = [];
  1020. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  1021. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  1022. foreach ($productList as $eleKey => $element) {
  1023. $property = intval($element['property'] ?? -1);
  1024. if ($property === 1) {
  1025. $level = 0;
  1026. $productId = $element['productId'];
  1027. $product = $productInfoList[$productId] ?? null;
  1028. if (empty($product)) {
  1029. util::fail('有花材信息没有找到');
  1030. }
  1031. $num = $element['num'] ?? 0;
  1032. $limitKey = \bizHd\product\classes\ProductClass::LIMIT_BUY_KEY . $productId;
  1033. $hasBuyNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $hdCustomId]);
  1034. $hasBuyNum = $num + ($hasBuyNum == null ? 0 : $hasBuyNum);
  1035. $price = \bizGhs\product\classes\ProductClass::getFinalPrice($product, $level, $priceMap, $addPriceMap, 0, $num, $hasBuyNum);
  1036. $reachNum = $product['reachNum'] ?? 0;
  1037. $reachNumDiscount = $product['reachNumDiscount'] ?? 0;
  1038. if ($reachNum > 0 && $num >= $reachNum && $reachNumDiscount > 0) {
  1039. $currentReachDiscount = bcmul($reachNumDiscount, $num, 2);
  1040. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  1041. }
  1042. $currentTotal = bcmul($price, $num, 2);
  1043. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1044. $weight = $product['weight'] ?? 0;
  1045. $currentWeight = bcmul($num, $weight, 2);
  1046. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1047. $totalNum = bcadd($totalNum, $num);
  1048. $itemBigNum = bcadd($itemBigNum, $num);
  1049. if (($product['limitBuy'] ?? 0) > 0) {
  1050. $product['productId'] = $productId;
  1051. \bizHd\product\classes\ProductClass::handleLimitBuy($product, $hdCustomId, floatval($num));
  1052. }
  1053. $resolvedProduct[] = [
  1054. 'productId' => $productId,
  1055. 'num' => $num,
  1056. 'itemId' => $element['itemId'] ?? 0,
  1057. 'unitType' => $element['unitType'] ?? 0,
  1058. 'property' => 1,
  1059. 'unitPrice' => $price,
  1060. ];
  1061. } else {
  1062. $goodsId = intval($element['goodsId'] ?? 0);
  1063. $specGoodsId = intval($element['specGoodsId'] ?? 0);
  1064. $saleGoodsId = intval($element['productId'] ?? 0);
  1065. $goodsNum = isset($element['num']) && $element['num'] > 0 ? $element['num'] : 1;
  1066. if ($goodsId <= 0 && $saleGoodsId > 0) {
  1067. $probe = GoodsClass::getById($saleGoodsId, true);
  1068. if (!empty($probe)) {
  1069. $masterId = intval($probe->masterId ?? 0);
  1070. if ($masterId > 0) {
  1071. $goodsId = $masterId;
  1072. $specGoodsId = $saleGoodsId;
  1073. } else {
  1074. $goodsId = $saleGoodsId;
  1075. }
  1076. }
  1077. }
  1078. if ($goodsId <= 0) {
  1079. util::fail('请选择花束商品');
  1080. }
  1081. $goodsInfo = GoodsClass::getById($goodsId, true);
  1082. if (empty($goodsInfo)) {
  1083. util::fail('没有找到花束商品');
  1084. }
  1085. if ($goodsInfo->mainId != $mainId) {
  1086. util::fail('不是你的商品');
  1087. }
  1088. if ($specGoodsId > 0) {
  1089. $specGoods = GoodsClass::getById($specGoodsId, true);
  1090. if (empty($specGoods) || $specGoods->mainId != $mainId || $specGoods->masterId != $goodsId || $specGoods->delStatus != 0 || $specGoods->status != 1) {
  1091. util::fail('规格不可用');
  1092. }
  1093. $goodsInfo = $specGoods;
  1094. $saleGoodsId = $specGoodsId;
  1095. } else {
  1096. if ((int)($goodsInfo->masterId ?? 0) === 0) {
  1097. $hasSpecs = GoodsClass::getByCondition(['masterId' => $goodsId, 'delStatus' => 0], true);
  1098. if (!empty($hasSpecs)) {
  1099. util::fail('请选择规格');
  1100. }
  1101. }
  1102. $saleGoodsId = $goodsId;
  1103. }
  1104. $stock = $goodsInfo->stock ?? 0;
  1105. $stockSet = $goodsInfo->stockSet ?? 0;
  1106. if ($stockSet == 1 && $stock <= 0) {
  1107. util::fail('花束库存不足');
  1108. }
  1109. // 秒杀商品:不信任前端传的价格,独立回查 Redis 秒杀配置核实活动状态/库存/限购后再核价
  1110. $seckillRow = null;
  1111. if (strval($element['activityType'] ?? '') === 'seckill') {
  1112. $seckillRow = HomePageModuleClass::getSeckillActiveRow($mainId, $saleGoodsId);
  1113. if (empty($seckillRow)) {
  1114. util::fail('秒杀活动已结束或商品已下架,请重新选择');
  1115. }
  1116. $seckillStock = floatval($seckillRow['stock'] ?? 0);
  1117. $soldCount = HomePageModuleClass::getSeckillSoldCount($mainId, $saleGoodsId);
  1118. if (bcadd($soldCount, $goodsNum, 2) > $seckillStock) {
  1119. util::fail('秒杀库存不足,请重新选择');
  1120. }
  1121. $seckillLimit = floatval($seckillRow['limit'] ?? 0);
  1122. if ($seckillLimit > 0) {
  1123. $boughtCount = HomePageModuleClass::getSeckillCustomBoughtCount($mainId, $saleGoodsId, $hdCustomId);
  1124. if (bcadd($boughtCount, $goodsNum, 2) > $seckillLimit) {
  1125. util::fail("秒杀商品每人限购{$seckillLimit}件,已超出可购买数量");
  1126. }
  1127. }
  1128. }
  1129. $goodsData = $goodsInfo->attributes;
  1130. if ($seckillRow) {
  1131. $unitPrice = floatval($seckillRow['price'] ?? 0);
  1132. if ($unitPrice <= 0) {
  1133. util::fail('秒杀价格异常,不能下单');
  1134. }
  1135. } else {
  1136. $ret = \bizHd\goods\classes\GoodsClass::getFinalPrice($goodsData, $shop, $custom, []);
  1137. $priceType = $ret['priceType'] ?? 0;
  1138. if ($priceType == 0) {
  1139. util::fail('花束没有价格,不能下单');
  1140. }
  1141. $unitPrice = $ret['price'] ?? 0;
  1142. if ($unitPrice <= 0) {
  1143. util::fail('花束没有价格,不能下单');
  1144. }
  1145. }
  1146. if ($seckillRow) {
  1147. // 通过校验后立即预占名额,失败/异常时随事务一起回滚(见 register_shutdown_function)
  1148. HomePageModuleClass::reserveSeckillPurchase($mainId, $saleGoodsId, $hdCustomId, $goodsNum);
  1149. }
  1150. $currentTotal = bcmul($unitPrice, $goodsNum, 2);
  1151. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1152. $weight = $goodsInfo->weight ?? 0;
  1153. if ($weight > 5) {
  1154. $weight = 5;
  1155. }
  1156. $currentWeight = bcmul($weight, $goodsNum, 2);
  1157. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1158. $totalNum = bcadd($totalNum, $goodsNum);
  1159. $resolvedProduct[] = [
  1160. 'productId' => $saleGoodsId,
  1161. 'unitType' => 0,
  1162. 'property' => 0,
  1163. 'unitPrice' => $unitPrice,
  1164. 'num' => $goodsNum,
  1165. ];
  1166. }
  1167. }
  1168. $post['product'] = $resolvedProduct;
  1169. $post['reachDiscountPrice'] = $totalReachDiscount;
  1170. $goodsOnlyPrice = $modifyPrice;
  1171. unset($post['sendCost'], $post['packCost'], $post['packingFee'], $post['unMeetSendCost']);
  1172. $sendType = intval($post['sendType'] ?? 0);
  1173. $customInfo = array_merge(
  1174. is_array($custom) ? $custom : ($custom ? $custom->attributes : []),
  1175. is_array($hd) ? $hd : ($hd ? $hd->attributes : [])
  1176. );
  1177. $additionalCosts = \bizHd\order\classes\PsMethodClass::calcFee(
  1178. $this->shopId,
  1179. $this->mainId,
  1180. $sendType,
  1181. $goodsOnlyPrice,
  1182. $itemBigNum,
  1183. $hdCustomId,
  1184. $customInfo
  1185. );
  1186. $unMeetSendCost = $additionalCosts['sendCost'] ?? 0;
  1187. $packingFee = $additionalCosts['packCost'] ?? 0;
  1188. $mapSet = ShopClass::hasIntraCity($this->shop);
  1189. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  1190. $hasItem = !empty($itemRows);
  1191. // 含花材(含混合)按花材报价 goodsType=1;纯花束按 0
  1192. $quoteGoodsType = $hasItem ? 1 : 0;
  1193. if (isset($post['sendType']) && $post['sendType'] == 2 && $openIntraCity != 0) {
  1194. if ($openIntraCity == 2) {
  1195. util::fail('不能使用跑腿');
  1196. }
  1197. if (empty($post['long']) || empty($post['lat'])) {
  1198. util::fail('位置错误');
  1199. }
  1200. $shopLat = $shop->lat ?? '';
  1201. $shopLong = $shop->long ?? '';
  1202. if (empty($shopLat) || empty($shopLong)) {
  1203. util::fail('商家门店地址定位未设置,编号263');
  1204. }
  1205. $distance = 0;
  1206. $sendCost = 0;
  1207. $prefix = 'PT-MIX-' . $this->mainId . '-';
  1208. $orderSn = $prefix . round(microtime(true) * 1000);
  1209. $ghsInfo = ['mainId' => $this->mainId, 'shopId' => $this->shopId];
  1210. try {
  1211. if (empty($post['deliveryPlatform'])) {
  1212. util::fail('请选择跑腿');
  1213. }
  1214. $quoteCustom = $this->user;
  1215. if ($quoteGoodsType === 0) {
  1216. $quoteCustom = (object)[
  1217. 'name' => $post['receiveUserName'] ?? '',
  1218. 'mobile' => $post['receiveMobile'] ?? '',
  1219. 'fullAddress' => $post['address'] ?? '',
  1220. 'floor' => $post['floor'] ?? '',
  1221. 'dist' => '',
  1222. 'lat' => $post['lat'],
  1223. 'long' => $post['long'],
  1224. 'address' => $post['address'] ?? '',
  1225. 'city' => $post['city'] ?? '',
  1226. ];
  1227. }
  1228. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  1229. 'productList' => $resolvedProduct,
  1230. 'deliveryPlatform' => $post['deliveryPlatform'],
  1231. 'deliveryBracketContent' => $post['deliveryBracketContent'] ?? '',
  1232. 'ghsInfo' => $ghsInfo,
  1233. 'custom' => $quoteCustom,
  1234. 'order' => [
  1235. 'orderSn' => $orderSn,
  1236. 'goodsType' => $quoteGoodsType,
  1237. 'itemTotalAmount' => $modifyPrice,
  1238. 'remark' => $post['remark'] ?? '',
  1239. ],
  1240. 'mainId' => $this->mainId,
  1241. 'productCount' => $totalNum,
  1242. ]);
  1243. $sendCost = $quoteResult['sendCost'];
  1244. $distance = $quoteResult['sendDistance'];
  1245. } catch (\Exception $e) {
  1246. util::fail($e->getMessage());
  1247. }
  1248. $post['sendCost'] = $sendCost;
  1249. $post['sendDistance'] = $distance;
  1250. $modifyPrice = bcadd($modifyPrice, $sendCost, 2);
  1251. }
  1252. if ($unMeetSendCost > 0) {
  1253. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $unMeetSendCost, 2);
  1254. $modifyPrice = bcadd($modifyPrice, $unMeetSendCost, 2);
  1255. }
  1256. if ($packingFee > 0) {
  1257. $post['packingFee'] = $packingFee;
  1258. $modifyPrice = bcadd($modifyPrice, $packingFee, 2);
  1259. }
  1260. // 红包(归属花店客户,与 buy-item 一致)
  1261. $hbId = $post['hbId'] ?? 0;
  1262. $hb = null;
  1263. if ($hbId > 0) {
  1264. $hb = HbClass::getById($hbId, true);
  1265. if (!empty($hb)) {
  1266. if ($hb->customId != $hdCustomId) {
  1267. util::fail('不是你的红包');
  1268. }
  1269. if ($hb->amount != $post['hbAmount']) {
  1270. util::fail('红包金额不相等');
  1271. }
  1272. if ($hb->status == 1) {
  1273. util::fail('红包已使用');
  1274. }
  1275. if ($hb->status == -1) {
  1276. util::fail('红包已作废');
  1277. }
  1278. if ($hb->endTime < time()) {
  1279. $hb->status = -1;
  1280. $hb->save();
  1281. util::fail('红包已失效');
  1282. }
  1283. if ($hb->beginTime > time()) {
  1284. util::fail('红包可使用期未到');
  1285. }
  1286. if (bccomp($modifyPrice, $hb->minConsume) == -1) {
  1287. util::fail("不满足最低消费金额{$hb->minConsume}元");
  1288. }
  1289. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);
  1290. } else {
  1291. util::fail('红包无效');
  1292. }
  1293. }
  1294. $psMethodError = \bizHd\order\classes\PsMethodClass::checkLimit(
  1295. $this->shopId,
  1296. $this->mainId,
  1297. $sendType,
  1298. $goodsOnlyPrice,
  1299. $itemBigNum,
  1300. $packingFee,
  1301. $unMeetSendCost,
  1302. $hdCustomId,
  1303. $customInfo
  1304. );
  1305. if ($psMethodError !== '') {
  1306. util::fail($psMethodError);
  1307. }
  1308. $sendType = $post['sendType'] ?? 0;
  1309. if ($sendType != 1) {
  1310. if (empty($post['reachPeriod'])) {
  1311. util::fail('请选择配送时间哈');
  1312. }
  1313. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  1314. }
  1315. $post['bigNum'] = $totalNum;
  1316. $post['modifyPrice'] = $modifyPrice;
  1317. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  1318. $orderSn = $return->orderSn ?? '';
  1319. if (!empty($orderSn) && (float)$unMeetSendCost > 0) {
  1320. $unMeetSendKey = 'hd_ps_order_unmeet_send_' . $orderSn;
  1321. Yii::$app->redis->executeCommand('SETEX', [$unMeetSendKey, 864000, (string)$unMeetSendCost]);
  1322. }
  1323. if (!empty($hb)) {
  1324. $hb->status = 1;
  1325. $hb->orderId = $return->id;
  1326. $hb->save();
  1327. }
  1328. if ($return->sendType == 2) {
  1329. $ext = ShopExtClass::getByCondition(['shopId' => $return->shopId], true, null, 'id,shopId,thirdSend');
  1330. if (!empty($ext) && $ext->thirdSend == 1) {
  1331. util::fail('本店暂不能使用跑腿呢');
  1332. }
  1333. }
  1334. $transaction->commit();
  1335. $transactionFinished = true;
  1336. \bizHd\product\classes\ProductClass::clearLimitBuyRollbackSnapshot();
  1337. HomePageModuleClass::clearSeckillReservationSnapshot();
  1338. $orderSn = $return->orderSn ?? '';
  1339. $orderPrice = $return->orderPrice ?? ($return->actPrice ?? 0);
  1340. $id = $return->id ?? 0;
  1341. $getPayType = dict::getDict('getPayType');
  1342. util::success([
  1343. 'orderSn' => $orderSn,
  1344. 'totalPrice' => $orderPrice,
  1345. 'couponId' => 0,
  1346. 'id' => $id,
  1347. 'getPayType' => $getPayType,
  1348. ]);
  1349. } catch (\Exception $e) {
  1350. $transaction->rollBack();
  1351. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  1352. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  1353. $transactionFinished = true;
  1354. Yii::error("合并下单失败:" . $e->getMessage());
  1355. util::fail('下单失败');
  1356. }
  1357. }
  1358. //下单要用到的相关信息 ssh 2019.12.6
  1359. public function actionOrderRelate()
  1360. {
  1361. $regionTree = RegionService::tree();
  1362. //门店名称
  1363. $shop = !empty($this->shop) ? $this->shop->attributes : [];
  1364. $sjName = $shop['merchantName'] ?? '';
  1365. $shopName = $shop['shopName'] ?? '';
  1366. $shop['showName'] = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  1367. $avatar = $shop['avatar'] ?? '';
  1368. $smallAvatar = imgUtil::groupImg($avatar) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  1369. $shop['smallAvatar'] = $smallAvatar;
  1370. $freight = ['first' => 5, 'add' => 2];
  1371. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  1372. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  1373. util::success($out);
  1374. }
  1375. //余额支付 ssh 20250410
  1376. public function actionBalancePay()
  1377. {
  1378. $post = Yii::$app->request->post();
  1379. $orderSn = $post['orderSn'] ?? '';
  1380. //避免重复提交
  1381. util::checkRepeatCommit($orderSn, 5);
  1382. $connection = Yii::$app->db;
  1383. $transaction = $connection->beginTransaction();
  1384. try {
  1385. $order = OrderClass::getByCondition(['orderSn' => $orderSn], true);
  1386. if (empty($order)) {
  1387. util::fail('没有找到订单');
  1388. }
  1389. if ($order->shopId != $this->shopId) {
  1390. util::fail('不是你的订单');
  1391. }
  1392. //支付前验证订单有效性
  1393. OrderService::checkBeforePay($order);
  1394. $payWay = dict::getDict('payWay', 'balancePay');
  1395. \bizHd\order\classes\OrderClass::payAfter($order, $payWay);
  1396. $transaction->commit();
  1397. //解决重复通知,重要
  1398. $cacheKey = 'mall_order_balance_pay_' . $orderSn;
  1399. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1400. if (empty($has)) {
  1401. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  1402. //打印小票和语音播报
  1403. $order = \bizHd\order\classes\OrderClass::getByCondition(['orderSn' => $orderSn], true);
  1404. if (!empty($order)) {
  1405. \bizHd\order\classes\OrderClass::onlinePrint($order);
  1406. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  1407. HdDeliveryOrderClass::payAfter($order);
  1408. $shopId = $order->shopId ?? 0;
  1409. $shop = ShopClass::getById($shopId, true);
  1410. if (in_array($order->fromType, [1, 3])) {
  1411. //您有新的收入提醒
  1412. WxMessageClass::gatheringIncomeInform($shop, $order);
  1413. }
  1414. if ($order->fromType == 2) {
  1415. //来自商城的新订单微信通知
  1416. WxMessageClass::hdNewOrderInform($shop, $order);
  1417. \bizHd\order\classes\PsMethodClass::markUnMeetFeePaidFromOrder($order);
  1418. }
  1419. }
  1420. }
  1421. util::complete('支付成功');
  1422. } catch (\Exception $e) {
  1423. $transaction->rollBack();
  1424. Yii::error("支付原因:" . $e->getMessage());
  1425. util::fail('支付失败');
  1426. }
  1427. }
  1428. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  1429. public function actionWxPay()
  1430. {
  1431. ini_set('date.timezone', 'Asia/Shanghai');
  1432. $post = Yii::$app->request->post();
  1433. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1434. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1435. $order = OrderService::getByOrderSn($orderSn);
  1436. $orderId = $order['id'];
  1437. //验证优惠券是否还有效
  1438. if (!empty($couponId)) {
  1439. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  1440. }
  1441. //支付前验证订单有效性
  1442. OrderService::checkBeforePay($order);
  1443. $name = !empty($order['orderName']) ? $order['orderName'] : '购买花材';
  1444. $shop = $this->shop;
  1445. if (empty($shop)) {
  1446. util::fail('没有找到门店信息');
  1447. }
  1448. if (isset($shop->shopName) && !empty($shop->shopName)) {
  1449. $name .= '(' . $shop->shopName . ')';
  1450. }
  1451. $totalFee = $order['mainPay'];
  1452. $openId = '';
  1453. if (!empty($post['miniOpenId'])) {
  1454. $openId = $post['miniOpenId'];
  1455. //noticeUtil::push('散客买花时,通过前端获取了openId:' . $openId, '15280215347');
  1456. }
  1457. if (empty($openId)) {
  1458. if (isset($this->user['miniOpenId']) && !empty($this->user['miniOpenId'])) {
  1459. $openId = $this->user['miniOpenId'];
  1460. //noticeUtil::push('散客买花时,通过数据库获取了openId:' . $openId, '15280215347');
  1461. }
  1462. }
  1463. if (empty($openId)) {
  1464. util::fail('没有找到openId');
  1465. }
  1466. $now = time();
  1467. $expireTime = $now + 1800;
  1468. $updateData = [];
  1469. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1470. $oldOrderSn = $orderSn;
  1471. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1472. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1473. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1474. $params = [
  1475. 'appid' => 'OP00002119',
  1476. 'serial_no' => '018b08cfddbd',
  1477. 'merchant_no' => $shop->lklSjNo,
  1478. 'term_no' => $shop->lklScanTermNo,
  1479. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1480. 'lklCertificatePath' => $lklCertificatePath,
  1481. ];
  1482. $laResource = new Lakala($params);
  1483. $closeParams = [
  1484. 'orderSn' => $oldOrderSn,
  1485. ];
  1486. $response = $laResource->close($closeParams);
  1487. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1488. $msg = $response['msg'] ?? '';
  1489. $lklSjNo = $shop->lklSjNo ?? '';
  1490. noticeUtil::push('重点注意,散客买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . '。商户号:' . $lklSjNo, '15280215347');
  1491. util::fail('出错了哦,请重新下一单');
  1492. }
  1493. $orderSn = orderSn::getOrderSn();
  1494. $updateData['orderSn'] = $orderSn;
  1495. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  1496. } else {
  1497. //已请求的不能再修改价格
  1498. $updateData['modPrice'] = 0;
  1499. }
  1500. if (empty($order['deadline'])) {
  1501. $updateData['deadline'] = $expireTime;
  1502. }
  1503. if (!empty($updateData)) {
  1504. OrderService::updateById($orderId, $updateData);
  1505. }
  1506. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1507. $sjExtend = WxOpenClass::getMallWxInfo();
  1508. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1509. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1510. $params = [
  1511. 'appid' => 'OP00002119',
  1512. 'serial_no' => '018b08cfddbd',
  1513. 'merchant_no' => $shop->lklSjNo,
  1514. 'term_no' => $shop->lklScanTermNo,
  1515. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1516. 'lklCertificatePath' => $lklCertificatePath,
  1517. ];
  1518. $laResource = new Lakala($params);
  1519. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1520. $wxParams = [
  1521. 'orderSn' => $orderSn,
  1522. 'amount' => $totalFee,
  1523. 'capitalType' => $capitalType,
  1524. 'notifyUrl' => $notifyUrl,
  1525. 'wxAppId' => $sjExtend['miniAppId'],
  1526. 'openId' => $openId,
  1527. 'subject' => $name,
  1528. 'couponId' => $couponId,
  1529. ];
  1530. $response = $laResource->driveWxPay($wxParams);
  1531. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1532. $errMsg = $response['msg'] ?? '';
  1533. noticeUtil::push($errMsg, '15280215347');
  1534. util::fail('支付失败');
  1535. }
  1536. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1537. $appId = $newParams['app_id'] ?? '';
  1538. $nonceStr = $newParams['nonce_str'] ?? '';
  1539. $paySign = $newParams['pay_sign'] ?? '';
  1540. $package = $newParams['package'] ?? '';
  1541. $signType = $newParams['sign_type'] ?? '';
  1542. $timeStamp = $newParams['time_stamp'] ?? '';
  1543. $new = [
  1544. 'id' => $orderId,
  1545. 'appId' => $appId,
  1546. 'nonceStr' => $nonceStr,
  1547. 'paySign' => $paySign,
  1548. 'package' => $package,
  1549. 'signType' => $signType,
  1550. 'timeStamp' => $timeStamp,
  1551. 'orderSn' => $orderSn,
  1552. ];
  1553. util::success($new);
  1554. }
  1555. //快捷付款订单
  1556. public function actionFastPay()
  1557. {
  1558. ini_set('date.timezone', 'Asia/Shanghai');
  1559. $post = Yii::$app->request->post();
  1560. $payWay = $post['payWay'] ?? 0;
  1561. $shopId = $this->shopId;
  1562. $shop = $this->shop;
  1563. if (empty($shop)) {
  1564. util::fail('没有门店信息');
  1565. }
  1566. $customId = $this->customId;
  1567. $custom = $this->custom;
  1568. $hdId = $this->hdId;
  1569. $hd = $this->hd;
  1570. if (empty($customId) || empty($hdId)) {
  1571. //考虑没有登录时的付款
  1572. $defaultCustomId = $shop->defaultCustomId ?? 0;
  1573. if (empty($defaultCustomId)) {
  1574. util::fail('请设置快捷开单的客户');
  1575. }
  1576. $customId = $defaultCustomId;
  1577. $custom = CustomClass::getById($defaultCustomId, true);
  1578. if (empty($custom)) {
  1579. util::fail('无效的快捷客户');
  1580. }
  1581. $hdId = $custom->hdId;
  1582. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1583. if (empty($hd)) {
  1584. util::fail('没有花店信息呢!');
  1585. }
  1586. }
  1587. $post['hdId'] = $hdId;
  1588. $post['hdName'] = $hd->name ?? '';
  1589. $customName = $custom->name ?? '';
  1590. $customPy = $custom->py ?? '';
  1591. $post['customName'] = $customName;
  1592. $post['customNamePy'] = $customPy;
  1593. $post['shopId'] = $shopId;
  1594. $post['mainId'] = $this->mainId;
  1595. $post['customId'] = $customId;
  1596. $prePrice = round($post['prePrice'], 2);
  1597. $actPrice = $prePrice;
  1598. if ($actPrice <= 0) {
  1599. util::fail('请填写付款金额');
  1600. }
  1601. $post['actPrice'] = $actPrice;
  1602. $post['userId'] = $this->userId;
  1603. $now = time();
  1604. $expireTime = $now + 300;//订单5分钟后过期
  1605. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1606. $post['deadline'] = date("Y-m-d H:i:s", $expireTime);
  1607. $order = ScanPayClass::addOrder($post);
  1608. $orderId = $order->id ?? 0;
  1609. $orderSn = $order->orderSn ?? '';
  1610. $capitalType = dict::getDict('capitalType', 'scanPay', 'id');
  1611. if ($payWay == 0) {
  1612. //微信
  1613. $name = '购买鲜花,扫码付款';
  1614. $totalFee = $actPrice;
  1615. $user = UserService::getById($this->userId);
  1616. //小程序使用miniOpenId
  1617. $openId = $user['miniOpenId'];
  1618. if (empty($openId)) {
  1619. $openId = !empty($post['miniOpenId']) ? $post['miniOpenId'] : '';
  1620. }
  1621. if (empty($openId)) {
  1622. util::fail('没有微信信息');
  1623. }
  1624. $sjExtend = WxOpenClass::getMallWxInfo();
  1625. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1626. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1627. $params = [
  1628. 'appid' => 'OP00002119',
  1629. 'serial_no' => '018b08cfddbd',
  1630. 'merchant_no' => $shop->lklSjNo,
  1631. 'term_no' => $shop->lklScanTermNo,
  1632. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1633. 'lklCertificatePath' => $lklCertificatePath,
  1634. ];
  1635. $laResource = new Lakala($params);
  1636. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1637. $wxParams = [
  1638. 'orderSn' => $orderSn,
  1639. 'amount' => $totalFee,
  1640. 'capitalType' => $capitalType,
  1641. 'notifyUrl' => $notifyUrl,
  1642. 'wxAppId' => $sjExtend['miniAppId'],
  1643. 'openId' => $openId,
  1644. 'subject' => $name,
  1645. 'couponId' => 0,
  1646. ];
  1647. $response = $laResource->driveWxPay($wxParams);
  1648. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1649. $errMsg = $response['msg'] ?? '';
  1650. noticeUtil::push($errMsg, '15280215347');
  1651. util::fail('支付失败');
  1652. }
  1653. $newParams = $response['resp_data']['acc_resp_fields'] ?? [];
  1654. $appId = $newParams['app_id'] ?? '';
  1655. $nonceStr = $newParams['nonce_str'] ?? '';
  1656. $paySign = $newParams['pay_sign'] ?? '';
  1657. $package = $newParams['package'] ?? '';
  1658. $signType = $newParams['sign_type'] ?? '';
  1659. $timeStamp = $newParams['time_stamp'] ?? '';
  1660. $new = [
  1661. 'id' => $orderId,
  1662. 'appId' => $appId,
  1663. 'nonceStr' => $nonceStr,
  1664. 'paySign' => $paySign,
  1665. 'package' => $package,
  1666. 'signType' => $signType,
  1667. 'timeStamp' => $timeStamp,
  1668. 'orderSn' => $orderSn,
  1669. ];
  1670. util::success($new);
  1671. } elseif ($payWay == 1) {
  1672. //支付宝
  1673. $totalFee = $actPrice;
  1674. $subject = '购买鲜花,扫码付款';
  1675. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1676. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1677. $params = [
  1678. 'appid' => 'OP00002119',
  1679. 'serial_no' => '018b08cfddbd',
  1680. 'merchant_no' => $shop->lklSjNo,
  1681. 'term_no' => $shop->lklB2BTermNo,
  1682. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1683. 'lklCertificatePath' => $lklCertificatePath,
  1684. ];
  1685. $laResource = new Lakala($params);
  1686. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/cash-pay-callback";
  1687. $cashParams = [
  1688. 'orderSn' => $orderSn,
  1689. 'amount' => $totalFee,
  1690. 'capitalType' => $capitalType,
  1691. 'notifyUrl' => $notifyUrl,
  1692. 'subject' => $subject,
  1693. ];
  1694. $response = $laResource->cashierPay($cashParams);
  1695. if (!isset($response['code']) || $response['code'] != '000000') {
  1696. util::fail('支付失败了');
  1697. }
  1698. $url = $response['resp_data']['counter_url'] ?? '';
  1699. if (empty($url)) {
  1700. util::fail('支付失败');
  1701. }
  1702. util::success(['url' => $url]);
  1703. } elseif ($payWay == 2) {
  1704. //余额支付
  1705. util::fail('暂不支持');
  1706. } else {
  1707. util::fail('无效的支付方式');
  1708. }
  1709. }
  1710. //订单列表 ssh 2019.12.12
  1711. public function actionList()
  1712. {
  1713. $get = Yii::$app->request->get();
  1714. $status = $get['status'] ?? 0;
  1715. $hdId = $get['hdId'] ?? ($get['id'] ?? 0);
  1716. $userId = $this->userId;
  1717. $where = ['userId' => $userId];
  1718. if (!empty($status)) {
  1719. $where['status'] = $status;
  1720. }
  1721. if (!empty($hdId)) {
  1722. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1723. if (empty($hd)) {
  1724. util::fail('无效的花店');
  1725. }
  1726. if ($hd['userId'] != $userId) {
  1727. util::fail('不是你的花店');
  1728. }
  1729. $where['hdId'] = $hdId;
  1730. }
  1731. $list = OrderService::getOrderList($where);
  1732. util::success($list);
  1733. }
  1734. //订单评价
  1735. public function actionComment()
  1736. {
  1737. $post = Yii::$app->request->post();
  1738. $id = $post['id'];
  1739. $order = OrderClass::getById($id);
  1740. if ($order['grade'] > 0) {
  1741. util::fail('您已经评过了');
  1742. }
  1743. OrderService::comment($post);
  1744. util::complete('提交成功');
  1745. }
  1746. //订单详情 ssh 2019.12.16
  1747. public function actionDetail()
  1748. {
  1749. $id = Yii::$app->request->get('id', 0);
  1750. $detail = OrderClass::getOrderById($id);
  1751. $userId = $this->userId;
  1752. if ($detail['userId'] != $userId) {
  1753. util::fail('不是你的单,不能查看');
  1754. }
  1755. $shOrderMap = [];
  1756. if ($detail['hasForward'] == 1) {
  1757. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1758. }
  1759. $detail['shOrderMap'] = $shOrderMap;
  1760. //是否显示余额支付按钮 ssh 20260120
  1761. $hd = $this->hd;
  1762. $balance = $hd->balance ?? 0;
  1763. $showYePay = $balance > 0 ? 1 : 0;
  1764. $detail['showYePay'] = $showYePay;
  1765. $detail['balance'] = $balance;
  1766. $detail['rechargeWeal'] = $this->shop->rechargeWeal; //是否开启余额支付
  1767. util::success($detail);
  1768. }
  1769. //获取详情 ssh 20220512
  1770. public function actionInfo()
  1771. {
  1772. $sn = Yii::$app->request->get('orderSn', '');
  1773. $detail = OrderClass::getOrderBySn($sn);
  1774. util::success($detail);
  1775. }
  1776. }