OrderController.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  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. $mainId = $this->mainId;
  893. $shop = $this->shop;
  894. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  895. if ($openShop == 0) {
  896. util::fail('已休店');
  897. }
  898. $hdId = $post['hdId'] ?? 0;
  899. $hd = HdClass::getById($hdId, true);
  900. if (empty($hd)) {
  901. util::fail('没有找到花店');
  902. }
  903. if ($hd->shopId != $this->shopId) {
  904. util::fail('不是你的花店');
  905. }
  906. $post['hdName'] = $hd->name ?? '';
  907. // 合并结算沿用花材购物车的客户身份(花店客户)
  908. $hdCustomId = $hd->customId ?? 0;
  909. $custom = CustomClass::getById($hdCustomId, true);
  910. if (empty($custom)) {
  911. util::fail('没有找到客户');
  912. }
  913. $customName = $custom->name;
  914. $post['customId'] = $hdCustomId;
  915. $post['customName'] = $customName;
  916. $post['customNamePy'] = stringUtil::py($customName);
  917. $productJson = $post['product'];
  918. if (empty($productJson)) {
  919. util::fail('请选择商品');
  920. }
  921. $productList = json_decode($productJson, true);
  922. if (empty($productList) || !is_array($productList)) {
  923. util::fail('请选择商品');
  924. }
  925. $itemRows = [];
  926. $goodsRows = [];
  927. foreach ($productList as $idx => $row) {
  928. $property = intval($row['property'] ?? -1);
  929. if ($property === 1) {
  930. $itemRows[$idx] = $row;
  931. } elseif ($property === 0) {
  932. $goodsRows[$idx] = $row;
  933. } else {
  934. util::fail('商品类型错误');
  935. }
  936. }
  937. if (empty($itemRows) && empty($goodsRows)) {
  938. util::fail('请选择商品');
  939. }
  940. // ---- 花材校验与定价 ----
  941. $productInfoList = [];
  942. if (!empty($itemRows)) {
  943. $ids = array_unique(array_filter(array_map(function ($r) {
  944. return intval($r['productId'] ?? 0);
  945. }, $itemRows)));
  946. $productInfoList = ProductClass::getByIds($ids, null, 'id');
  947. if (empty($productInfoList)) {
  948. util::fail('花材不存在');
  949. }
  950. $presellData = [];
  951. $nowTime = strtotime(date("Y-m-d"));
  952. foreach ($productInfoList as $currentInfo) {
  953. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $this->mainId) {
  954. util::fail('只能选一家的商品,请清空重新选呢');
  955. }
  956. $presell = $currentInfo['presell'] ?? 0;
  957. $presellData[] = $presell;
  958. if ($presell == 1) {
  959. if (empty($post['reachDate'])) {
  960. util::fail('请选择配送或取货日期');
  961. }
  962. $sendTimeWant = $post['reachDate'];
  963. if (strtotime($sendTimeWant) < $nowTime) {
  964. util::fail('不能选择过去时间');
  965. }
  966. $hasDateStr = $currentInfo['presellDate'] ?? [];
  967. $hasDate = explode(',', trim($hasDateStr));
  968. if (empty($hasDate)) {
  969. util::fail('预售日期有问题,请提醒门店');
  970. }
  971. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  972. util::fail("有预售花材在{$sendTimeWant}没到货");
  973. }
  974. $post['presell'] = 1;
  975. }
  976. }
  977. if (count($productInfoList) != count($ids)) {
  978. util::fail('存在无效花材');
  979. }
  980. $presellData = array_unique($presellData);
  981. if (count($presellData) > 1) {
  982. util::fail('预售和非预售花材不能一起下单');
  983. }
  984. }
  985. $connection = Yii::$app->db;
  986. $transaction = $connection->beginTransaction();
  987. $transactionFinished = false;
  988. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  989. if ($transactionFinished) {
  990. return;
  991. }
  992. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  993. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  994. if ($transaction->isActive) {
  995. $transaction->rollBack();
  996. }
  997. });
  998. try {
  999. $orderValidTime = !getenv('ORDER_VALID_TIME') ? 600 : getenv('ORDER_VALID_TIME'); // TODO 找少华确认
  1000. $post['deadline'] = time() + $orderValidTime;
  1001. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  1002. $post['needPrint'] = dict::getDict('needPrint', 'need');
  1003. $post['fromType'] = dict::getDict('fromType', 'mall');
  1004. $post['store'] = 0;
  1005. $user = $this->user;
  1006. $post['bookMobile'] = $user->mobile ?? '';
  1007. $post['bookName'] = $user->name ?? '';
  1008. $hasPay = 0;
  1009. $modifyPrice = 0;
  1010. $totalWeight = 0;
  1011. $totalNum = 0;
  1012. $itemBigNum = 0;
  1013. $totalReachDiscount = 0;
  1014. $resolvedProduct = [];
  1015. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  1016. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  1017. $post['orderType'] = 0;
  1018. foreach ($productList as $eleKey => $element) {
  1019. $property = $element['property']; // 1: 花材, 0: 花束
  1020. if ($property === 1) {
  1021. $level = 0;
  1022. $productId = $element['productId'];
  1023. $product = $productInfoList[$productId] ?? null;
  1024. if (empty($product)) {
  1025. util::fail('有花材信息没有找到');
  1026. }
  1027. $num = $element['num'] ?? 0;
  1028. $limitKey = \bizHd\product\classes\ProductClass::LIMIT_BUY_KEY . $productId;
  1029. $hasBuyNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $hdCustomId]);
  1030. $hasBuyNum = $num + ($hasBuyNum == null ? 0 : $hasBuyNum);
  1031. $price = \bizGhs\product\classes\ProductClass::getFinalPrice($product, $level, $priceMap, $addPriceMap, 0, $num, $hasBuyNum);
  1032. $reachNum = $product['reachNum'] ?? 0;
  1033. $reachNumDiscount = $product['reachNumDiscount'] ?? 0;
  1034. if ($reachNum > 0 && $num >= $reachNum && $reachNumDiscount > 0) {
  1035. $currentReachDiscount = bcmul($reachNumDiscount, $num, 2);
  1036. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  1037. }
  1038. $currentTotal = bcmul($price, $num, 2);
  1039. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1040. $weight = $product['weight'] ?? 0;
  1041. $currentWeight = bcmul($num, $weight, 2);
  1042. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1043. $totalNum = bcadd($totalNum, $num);
  1044. $itemBigNum = bcadd($itemBigNum, $num);
  1045. if (($product['limitBuy'] ?? 0) > 0) {
  1046. $product['productId'] = $productId;
  1047. \bizHd\product\classes\ProductClass::handleLimitBuy($product, $hdCustomId, floatval($num));
  1048. }
  1049. $resolvedProduct[] = [
  1050. 'productId' => $productId,
  1051. 'num' => $num,
  1052. 'itemId' => $element['itemId'] ?? 0,
  1053. 'unitType' => $element['unitType'] ?? 0,
  1054. 'property' => 1,
  1055. 'unitPrice' => $price,
  1056. ];
  1057. } else {
  1058. $goodsId = $element['goodsId'];
  1059. $specGoodsId = $element['specGoodsId'];
  1060. $saleGoodsId = $element['productId'];
  1061. $goodsNum = isset($element['num']) && $element['num'] > 0 ? $element['num'] : 1;
  1062. if ($goodsId <= 0 && $saleGoodsId > 0) {
  1063. $probe = GoodsClass::getById($saleGoodsId, true);
  1064. if (!empty($probe)) {
  1065. $masterId = intval($probe->masterId);
  1066. if ($masterId > 0) {
  1067. $goodsId = $masterId;
  1068. $specGoodsId = $saleGoodsId;
  1069. } else {
  1070. $goodsId = $saleGoodsId;
  1071. }
  1072. }
  1073. }
  1074. if ($goodsId <= 0) {
  1075. util::fail('请选择花束商品');
  1076. }
  1077. $goodsInfo = GoodsClass::getById($goodsId, true);
  1078. if (empty($goodsInfo)) {
  1079. util::fail('没有找到花束商品');
  1080. }
  1081. if ($goodsInfo->mainId != $mainId) {
  1082. util::fail('不是你的商品');
  1083. }
  1084. if ($specGoodsId > 0) {
  1085. $specGoods = GoodsClass::getById($specGoodsId, true);
  1086. if (empty($specGoods) || $specGoods->mainId != $mainId || $specGoods->masterId != $goodsId || $specGoods->delStatus != 0 || $specGoods->status != 1) {
  1087. util::fail('规格不可用');
  1088. }
  1089. $goodsInfo = $specGoods;
  1090. $saleGoodsId = $specGoodsId;
  1091. } else {
  1092. if ((int)($goodsInfo->masterId ?? 0) === 0) {
  1093. $hasSpecs = GoodsClass::getByCondition(['masterId' => $goodsId, 'delStatus' => 0], true);
  1094. if (!empty($hasSpecs)) {
  1095. util::fail('请选择规格');
  1096. }
  1097. }
  1098. $saleGoodsId = $goodsId;
  1099. }
  1100. $stock = $goodsInfo->stock;
  1101. $stockSet = $goodsInfo->stockSet;
  1102. if ($stockSet == 1 && $stock <= 0) {
  1103. util::fail('花束库存不足');
  1104. }
  1105. // 秒杀商品:不信任前端传的价格,独立回查 Redis 秒杀配置核实活动状态/库存/限购后再核价
  1106. $seckillRow = null;
  1107. if (strval($element['activityType'] ?? '') === 'seckill') {
  1108. $seckillRow = HomePageModuleClass::getSeckillActiveRow($mainId, $saleGoodsId);
  1109. if (empty($seckillRow)) {
  1110. util::fail('秒杀活动已结束或商品已下架,请重新选择');
  1111. }
  1112. $seckillStock = floatval($seckillRow['stock']);
  1113. $soldCount = HomePageModuleClass::getSeckillSoldCount($mainId, $saleGoodsId);
  1114. if (bcadd($soldCount, $goodsNum, 2) > $seckillStock) {
  1115. util::fail('秒杀库存不足,请重新选择');
  1116. }
  1117. $seckillLimit = floatval($seckillRow['limit'] ?? 0);
  1118. if ($seckillLimit > 0) {
  1119. $boughtCount = HomePageModuleClass::getSeckillCustomBoughtCount($mainId, $saleGoodsId, $hdCustomId); // TODO 同一个商品,如果缓存没有合理清除,就会一直限购
  1120. if (bcadd($boughtCount, $goodsNum, 2) > $seckillLimit) {
  1121. util::fail("秒杀商品每人限购{$seckillLimit}件,已超出可购买数量");
  1122. }
  1123. }
  1124. }
  1125. $goodsData = $goodsInfo->attributes;
  1126. if ($seckillRow) {
  1127. $unitPrice = floatval($seckillRow['price'] ?? 0);
  1128. if ($unitPrice <= 0) {
  1129. util::fail('秒杀价格异常,不能下单');
  1130. }
  1131. } else {
  1132. $ret = \bizHd\goods\classes\GoodsClass::getFinalPrice($goodsData, $shop, $custom, []);
  1133. $priceType = $ret['priceType'] ?? 0;
  1134. if ($priceType == 0) {
  1135. util::fail('花束没有价格,不能下单');
  1136. }
  1137. $unitPrice = $ret['price'] ?? 0;
  1138. if ($unitPrice <= 0) {
  1139. util::fail('花束没有价格,不能下单');
  1140. }
  1141. }
  1142. if ($seckillRow) {
  1143. // 通过校验后立即预占名额,失败/异常时随事务一起回滚(见 register_shutdown_function)
  1144. HomePageModuleClass::reserveSeckillPurchase($mainId, $saleGoodsId, $hdCustomId, $goodsNum);
  1145. }
  1146. $currentTotal = bcmul($unitPrice, $goodsNum, 2);
  1147. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1148. $weight = $goodsInfo->weight ?? 0;
  1149. if ($weight > 5) {
  1150. $weight = 5;
  1151. }
  1152. $currentWeight = bcmul($weight, $goodsNum, 2);
  1153. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1154. $totalNum = bcadd($totalNum, $goodsNum);
  1155. $resolvedProduct[] = [
  1156. 'productId' => $saleGoodsId,
  1157. 'unitType' => 0,
  1158. 'property' => 0,
  1159. 'unitPrice' => $unitPrice,
  1160. 'num' => $goodsNum,
  1161. ];
  1162. }
  1163. }
  1164. // 根据 $resolvedProduct 设置订单类型:1纯花束 2纯花材 3混合
  1165. $properties = array_unique(array_column($resolvedProduct, 'property'));
  1166. if (count($properties) === 1) {
  1167. $post['orderType'] = intval($properties[0]) === 0 ? 1 : 2;
  1168. } elseif (count($properties) > 1) {
  1169. $post['orderType'] = 3;
  1170. }
  1171. $post['product'] = $resolvedProduct;
  1172. $post['reachDiscountPrice'] = $totalReachDiscount;
  1173. $goodsOnlyPrice = $modifyPrice;
  1174. unset($post['sendCost'], $post['packCost'], $post['packingFee'], $post['unMeetSendCost']);
  1175. $sendType = intval($post['sendType'] ?? 0);
  1176. $customInfo = array_merge(
  1177. is_array($custom) ? $custom : ($custom ? $custom->attributes : []),
  1178. is_array($hd) ? $hd : ($hd ? $hd->attributes : [])
  1179. );
  1180. $additionalCosts = \bizHd\order\classes\PsMethodClass::calcFee(
  1181. $this->shopId,
  1182. $this->mainId,
  1183. $sendType,
  1184. $goodsOnlyPrice,
  1185. $itemBigNum,
  1186. $hdCustomId,
  1187. $customInfo
  1188. );
  1189. $unMeetSendCost = $additionalCosts['sendCost'] ?? 0;
  1190. $packingFee = $additionalCosts['packCost'] ?? 0;
  1191. $mapSet = ShopClass::hasIntraCity($this->shop);
  1192. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  1193. $hasItem = !empty($itemRows);
  1194. // 含花材(含混合)按花材报价 goodsType=1;纯花束按 0
  1195. $quoteGoodsType = $hasItem ? 1 : 0;
  1196. if (isset($post['sendType']) && $post['sendType'] == 2 && $openIntraCity != 0) {
  1197. if ($openIntraCity == 2) {
  1198. util::fail('不能使用跑腿');
  1199. }
  1200. if (empty($post['long']) || empty($post['lat'])) {
  1201. util::fail('位置错误');
  1202. }
  1203. $shopLat = $shop->lat ?? '';
  1204. $shopLong = $shop->long ?? '';
  1205. if (empty($shopLat) || empty($shopLong)) {
  1206. util::fail('商家门店地址定位未设置,编号263');
  1207. }
  1208. $distance = 0;
  1209. $sendCost = 0;
  1210. $prefix = 'PT-MIX-' . $this->mainId . '-';
  1211. $orderSn = $prefix . round(microtime(true) * 1000);
  1212. $ghsInfo = ['mainId' => $this->mainId, 'shopId' => $this->shopId];
  1213. try {
  1214. if (empty($post['deliveryPlatform'])) {
  1215. util::fail('请选择跑腿');
  1216. }
  1217. $quoteCustom = $this->user;
  1218. if ($quoteGoodsType === 0) {
  1219. $quoteCustom = (object)[
  1220. 'name' => $post['receiveUserName'] ?? '',
  1221. 'mobile' => $post['receiveMobile'] ?? '',
  1222. 'fullAddress' => $post['address'] ?? '',
  1223. 'floor' => $post['floor'] ?? '',
  1224. 'dist' => '',
  1225. 'lat' => $post['lat'],
  1226. 'long' => $post['long'],
  1227. 'address' => $post['address'] ?? '',
  1228. 'city' => $post['city'] ?? '',
  1229. ];
  1230. }
  1231. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  1232. 'productList' => $resolvedProduct,
  1233. 'deliveryPlatform' => $post['deliveryPlatform'],
  1234. 'deliveryBracketContent' => $post['deliveryBracketContent'] ?? '',
  1235. 'ghsInfo' => $ghsInfo,
  1236. 'custom' => $quoteCustom,
  1237. 'order' => [
  1238. 'orderSn' => $orderSn,
  1239. 'goodsType' => $quoteGoodsType,
  1240. 'itemTotalAmount' => $modifyPrice,
  1241. 'remark' => $post['remark'] ?? '',
  1242. ],
  1243. 'mainId' => $this->mainId,
  1244. 'productCount' => $totalNum,
  1245. ]);
  1246. $sendCost = $quoteResult['sendCost'];
  1247. $distance = $quoteResult['sendDistance'];
  1248. } catch (\Exception $e) {
  1249. util::fail($e->getMessage());
  1250. }
  1251. $post['sendCost'] = $sendCost;
  1252. $post['sendDistance'] = $distance;
  1253. $modifyPrice = bcadd($modifyPrice, $sendCost, 2);
  1254. }
  1255. if ($unMeetSendCost > 0) {
  1256. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $unMeetSendCost, 2);
  1257. $modifyPrice = bcadd($modifyPrice, $unMeetSendCost, 2);
  1258. }
  1259. if ($packingFee > 0) {
  1260. $post['packingFee'] = $packingFee;
  1261. $modifyPrice = bcadd($modifyPrice, $packingFee, 2);
  1262. }
  1263. // 红包(归属花店客户,与 buy-item 一致)
  1264. $hbId = $post['hbId'] ?? 0;
  1265. $hb = null;
  1266. if ($hbId > 0) {
  1267. $hb = HbClass::getById($hbId, true);
  1268. if (!empty($hb)) {
  1269. if ($hb->customId != $hdCustomId) {
  1270. util::fail('不是你的红包');
  1271. }
  1272. if ($hb->amount != $post['hbAmount']) {
  1273. util::fail('红包金额不相等');
  1274. }
  1275. if ($hb->status == 1) {
  1276. util::fail('红包已使用');
  1277. }
  1278. if ($hb->status == -1) {
  1279. util::fail('红包已作废');
  1280. }
  1281. if ($hb->endTime < time()) {
  1282. $hb->status = -1;
  1283. $hb->save();
  1284. util::fail('红包已失效');
  1285. }
  1286. if ($hb->beginTime > time()) {
  1287. util::fail('红包可使用期未到');
  1288. }
  1289. if (bccomp($modifyPrice, $hb->minConsume) == -1) {
  1290. util::fail("不满足最低消费金额{$hb->minConsume}元");
  1291. }
  1292. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);
  1293. } else {
  1294. util::fail('红包无效');
  1295. }
  1296. }
  1297. $psMethodError = \bizHd\order\classes\PsMethodClass::checkLimit(
  1298. $this->shopId,
  1299. $this->mainId,
  1300. $sendType,
  1301. $goodsOnlyPrice,
  1302. $itemBigNum,
  1303. $packingFee,
  1304. $unMeetSendCost,
  1305. $hdCustomId,
  1306. $customInfo
  1307. );
  1308. if ($psMethodError !== '') {
  1309. util::fail($psMethodError);
  1310. }
  1311. $sendType = $post['sendType'] ?? 0;
  1312. if ($sendType != 1) {
  1313. if (empty($post['reachPeriod'])) {
  1314. util::fail('请选择配送时间哈');
  1315. }
  1316. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  1317. }
  1318. $post['bigNum'] = $totalNum;
  1319. $post['modifyPrice'] = $modifyPrice;
  1320. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  1321. $orderSn = $return->orderSn ?? '';
  1322. if (!empty($orderSn) && (float)$unMeetSendCost > 0) {
  1323. $unMeetSendKey = 'hd_ps_order_unmeet_send_' . $orderSn;
  1324. Yii::$app->redis->executeCommand('SETEX', [$unMeetSendKey, 864000, (string)$unMeetSendCost]);
  1325. }
  1326. if (!empty($hb)) {
  1327. $hb->status = 1;
  1328. $hb->orderId = $return->id;
  1329. $hb->save();
  1330. }
  1331. if ($return->sendType == 2) {
  1332. $ext = ShopExtClass::getByCondition(['shopId' => $return->shopId], true, null, 'id,shopId,thirdSend');
  1333. if (!empty($ext) && $ext->thirdSend == 1) {
  1334. util::fail('本店暂不能使用跑腿呢');
  1335. }
  1336. }
  1337. $transaction->commit();
  1338. $transactionFinished = true;
  1339. \bizHd\product\classes\ProductClass::clearLimitBuyRollbackSnapshot();
  1340. HomePageModuleClass::clearSeckillReservationSnapshot();
  1341. $orderSn = $return->orderSn ?? '';
  1342. $orderPrice = $return->orderPrice ?? ($return->actPrice ?? 0);
  1343. $id = $return->id ?? 0;
  1344. $getPayType = dict::getDict('getPayType');
  1345. util::success([
  1346. 'orderSn' => $orderSn,
  1347. 'totalPrice' => $orderPrice,
  1348. 'couponId' => 0,
  1349. 'id' => $id,
  1350. 'getPayType' => $getPayType,
  1351. ]);
  1352. } catch (\Exception $e) {
  1353. $transaction->rollBack();
  1354. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  1355. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  1356. $transactionFinished = true;
  1357. Yii::error("合并下单失败:" . $e->getMessage());
  1358. util::fail('下单失败');
  1359. }
  1360. }
  1361. //下单要用到的相关信息 ssh 2019.12.6
  1362. public function actionOrderRelate()
  1363. {
  1364. $regionTree = RegionService::tree();
  1365. //门店名称
  1366. $shop = !empty($this->shop) ? $this->shop->attributes : [];
  1367. $sjName = $shop['merchantName'] ?? '';
  1368. $shopName = $shop['shopName'] ?? '';
  1369. $shop['showName'] = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  1370. $avatar = $shop['avatar'] ?? '';
  1371. $smallAvatar = imgUtil::groupImg($avatar) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  1372. $shop['smallAvatar'] = $smallAvatar;
  1373. $freight = ['first' => 5, 'add' => 2];
  1374. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  1375. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  1376. util::success($out);
  1377. }
  1378. //余额支付 ssh 20250410
  1379. public function actionBalancePay()
  1380. {
  1381. $post = Yii::$app->request->post();
  1382. $orderSn = $post['orderSn'] ?? '';
  1383. //避免重复提交
  1384. util::checkRepeatCommit($orderSn, 5);
  1385. $connection = Yii::$app->db;
  1386. $transaction = $connection->beginTransaction();
  1387. try {
  1388. $order = OrderClass::getByCondition(['orderSn' => $orderSn], true);
  1389. if (empty($order)) {
  1390. util::fail('没有找到订单');
  1391. }
  1392. if ($order->shopId != $this->shopId) {
  1393. util::fail('不是你的订单');
  1394. }
  1395. //支付前验证订单有效性
  1396. OrderService::checkBeforePay($order);
  1397. $payWay = dict::getDict('payWay', 'balancePay');
  1398. \bizHd\order\classes\OrderClass::payAfter($order, $payWay);
  1399. $transaction->commit();
  1400. //解决重复通知,重要
  1401. $cacheKey = 'mall_order_balance_pay_' . $orderSn;
  1402. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1403. if (empty($has)) {
  1404. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  1405. //打印小票和语音播报
  1406. $order = \bizHd\order\classes\OrderClass::getByCondition(['orderSn' => $orderSn], true);
  1407. if (!empty($order)) {
  1408. \bizHd\order\classes\OrderClass::onlinePrint($order);
  1409. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  1410. HdDeliveryOrderClass::payAfter($order);
  1411. $shopId = $order->shopId ?? 0;
  1412. $shop = ShopClass::getById($shopId, true);
  1413. if (in_array($order->fromType, [1, 3])) {
  1414. //您有新的收入提醒
  1415. WxMessageClass::gatheringIncomeInform($shop, $order);
  1416. }
  1417. if ($order->fromType == 2) {
  1418. //来自商城的新订单微信通知
  1419. WxMessageClass::hdNewOrderInform($shop, $order);
  1420. \bizHd\order\classes\PsMethodClass::markUnMeetFeePaidFromOrder($order);
  1421. }
  1422. }
  1423. }
  1424. util::complete('支付成功');
  1425. } catch (\Exception $e) {
  1426. $transaction->rollBack();
  1427. Yii::error("支付原因:" . $e->getMessage());
  1428. util::fail('支付失败');
  1429. }
  1430. }
  1431. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  1432. public function actionWxPay()
  1433. {
  1434. ini_set('date.timezone', 'Asia/Shanghai');
  1435. $post = Yii::$app->request->post();
  1436. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1437. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1438. $order = OrderService::getByOrderSn($orderSn);
  1439. $orderId = $order['id'];
  1440. //验证优惠券是否还有效
  1441. if (!empty($couponId)) {
  1442. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  1443. }
  1444. //支付前验证订单有效性
  1445. OrderService::checkBeforePay($order);
  1446. $name = !empty($order['orderName']) ? $order['orderName'] : '购买花材';
  1447. $shop = $this->shop;
  1448. if (empty($shop)) {
  1449. util::fail('没有找到门店信息');
  1450. }
  1451. if (isset($shop->shopName) && !empty($shop->shopName)) {
  1452. $name .= '(' . $shop->shopName . ')';
  1453. }
  1454. $totalFee = $order['mainPay'];
  1455. $openId = '';
  1456. if (!empty($post['miniOpenId'])) {
  1457. $openId = $post['miniOpenId'];
  1458. //noticeUtil::push('散客买花时,通过前端获取了openId:' . $openId, '15280215347');
  1459. }
  1460. if (empty($openId)) {
  1461. if (isset($this->user['miniOpenId']) && !empty($this->user['miniOpenId'])) {
  1462. $openId = $this->user['miniOpenId'];
  1463. //noticeUtil::push('散客买花时,通过数据库获取了openId:' . $openId, '15280215347');
  1464. }
  1465. }
  1466. if (empty($openId)) {
  1467. util::fail('没有找到openId');
  1468. }
  1469. $now = time();
  1470. $expireTime = $now + 1800;
  1471. $updateData = [];
  1472. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1473. $oldOrderSn = $orderSn;
  1474. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1475. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1476. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1477. $params = [
  1478. 'appid' => 'OP00002119',
  1479. 'serial_no' => '018b08cfddbd',
  1480. 'merchant_no' => $shop->lklSjNo,
  1481. 'term_no' => $shop->lklScanTermNo,
  1482. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1483. 'lklCertificatePath' => $lklCertificatePath,
  1484. ];
  1485. $laResource = new Lakala($params);
  1486. $closeParams = [
  1487. 'orderSn' => $oldOrderSn,
  1488. ];
  1489. $response = $laResource->close($closeParams);
  1490. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1491. $msg = $response['msg'] ?? '';
  1492. $lklSjNo = $shop->lklSjNo ?? '';
  1493. noticeUtil::push('重点注意,散客买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . '。商户号:' . $lklSjNo, '15280215347');
  1494. util::fail('出错了哦,请重新下一单');
  1495. }
  1496. $orderSn = orderSn::getOrderSn();
  1497. $updateData['orderSn'] = $orderSn;
  1498. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  1499. } else {
  1500. //已请求的不能再修改价格
  1501. $updateData['modPrice'] = 0;
  1502. }
  1503. if (empty($order['deadline'])) {
  1504. $updateData['deadline'] = $expireTime;
  1505. }
  1506. if (!empty($updateData)) {
  1507. OrderService::updateById($orderId, $updateData);
  1508. }
  1509. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1510. $sjExtend = WxOpenClass::getMallWxInfo();
  1511. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1512. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1513. $params = [
  1514. 'appid' => 'OP00002119',
  1515. 'serial_no' => '018b08cfddbd',
  1516. 'merchant_no' => $shop->lklSjNo,
  1517. 'term_no' => $shop->lklScanTermNo,
  1518. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1519. 'lklCertificatePath' => $lklCertificatePath,
  1520. ];
  1521. $laResource = new Lakala($params);
  1522. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1523. $wxParams = [
  1524. 'orderSn' => $orderSn,
  1525. 'amount' => $totalFee,
  1526. 'capitalType' => $capitalType,
  1527. 'notifyUrl' => $notifyUrl,
  1528. 'wxAppId' => $sjExtend['miniAppId'],
  1529. 'openId' => $openId,
  1530. 'subject' => $name,
  1531. 'couponId' => $couponId,
  1532. ];
  1533. $response = $laResource->driveWxPay($wxParams);
  1534. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1535. $errMsg = $response['msg'] ?? '';
  1536. noticeUtil::push($errMsg, '15280215347');
  1537. util::fail('支付失败');
  1538. }
  1539. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1540. $appId = $newParams['app_id'] ?? '';
  1541. $nonceStr = $newParams['nonce_str'] ?? '';
  1542. $paySign = $newParams['pay_sign'] ?? '';
  1543. $package = $newParams['package'] ?? '';
  1544. $signType = $newParams['sign_type'] ?? '';
  1545. $timeStamp = $newParams['time_stamp'] ?? '';
  1546. $new = [
  1547. 'id' => $orderId,
  1548. 'appId' => $appId,
  1549. 'nonceStr' => $nonceStr,
  1550. 'paySign' => $paySign,
  1551. 'package' => $package,
  1552. 'signType' => $signType,
  1553. 'timeStamp' => $timeStamp,
  1554. 'orderSn' => $orderSn,
  1555. ];
  1556. util::success($new);
  1557. }
  1558. //快捷付款订单
  1559. public function actionFastPay()
  1560. {
  1561. ini_set('date.timezone', 'Asia/Shanghai');
  1562. $post = Yii::$app->request->post();
  1563. $payWay = $post['payWay'] ?? 0;
  1564. $shopId = $this->shopId;
  1565. $shop = $this->shop;
  1566. if (empty($shop)) {
  1567. util::fail('没有门店信息');
  1568. }
  1569. $customId = $this->customId;
  1570. $custom = $this->custom;
  1571. $hdId = $this->hdId;
  1572. $hd = $this->hd;
  1573. if (empty($customId) || empty($hdId)) {
  1574. //考虑没有登录时的付款
  1575. $defaultCustomId = $shop->defaultCustomId ?? 0;
  1576. if (empty($defaultCustomId)) {
  1577. util::fail('请设置快捷开单的客户');
  1578. }
  1579. $customId = $defaultCustomId;
  1580. $custom = CustomClass::getById($defaultCustomId, true);
  1581. if (empty($custom)) {
  1582. util::fail('无效的快捷客户');
  1583. }
  1584. $hdId = $custom->hdId;
  1585. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1586. if (empty($hd)) {
  1587. util::fail('没有花店信息呢!');
  1588. }
  1589. }
  1590. $post['hdId'] = $hdId;
  1591. $post['hdName'] = $hd->name ?? '';
  1592. $customName = $custom->name ?? '';
  1593. $customPy = $custom->py ?? '';
  1594. $post['customName'] = $customName;
  1595. $post['customNamePy'] = $customPy;
  1596. $post['shopId'] = $shopId;
  1597. $post['mainId'] = $this->mainId;
  1598. $post['customId'] = $customId;
  1599. $prePrice = round($post['prePrice'], 2);
  1600. $actPrice = $prePrice;
  1601. if ($actPrice <= 0) {
  1602. util::fail('请填写付款金额');
  1603. }
  1604. $post['actPrice'] = $actPrice;
  1605. $post['userId'] = $this->userId;
  1606. $now = time();
  1607. $expireTime = $now + 300;//订单5分钟后过期
  1608. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1609. $post['deadline'] = date("Y-m-d H:i:s", $expireTime);
  1610. $order = ScanPayClass::addOrder($post);
  1611. $orderId = $order->id ?? 0;
  1612. $orderSn = $order->orderSn ?? '';
  1613. $capitalType = dict::getDict('capitalType', 'scanPay', 'id');
  1614. if ($payWay == 0) {
  1615. //微信
  1616. $name = '购买鲜花,扫码付款';
  1617. $totalFee = $actPrice;
  1618. $user = UserService::getById($this->userId);
  1619. //小程序使用miniOpenId
  1620. $openId = $user['miniOpenId'];
  1621. if (empty($openId)) {
  1622. $openId = !empty($post['miniOpenId']) ? $post['miniOpenId'] : '';
  1623. }
  1624. if (empty($openId)) {
  1625. util::fail('没有微信信息');
  1626. }
  1627. $sjExtend = WxOpenClass::getMallWxInfo();
  1628. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1629. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1630. $params = [
  1631. 'appid' => 'OP00002119',
  1632. 'serial_no' => '018b08cfddbd',
  1633. 'merchant_no' => $shop->lklSjNo,
  1634. 'term_no' => $shop->lklScanTermNo,
  1635. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1636. 'lklCertificatePath' => $lklCertificatePath,
  1637. ];
  1638. $laResource = new Lakala($params);
  1639. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1640. $wxParams = [
  1641. 'orderSn' => $orderSn,
  1642. 'amount' => $totalFee,
  1643. 'capitalType' => $capitalType,
  1644. 'notifyUrl' => $notifyUrl,
  1645. 'wxAppId' => $sjExtend['miniAppId'],
  1646. 'openId' => $openId,
  1647. 'subject' => $name,
  1648. 'couponId' => 0,
  1649. ];
  1650. $response = $laResource->driveWxPay($wxParams);
  1651. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1652. $errMsg = $response['msg'] ?? '';
  1653. noticeUtil::push($errMsg, '15280215347');
  1654. util::fail('支付失败');
  1655. }
  1656. $newParams = $response['resp_data']['acc_resp_fields'] ?? [];
  1657. $appId = $newParams['app_id'] ?? '';
  1658. $nonceStr = $newParams['nonce_str'] ?? '';
  1659. $paySign = $newParams['pay_sign'] ?? '';
  1660. $package = $newParams['package'] ?? '';
  1661. $signType = $newParams['sign_type'] ?? '';
  1662. $timeStamp = $newParams['time_stamp'] ?? '';
  1663. $new = [
  1664. 'id' => $orderId,
  1665. 'appId' => $appId,
  1666. 'nonceStr' => $nonceStr,
  1667. 'paySign' => $paySign,
  1668. 'package' => $package,
  1669. 'signType' => $signType,
  1670. 'timeStamp' => $timeStamp,
  1671. 'orderSn' => $orderSn,
  1672. ];
  1673. util::success($new);
  1674. } elseif ($payWay == 1) {
  1675. //支付宝
  1676. $totalFee = $actPrice;
  1677. $subject = '购买鲜花,扫码付款';
  1678. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1679. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1680. $params = [
  1681. 'appid' => 'OP00002119',
  1682. 'serial_no' => '018b08cfddbd',
  1683. 'merchant_no' => $shop->lklSjNo,
  1684. 'term_no' => $shop->lklB2BTermNo,
  1685. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1686. 'lklCertificatePath' => $lklCertificatePath,
  1687. ];
  1688. $laResource = new Lakala($params);
  1689. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/cash-pay-callback";
  1690. $cashParams = [
  1691. 'orderSn' => $orderSn,
  1692. 'amount' => $totalFee,
  1693. 'capitalType' => $capitalType,
  1694. 'notifyUrl' => $notifyUrl,
  1695. 'subject' => $subject,
  1696. ];
  1697. $response = $laResource->cashierPay($cashParams);
  1698. if (!isset($response['code']) || $response['code'] != '000000') {
  1699. util::fail('支付失败了');
  1700. }
  1701. $url = $response['resp_data']['counter_url'] ?? '';
  1702. if (empty($url)) {
  1703. util::fail('支付失败');
  1704. }
  1705. util::success(['url' => $url]);
  1706. } elseif ($payWay == 2) {
  1707. //余额支付
  1708. util::fail('暂不支持');
  1709. } else {
  1710. util::fail('无效的支付方式');
  1711. }
  1712. }
  1713. //订单列表 ssh 2019.12.12
  1714. public function actionList()
  1715. {
  1716. $get = Yii::$app->request->get();
  1717. $status = $get['status'] ?? 0;
  1718. $hdId = $get['hdId'] ?? 0;
  1719. $userId = $this->userId;
  1720. $where = ['userId' => $userId];
  1721. if (!empty($status)) {
  1722. $where['status'] = $status;
  1723. }
  1724. if (!empty($hdId)) {
  1725. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1726. if (empty($hd)) {
  1727. util::fail('无效的花店');
  1728. }
  1729. if ($hd['userId'] != $userId) {
  1730. util::fail('不是你的花店');
  1731. }
  1732. $where['hdId'] = $hdId;
  1733. }
  1734. $list = OrderService::getOrderList($where);
  1735. util::success($list);
  1736. }
  1737. //订单评价
  1738. public function actionComment()
  1739. {
  1740. $post = Yii::$app->request->post();
  1741. $id = $post['id'];
  1742. $order = OrderClass::getById($id);
  1743. if ($order['grade'] > 0) {
  1744. util::fail('您已经评过了');
  1745. }
  1746. OrderService::comment($post);
  1747. util::complete('提交成功');
  1748. }
  1749. //订单详情 ssh 2019.12.16
  1750. public function actionDetail()
  1751. {
  1752. $id = Yii::$app->request->get('id', 0);
  1753. $detail = OrderClass::getOrderById($id);
  1754. $userId = $this->userId;
  1755. if ($detail['userId'] != $userId) {
  1756. util::fail('不是你的单,不能查看');
  1757. }
  1758. $shOrderMap = [];
  1759. if ($detail['hasForward'] == 1) {
  1760. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1761. }
  1762. $detail['shOrderMap'] = $shOrderMap;
  1763. //是否显示余额支付按钮 ssh 20260120
  1764. $hd = $this->hd;
  1765. $balance = $hd->balance ?? 0;
  1766. $showYePay = $balance > 0 ? 1 : 0;
  1767. $detail['showYePay'] = $showYePay;
  1768. $detail['balance'] = $balance;
  1769. $detail['rechargeWeal'] = $this->shop->rechargeWeal; //是否开启余额支付
  1770. util::success($detail);
  1771. }
  1772. //获取详情 ssh 20220512
  1773. public function actionInfo()
  1774. {
  1775. $sn = Yii::$app->request->get('orderSn', '');
  1776. $detail = OrderClass::getOrderBySn($sn);
  1777. util::success($detail);
  1778. }
  1779. }