OrderController.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\hb\classes\HbClass;
  4. use Yii;
  5. use biz\shop\classes\ShopExtClass;
  6. use biz\sj\services\MerchantExtendService;
  7. use biz\sj\services\MerchantService;
  8. use bizHd\custom\classes\CustomClass;
  9. use bizHd\custom\classes\HdClass;
  10. use bizHd\goods\classes\GoodsClass;
  11. use bizHd\merchant\services\ShopService;
  12. use bizHd\order\classes\OrderClass;
  13. use bizHd\order\classes\OrderForwardClass;
  14. use bizHd\order\classes\OrderItemClass;
  15. use bizHd\order\classes\OrderSendClass;
  16. use hd\models\order\CreateOrderForm;
  17. use bizHd\express\classes\HdDeliveryOrderClass;
  18. use bizHd\order\services\OrderService;
  19. use bizHd\product\classes\ProductClass;
  20. use bizHd\saas\services\RegionService;
  21. use bizHd\shop\classes\ShopClass;
  22. use bizHd\user\services\UserService;
  23. use bizHd\work\classes\WorkClass;
  24. use common\components\dict;
  25. use common\components\dateUtil;
  26. use common\components\noticeUtil;
  27. use common\components\orderSn;
  28. use common\components\payUtil;
  29. use common\services\xhPayToolService;
  30. use common\components\util;
  31. use common\components\stringUtil;
  32. use bizHd\promote\services\CouponService;
  33. use common\components\httpUtil;
  34. use biz\wx\classes\WxMessageClass;
  35. use common\components\lakala\Lakala;
  36. use yii\helpers\ArrayHelper;
  37. class OrderController extends BaseController
  38. {
  39. public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list', 'info'];
  40. public function actionDebt()
  41. {
  42. $get = Yii::$app->request->get();
  43. $id = $get['id'] ?? 0;
  44. $info = OrderClass::getById($id, true);
  45. if (empty($info)) {
  46. util::fail('没有找到订单');
  47. }
  48. if ($info->mainId != $this->mainId) {
  49. util::fail('不是你的订单');
  50. }
  51. //4秒内不允许重复提交
  52. util::checkRepeatCommit($id, 4);
  53. if ($info->status != 1) {
  54. util::fail('订单已付款或取消');
  55. }
  56. $payWay = dict::getDict('payWay', 'debtPay');
  57. $connection = Yii::$app->db;
  58. $transaction = $connection->beginTransaction();
  59. try {
  60. $actPrice = $info->actPrice ?? 0;
  61. $info->debtPrice = $actPrice;
  62. $info->remainDebtPrice = $actPrice;
  63. $info->debt = 1;
  64. $info->save();
  65. OrderClass::payAfter($info, $payWay);
  66. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  67. if ($info->getGoods == 1 && $info->sendType == 1 && $info->status == 2) {
  68. $info->status = 4;
  69. $info->save();
  70. }
  71. $transaction->commit();
  72. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  73. HdDeliveryOrderClass::payAfter($info);
  74. util::complete('赊账成功');
  75. } catch (\Exception $exception) {
  76. $transaction->rollBack();
  77. Yii::info("赊账失败原因:" . $exception->getMessage());
  78. util::fail('操作失败');
  79. }
  80. }
  81. //取消订单 ssh 20221231
  82. public function actionCancel()
  83. {
  84. //避免重复提交
  85. $adminId = $this->adminId;
  86. util::checkRepeatCommit($adminId, 8);
  87. $get = Yii::$app->request->get();
  88. $id = $get['id'] ?? 0;
  89. $order = OrderClass::getById($id, true);
  90. if ($order->mainId != $this->mainId) {
  91. util::fail('不是你的订单');
  92. }
  93. $staff = $this->shopAdmin;
  94. $connection = Yii::$app->db;
  95. $transaction = $connection->beginTransaction();
  96. try {
  97. OrderClass::setExpire($order, true, $staff);
  98. $transaction->commit();
  99. util::complete();
  100. } catch (\Exception $exception) {
  101. $transaction->rollBack();
  102. Yii::info("取消原因:" . $exception->getMessage());
  103. util::fail('取消失败');
  104. }
  105. }
  106. //修改订单 ssh 20220926
  107. public function actionUpdate()
  108. {
  109. $post = Yii::$app->request->post();
  110. $id = $post['id'] ?? 0;
  111. $order = OrderClass::getById($id, true);
  112. OrderClass::valid($order, $this->mainId);
  113. unset($post['id']);
  114. if ($order->status == 3) {
  115. util::fail('订单已配送');
  116. }
  117. if ($order->status == 4) {
  118. util::fail('订单已完成');
  119. }
  120. if ($order->status == 5) {
  121. util::fail('订单已取消');
  122. }
  123. if ($order->fromType == 4) {
  124. util::fail('请在美团APP上修改');
  125. }
  126. $address = $post['address'] ?? '';
  127. $floor = $post['floor'] ?? '';
  128. $post['fullAddress'] = $address . $floor;
  129. OrderClass::updateById($id, $post);
  130. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  131. $remark = $post['remark'] ?? '';
  132. $reachDate = $post['reachDate'] ?? '';
  133. $reachPeriod = $post['reachPeriod'] ?? '';
  134. $cardInfo = $post['cardInfo'] ?? '';
  135. $anonymity = $post['anonymity'] ?? 0;
  136. $bookName = $post['bookName'] ?? '';
  137. if (!empty($workList)) {
  138. foreach ($workList as $work) {
  139. $work->remark = $remark;
  140. $work->reachDate = $reachDate;
  141. $work->reachPeriod = $reachPeriod;
  142. $work->cardInfo = $cardInfo;
  143. $work->anonymity = $anonymity;
  144. $work->bookName = $bookName;
  145. $work->save();
  146. }
  147. }
  148. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  149. ShopExtClass::orderUpdateRemind($shopExt, $order);
  150. util::complete();
  151. }
  152. //客户欠款的订单 ssh 2021.2.4
  153. public function actionDebtList()
  154. {
  155. $get = Yii::$app->request->get();
  156. $id = $get['id'] ?? 0;
  157. $info = CustomClass::getById($id, true);
  158. CustomClass::valid($info, $this->shopId);
  159. $where = ['customId' => $id, 'debt' => 1];
  160. $searchTime = $get['searchTime'] ?? '';
  161. if (!empty($searchTime)) {
  162. $startTime = $get['startTime'] ?? '';
  163. $endTime = $get['endTime'] ?? '';
  164. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  165. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  166. }
  167. $allowedPageSizes = [100, 200, 300];
  168. $pageSize = isset($get['pageSize']) && in_array((int)$get['pageSize'], $allowedPageSizes, true)
  169. ? (int)$get['pageSize'] : 100;
  170. $page = max(1, (int)($get['page'] ?? 1));
  171. $fields = ['id', 'orderSn', 'actPrice', 'addTime', 'remainDebtPrice', 'debtPrice'];
  172. Yii::$app->request->setQueryParams(array_merge($get, ['page' => $page, 'pageSize' => $pageSize]));
  173. $result = OrderClass::getList($fields, $where, 'addTime DESC');
  174. if (!empty($result['list'])) {
  175. foreach ($result['list'] as $key => $value) {
  176. $debtPrice = $value['debtPrice'] ?? 0;
  177. $remainDebtPrice = $value['remainDebtPrice'] ?? 0;
  178. $hasPayDebt = 0;
  179. if ($debtPrice > $remainDebtPrice) {
  180. $hasPayDebt = bcsub($debtPrice, $remainDebtPrice, 2);
  181. }
  182. $result['list'][$key]['hasPayDebt'] = floatval($hasPayDebt);
  183. }
  184. }
  185. $result['customInfo'] = $info;
  186. util::success($result);
  187. }
  188. //确认送达 ssh 20250902
  189. public function actionReach()
  190. {
  191. //解决重复提交
  192. util::checkRepeatCommit($this->adminId, 5);
  193. $get = Yii::$app->request->get();
  194. $id = $get['id'] ?? 0;
  195. $order = OrderClass::getById($id, true);
  196. if (empty($order)) {
  197. util::fail('没有找到订单');
  198. }
  199. OrderClass::valid($order, $this->mainId);
  200. if ($order->status == 5) {
  201. util::fail('订单已取消');
  202. }
  203. if ($order->status == 1) {
  204. util::fail('订单待付款');
  205. }
  206. if ($order->status == 2) {
  207. util::fail('订单未发货');
  208. }
  209. if ($order->status == 4) {
  210. util::fail('订单已经送到了');
  211. }
  212. if (!in_array($order->sendStatus, [-1, -4])) {
  213. util::fail('由跑腿送货,无需确认');
  214. }
  215. $order->status = 4;
  216. $order->save();
  217. util::complete('操作成功');
  218. }
  219. //确认取货
  220. public function actionFetch()
  221. {
  222. $get = Yii::$app->request->get();
  223. $id = $get['id'] ?? 0;
  224. //解决重复提交
  225. util::checkRepeatCommit($id . '_' . $this->adminId, 5);
  226. $order = OrderClass::getById($id, true);
  227. if (empty($order)) {
  228. util::fail('没有找到订单');
  229. }
  230. OrderClass::valid($order, $this->mainId);
  231. if ($order->status == 5) {
  232. util::fail('订单已取消');
  233. }
  234. if ($order->status == 1) {
  235. util::fail('订单待付款');
  236. }
  237. if ($order->status == 4) {
  238. util::fail('订单已取过了');
  239. }
  240. if (in_array($order->sendStatus, [-1, 0, 1, 2, 4, 5])) {
  241. util::fail('由跑腿送货,无需确认');
  242. }
  243. $order->status = 4;
  244. $order->save();
  245. util::complete('操作成功');
  246. }
  247. //批量确认取货 待发货的自取订单 每次500个
  248. public function actionBatchFetch()
  249. {
  250. $where = ["status" => 2, "sendType" => 1, "shopId" => $this->shopId];
  251. $orderList = OrderService::getLimitList("id", $where, 500, "id desc");
  252. $ids = ArrayHelper::getColumn($orderList, "id");
  253. OrderService::updateByIds($ids, ["status" => 4]);
  254. util::complete($ids);
  255. }
  256. //确认发货
  257. public function actionSend()
  258. {
  259. //解决重复提交
  260. util::checkRepeatCommit($this->adminId, 5);
  261. $get = Yii::$app->request->get();
  262. $id = $get['id'] ?? 0;
  263. $order = OrderClass::getById($id, true);
  264. if (empty($order)) {
  265. util::fail('没有找到订单');
  266. }
  267. OrderClass::valid($order, $this->mainId);
  268. if ($order->status != 2) {
  269. util::fail('订单不是待发货状态');
  270. }
  271. // $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  272. // if (!empty($workList)) {
  273. // $unComplete = false;
  274. // foreach ($workList as $work) {
  275. // if ($work->status != 1) {
  276. // $unComplete = true;
  277. // }
  278. // }
  279. // if ($unComplete == true) {
  280. // util::fail('还有制作单没有完成');
  281. // }
  282. // }
  283. $order->status = 3;
  284. $order->save();
  285. util::complete('已发货');
  286. }
  287. //打印订单 ssh 20220601
  288. public function actionPrintOrder()
  289. {
  290. $get = Yii::$app->request->get();
  291. $id = isset($get['id']) ? $get['id'] : 0;
  292. $order = OrderClass::getById($id, true);
  293. if (empty($order)) {
  294. util::fail('没有找到订单');
  295. }
  296. if ($order->forward == 1) {
  297. util::fail('红冲订单不能打印');
  298. }
  299. OrderClass::valid($order, $this->mainId);
  300. OrderClass::onlinePrint($order, true);
  301. util::complete();
  302. }
  303. //微信和支付宝付款码支付复查 ssh 20220422
  304. public function actionCodePayCheck()
  305. {
  306. ini_set('date.timezone', 'Asia/Shanghai');
  307. header("Content-type: text/html; charset=utf-8");
  308. $get = Yii::$app->request->get();
  309. $id = isset($get['id']) ? $get['id'] : 0;
  310. util::checkRepeatCommit($id, 3);
  311. $order = OrderClass::getById($id, true);
  312. OrderClass::valid($order, $this->mainId);
  313. $orderSn = $order->orderSn ?? '';
  314. $totalFee = $order->mainPay ?? 0;
  315. if ($order->payStatus == 1) {
  316. util::success(['returnStatus' => 'SUCCESS']);
  317. } else {
  318. util::success(['returnStatus' => 'unPay']);
  319. }
  320. $connection = Yii::$app->db;
  321. $transaction = $connection->beginTransaction();
  322. try {
  323. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  324. $shop = $this->shop;
  325. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  326. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  327. $params = [
  328. 'appid' => 'OP00002119',
  329. 'serial_no' => '018b08cfddbd',
  330. 'merchant_no' => $shop->lklSjNo,
  331. 'term_no' => $shop->lklScanTermNo,
  332. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  333. 'lklCertificatePath' => $lklCertificatePath,
  334. ];
  335. $laResource = new Lakala($params);
  336. $scanParams = ['orderSn' => $orderSn,];
  337. $response = $laResource->query($scanParams);
  338. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  339. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  340. $payWayType = dict::getDict('payWay', 'wxPay');
  341. $account_type = $response['resp_data']['account_type'] ?? '';
  342. if ($account_type == 'WECHAT') {
  343. $payWayType = dict::getDict('payWay', 'wxPay');
  344. }
  345. if ($account_type == 'ALIPAY') {
  346. $payWayType = dict::getDict('payWay', 'alipay');
  347. }
  348. $transactionId = $response['resp_data']['trade_no'] ?? '';
  349. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  350. $order->save();
  351. $attach = '';
  352. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  353. $transaction->commit();
  354. //解决重复通知
  355. $cacheKey = 'hd_shop_order_pay_check_' . $orderSn;
  356. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  357. if (empty($has)) {
  358. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  359. //打印小票和语音播报
  360. $newOrder = OrderClass::getById($id, true);
  361. OrderClass::onlinePrint($newOrder);
  362. ShopExtClass::hdGatheringReport($newOrder);
  363. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  364. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  365. $newOrder->status = 4;
  366. $newOrder->save();
  367. }
  368. HdDeliveryOrderClass::payAfter($newOrder);
  369. $shopId = $newOrder->shopId ?? 0;
  370. $shop = ShopClass::getById($shopId, true);
  371. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  372. }
  373. util::success(['returnStatus' => 'SUCCESS']);
  374. } else {
  375. util::complete('未知状态..');
  376. }
  377. }
  378. util::complete('未知状态..');
  379. } catch (\Exception $e) {
  380. $transaction->rollBack();
  381. util::complete('支付失败');
  382. }
  383. }
  384. //微信和支付宝付款码支付复查 ssh 20260716
  385. public function actionCodePayVerify()
  386. {
  387. ini_set('date.timezone', 'Asia/Shanghai');
  388. header("Content-type: text/html; charset=utf-8");
  389. $get = Yii::$app->request->get();
  390. $id = $get['id'] ?? 0;
  391. util::checkRepeatCommit($id, 3);
  392. $order = OrderClass::getById($id, true);
  393. OrderClass::valid($order, $this->mainId);
  394. $orderSn = $order->orderSn ?? '';
  395. $totalFee = $order->mainPay ?? 0;
  396. if ($order->payStatus == 1) {
  397. util::success(['returnStatus' => 'SUCCESS']);
  398. } else {
  399. util::success(['returnStatus' => 'unPay']);
  400. }
  401. $connection = Yii::$app->db;
  402. $transaction = $connection->beginTransaction();
  403. try {
  404. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  405. $shop = $this->shop;
  406. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  407. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  408. $params = [
  409. 'appid' => 'OP00002119',
  410. 'serial_no' => '018b08cfddbd',
  411. 'merchant_no' => $shop->lklSjNo,
  412. 'term_no' => $shop->lklScanTermNo,
  413. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  414. 'lklCertificatePath' => $lklCertificatePath,
  415. ];
  416. $laResource = new Lakala($params);
  417. $scanParams = ['orderSn' => $orderSn,];
  418. $response = $laResource->query($scanParams);
  419. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  420. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  421. $payWayType = dict::getDict('payWay', 'wxPay');
  422. $account_type = $response['resp_data']['account_type'] ?? '';
  423. if ($account_type == 'WECHAT') {
  424. $payWayType = dict::getDict('payWay', 'wxPay');
  425. }
  426. if ($account_type == 'ALIPAY') {
  427. $payWayType = dict::getDict('payWay', 'alipay');
  428. }
  429. $transactionId = $response['resp_data']['trade_no'] ?? '';
  430. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  431. $order->save();
  432. $attach = '';
  433. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  434. $transaction->commit();
  435. //解决重复通知
  436. $cacheKey = 'hd_shop_order_pay_check_' . $orderSn;
  437. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  438. if (empty($has)) {
  439. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  440. //打印小票和语音播报
  441. $newOrder = OrderClass::getById($id, true);
  442. OrderClass::onlinePrint($newOrder);
  443. ShopExtClass::hdGatheringReport($newOrder);
  444. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  445. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  446. $newOrder->status = 4;
  447. $newOrder->save();
  448. }
  449. HdDeliveryOrderClass::payAfter($newOrder);
  450. $shopId = $newOrder->shopId ?? 0;
  451. $shop = ShopClass::getById($shopId, true);
  452. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  453. }
  454. util::success(['returnStatus' => 'SUCCESS']);
  455. } else {
  456. util::success(['returnStatus' => 'PENDING'], '等待支付中...');
  457. }
  458. }
  459. util::success(['returnStatus' => 'PENDING'], '等待支付中...');
  460. } catch (\Exception $e) {
  461. $transaction->rollBack();
  462. util::complete('支付失败');
  463. }
  464. }
  465. /**
  466. * 微信和支付宝付款码支付
  467. * 职责:处理商户扫描客户付款码(被扫支付)的请求,调用拉卡拉支付接口并更新本地订单状态(零售端)
  468. * 入参:GET 传参 id (订单ID), authCode (付款码), version (版本号)
  469. * 返回:JSON 格式的支付结果(SUCCESS/FAILURE)
  470. * 副作用:更新订单支付状态、支付方式,记录支付日志,触发云打印、跑腿呼叫及语音播报
  471. * 关键边界:
  472. * 1. 验证订单有效性与待付款状态
  473. * 2. 校验付款码格式(微信/支付宝)
  474. * 3. 优化:将拉卡拉外部网络请求移出数据库事务,避免因网络延迟长时间占用数据库连接和行锁
  475. */
  476. public function actionCodePay()
  477. {
  478. ini_set('date.timezone', 'Asia/Shanghai');
  479. header("Content-type: text/html; charset=utf-8");
  480. $get = Yii::$app->request->get();
  481. $id = isset($get['id']) ? $get['id'] : 0;
  482. util::checkRepeatCommit($id, 3);
  483. $version = $get['version'] ?? 0;
  484. $order = OrderClass::getById($id, true);
  485. OrderClass::valid($order, $this->mainId);
  486. if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
  487. $msg = '订单已取消';
  488. util::success(['returnStatus' => 'FAILURE'], $msg);
  489. }
  490. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  491. $msg = '订单不是待付款状态';
  492. util::success(['returnStatus' => 'FAILURE'], $msg);
  493. }
  494. $shop = $this->shop;
  495. $sj = $shop->merchantName;
  496. $shopName = $shop->shopName;
  497. $name = $shopName == '首店' ? $sj : $sj . '-' . $shopName;
  498. $authCode = (string)$get['authCode'] ?? '';
  499. if ($version > 0) {
  500. if (empty($authCode)) {
  501. $msg = '没有扫到付款码';
  502. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  503. noticeUtil::push($remind . ' 编号005', '15280215347');
  504. util::success(['returnStatus' => 'FAILURE'], $msg);
  505. }
  506. //微信文档说明 https://pay.weixin.qq.com/doc/v2/merchant/4011936234
  507. $wxPattern = '/^(10|11|12|13|14|15)\d{16}$/';
  508. //支付宝文档说明 https://opendocs.alipay.com/open/194/106039/
  509. $aliPattern = '/^(25|26|27|28|29|30)\d{14,22}$/';
  510. if (!preg_match($wxPattern, $authCode) && !preg_match($aliPattern, $authCode)) {
  511. $msg = '付款码错误,请使用微信或支付宝付款码';
  512. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  513. //noticeUtil::push($remind . ' 编号009', '15280215347');
  514. util::success(['returnStatus' => 'FAILURE'], $msg);
  515. }
  516. } else {
  517. if (empty($authCode)) {
  518. util::fail('没有获取到支付码');
  519. }
  520. }
  521. $orderSn = $order->orderSn ?? '';
  522. $lsCodePayErrorKey = 'ls_code_pay_error_' . $id;
  523. $hasFailPay = Yii::$app->redis->executeCommand('GET', [$lsCodePayErrorKey]);
  524. //前面有付失败过,要重新生成单号
  525. if (!empty($hasFailPay)) {
  526. $oldOrderSn = $order->orderSn;
  527. $orderSn = orderSn::getOrderSn();
  528. $order->orderSn = $orderSn;
  529. $order->save();
  530. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  531. }
  532. $subject = '购买花材 ' . $orderSn;
  533. $totalFee = $order->mainPay ?? 0;
  534. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  535. try {
  536. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  537. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  538. $params = [
  539. 'appid' => 'OP00002119',
  540. 'serial_no' => '018b08cfddbd',
  541. 'merchant_no' => $shop->lklSjNo,
  542. 'term_no' => $shop->lklScanTermNo,
  543. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  544. 'lklCertificatePath' => $lklCertificatePath,
  545. ];
  546. $laResource = new Lakala($params);
  547. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  548. $scanParams = [
  549. 'orderSn' => $orderSn,
  550. 'amount' => $totalFee,
  551. 'capitalType' => $capitalType,
  552. 'notifyUrl' => $notifyUrl,
  553. 'subject' => $subject,
  554. 'authCode' => $authCode,
  555. ];
  556. // 复杂分支/关键逻辑:在调用外部支付接口前不开启事务,防止网络延迟卡死数据库连接
  557. $response = $laResource->scanPay($scanParams);
  558. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  559. // 复杂分支/关键逻辑:支付成功后,开启数据库事务,确保本地订单状态更新的原子性
  560. $connection = Yii::$app->db;
  561. $transaction = $connection->beginTransaction();
  562. try {
  563. $account_type = $response['resp_data']['account_type'] ?? '';
  564. $payWayType = dict::getDict('payWay', 'wxPay');
  565. if ($account_type == 'WECHAT') {
  566. $payWayType = dict::getDict('payWay', 'wxPay');
  567. }
  568. if ($account_type == 'ALIPAY') {
  569. $payWayType = dict::getDict('payWay', 'alipay');
  570. }
  571. $order->payWay = $payWayType;
  572. $transactionId = $response['resp_data']['trade_no'] ?? '';
  573. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  574. $order->save();
  575. $attach = '';
  576. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  577. $transaction->commit();
  578. } catch (\Exception $e) {
  579. $transaction->rollBack();
  580. throw $e;
  581. }
  582. //解决重复通知
  583. $cacheKey = 'hd_shop_order_pay_' . $orderSn;
  584. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  585. if (empty($has)) {
  586. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  587. $newOrder = OrderClass::getById($id, true);
  588. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  589. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  590. $newOrder->status = 4;
  591. $newOrder->save();
  592. }
  593. //打印小票
  594. OrderClass::onlinePrint($newOrder);
  595. HdDeliveryOrderClass::payAfter($newOrder);
  596. //语音播报
  597. ShopExtClass::hdGatheringReport($newOrder);
  598. $shopId = $newOrder->shopId ?? 0;
  599. $shop = ShopClass::getById($shopId, true);
  600. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  601. }
  602. util::success(['returnStatus' => 'SUCCESS']);
  603. } else {
  604. //标记有没付成功的次数,原因有可能是余额不足等
  605. Yii::$app->redis->executeCommand('SETEX', [$lsCodePayErrorKey, 1200, 'hasFail']);
  606. $msg = $response['msg'] ?? '';
  607. $retCode = $response['code'] ?? '';
  608. $fullMsg = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  609. if ($retCode == 'BBS10000' || $retCode == 'BBS11105') {
  610. $shopId = $order->shopId;
  611. ShopExtClass::remindInputPassword($shopId);
  612. }
  613. //noticeUtil::push($fullMsg . ' ' . $retCode . ' 编号008', '15280215347');
  614. util::success(['returnStatus' => 'FAILURE', 'returnCode' => $retCode], $msg);
  615. }
  616. } catch (\Exception $e) {
  617. Yii::error("零售端支付失败原因:" . $e->getMessage());
  618. util::fail('支付失败');
  619. }
  620. }
  621. //开单操作 ssh 20220316
  622. public function actionCreateOrder()
  623. {
  624. $post = Yii::$app->request->post();
  625. $post['sjId'] = $this->sjId;
  626. $post['shopId'] = $this->shopId;
  627. $post['mainId'] = $this->mainId ?? 0;
  628. $shop = $this->shop;
  629. if ($shop->memberLevelSet == 0) {
  630. //util::fail('请先设置会员等级');
  631. }
  632. $now = time();
  633. $orderValidTime = 600;
  634. $expireTime = $now + $orderValidTime;
  635. $post['deadline'] = $expireTime;
  636. $post['staffId'] = $this->shopAdminId ?? 0;
  637. $post['staffName'] = $this->shopAdmin->name ?? '';
  638. $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
  639. $version = $post['version'] ?? 0; //验证已移至 CreateOrderForm
  640. if ($version < 3) {
  641. util::fail('请升级版本,或用小程序');
  642. }
  643. //默认情况开单员工和收款员工是同个人
  644. $staffId = $this->shopAdminId ?? 0;
  645. $staffName = $this->shopAdmin->name ?? '';
  646. if (empty($post['shopAdminId'])) {
  647. $post['shopAdminId'] = $staffId;
  648. $post['shopAdminName'] = $staffName;
  649. }
  650. if (empty($post['getStaffId'])) {
  651. $post['getStaffId'] = $staffId;
  652. $post['getStaffName'] = $this->shopAdmin->name ?? '';
  653. }
  654. $groupId = !empty($post['groupId']) ? $post['groupId'] : 0;
  655. $post['fromType'] = $post['fromType'] ?? 1;
  656. if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
  657. if (empty($post['bookName'])) {
  658. util::fail('请填写订花人姓名');
  659. }
  660. }
  661. $customId = $post['customId'] ?? 0;
  662. $custom = CustomClass::getById($customId, true);
  663. if (empty($custom)) {
  664. util::fail('没有找到客户哦');
  665. }
  666. $hdId = $custom->hdId ?? 0;
  667. $hd = HdClass::getById($hdId, true);
  668. if (empty($hd)) {
  669. util::fail('客户对应的花店信息缺失,编号869');
  670. }
  671. $hdName = $hd->name ?? '';
  672. $post['hdId'] = $hdId;
  673. $post['hdName'] = $hdName;
  674. $customName = $custom->name ?? '';
  675. $post['customName'] = $customName;
  676. $post['customNamePy'] = stringUtil::py($customName);
  677. if (!empty($post['receiveMobile'])) {
  678. if (!stringUtil::isMobile($post['receiveMobile'])) {
  679. util::fail('请填写正确的收花人手机号');
  680. }
  681. }
  682. if (!empty($post['bookMobile'])) {
  683. if (!stringUtil::isMobile($post['bookMobile'])) {
  684. util::fail('请填写正确的订花人手机号');
  685. }
  686. }
  687. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  688. $post['sendType'] = $post['sendType'] ?? 1;
  689. $forward = $post['forward'] ?? 0;
  690. if ($forward == 1) {
  691. if ($hasPay != 1) {
  692. util::fail('红冲订单只能走线下转账');
  693. }
  694. $historyDate = $post['historyDate'] ?? '';
  695. if (!empty($historyDate)) {
  696. if ($historyDate != date("Y-m-d")) {
  697. util::fail('红冲订单不能修改账单日期,只能今天');
  698. }
  699. }
  700. }
  701. $productJson = $post['product'] ?? '';
  702. $productList = [];
  703. if (!empty($productJson)) {
  704. $productList = json_decode($productJson, true);
  705. }
  706. if (empty($productList) && empty($groupId)) {
  707. //商家手机上开单并生成制作单
  708. if (!empty($post['unitGoodsPrice'])) {
  709. util::fail('此功能停用,有需要请联系管理员');
  710. $unitGoodsPrice = $post['unitGoodsPrice'];
  711. if (!is_numeric($unitGoodsPrice)) {
  712. util::fail('请输入正确的单价');
  713. }
  714. $productList = GoodsClass::orderCreateGoods($post);
  715. }
  716. }
  717. //直接收款
  718. $zjGathering = $post['zjGathering'] ?? 0;
  719. if ($zjGathering == 1) {
  720. $lsGoodsPrice = $post['lsGoodsPrice'] ?? 0;
  721. if (!is_numeric($lsGoodsPrice) || $lsGoodsPrice <= 0) {
  722. util::fail('请填写价格');
  723. }
  724. //直接收款不需要打印小票
  725. $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
  726. $shopId = $this->shopId;
  727. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  728. $zjGatheringItem = !empty($ext) ? $ext->zjGatheringItem : 0;
  729. if (empty($zjGatheringItem)) {
  730. util::fail('请设置直接收款的商品');
  731. }
  732. $zjGatheringItemInfo = ProductClass::getById($zjGatheringItem, true);
  733. if (empty($zjGatheringItemInfo)) {
  734. util::fail('请设置直接收款的商品哈');
  735. }
  736. $productList = [['productId' => $zjGatheringItem, 'unitType' => 0, 'num' => 1, 'property' => '1', 'unitPrice' => $lsGoodsPrice]];
  737. }
  738. $callErrand = $post['callErrand'] ?? 0;
  739. if ($callErrand == 1) {
  740. $shopId = $this->shopId;
  741. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  742. if (!empty($shopExt) && $shopExt->orderFlow == 0) {
  743. util::fail('下单后要变待发货,才能直接发跑腿');
  744. }
  745. }
  746. $connection = Yii::$app->db;
  747. $transaction = $connection->beginTransaction();
  748. try {
  749. $post['product'] = $productList;
  750. $reduceStock = $post['reduceStock'] ?? 0;
  751. if ($reduceStock == 1) {
  752. //如果扣除库,则走另外一条路
  753. $return = OrderClass::reduceMyStock($post, $this->shop, $custom);
  754. $transaction->commit();
  755. util::success($return);
  756. }
  757. //解决开单提交订单时,别人修改价格,造成提交价格不是真实卖价问题!!
  758. $dealPrice = $post['dealPrice'] ?? 0;
  759. //解决重复提交
  760. util::checkRepeatCommit($this->adminId . '_' . $dealPrice, 3);
  761. $totalNum = 0;
  762. if ($dealPrice == 0) {
  763. $productIds = [];
  764. $hsIds = [];
  765. foreach ($productList as $pv) {
  766. $property = $pv['property'] ?? 0;
  767. $puId = $pv['productId'] ?? 0;
  768. if ($property == 0) {
  769. $hsIds[] = $puId;
  770. } else {
  771. $productIds[] = $puId;
  772. }
  773. }
  774. $itemInfo = [];
  775. if (!empty($productIds)) {
  776. $itemInfo = ProductClass::getByIds($productIds, null, 'id');
  777. }
  778. $hsInfo = [];
  779. if (!empty($hsIds)) {
  780. $hsInfo = GoodsClass::getByIds($hsIds, null, 'id');
  781. }
  782. $diff = [];
  783. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  784. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  785. $level = 0;
  786. foreach ($productList as $currentProduct) {
  787. $property = $currentProduct['property'] ?? 0;
  788. $currentPrice = $currentProduct['unitPrice'] ?? 0;
  789. $currentId = $currentProduct['productId'] ?? 0;
  790. if ($property == 1) {
  791. $systemInfo = $itemInfo[$currentId] ?? [];
  792. if (!empty($systemInfo)) {
  793. $name = $systemInfo['name'] ?? '';
  794. $systemPrice = \bizGhs\product\classes\ProductClass::getFinalPrice($systemInfo, $level, $priceMap, $addPriceMap);
  795. if (floatval($currentPrice) != floatval($systemPrice)) {
  796. $diff[] = [
  797. 'name' => $name,
  798. 'price' => $systemPrice,
  799. 'kdPrice' => $currentPrice,
  800. ];
  801. }
  802. }
  803. } else {
  804. $systemInfo = $hsInfo[$currentId] ?? [];
  805. if (!empty($systemInfo)) {
  806. $params = [];
  807. $name = $systemInfo['name'] ?? '';
  808. $hsData = GoodsClass::getFinalPrice($systemInfo, $shop, $custom, $params);
  809. $systemPrice = $hsData['price'] ?? 0;
  810. if ($systemInfo['priceType'] == 1) {
  811. if (floatval($currentPrice) != floatval($systemPrice)) {
  812. $diff[] = [
  813. 'name' => $name,
  814. 'price' => $systemPrice,
  815. 'kdPrice' => $currentPrice,
  816. ];
  817. }
  818. }
  819. }
  820. }
  821. $num = $currentProduct['num'];
  822. $totalNum = bcadd($totalNum, $num);
  823. }
  824. if (!empty($diff)) {
  825. util::success(['diff' => $diff, 'respondType' => 'priceError']);
  826. }
  827. }
  828. //红包使用,多有处,关键词 use_hb_action
  829. $hbId = $post['hbId'] ?? 0;
  830. $hb = null;
  831. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  832. $hb = HbClass::getById($hbId, true);
  833. if (!empty($hb)) {
  834. if ($hb->customId != $customId) {
  835. util::fail('不是这个客户的红包');
  836. }
  837. if ($hb->amount != $post['hbAmount']) {
  838. util::fail('红包错误'); //红包数据可能被串改
  839. }
  840. if ($hb->status == 1) {
  841. util::fail('红包已使用');
  842. }
  843. if ($hb->status == -1) {
  844. util::fail('红包已作废');
  845. }
  846. if ($hb->endTime < time()) {
  847. $hb->status = -1;
  848. $hb->save();
  849. util::fail('红包已失效');
  850. }
  851. if ($hb->beginTime > time()) {
  852. util::fail('红包可使用期未到');
  853. }
  854. if ($this->shop->rechargeWeal == 3) {
  855. // 判断支付方式是否是余额支付
  856. if ($hasPay != dict::getDict('hasPay', 'balance')) {
  857. util::fail('用红包要用余额支付');
  858. } else {
  859. if ($custom->balance < $post['modifyPrice']) {
  860. util::fail('用红包要用余额支付(您的余额不足)');
  861. }
  862. }
  863. }
  864. } else {
  865. Yii::error('没有找到红包,hbId: ', $hbId . ' ' . __METHOD__);
  866. util::fail('红包无效');
  867. }
  868. }
  869. $post['bigNum'] = $totalNum;
  870. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  871. $return = OrderService::createHdOrder($post, $custom, $hasPay);
  872. if (!empty($hb)) {
  873. $hb->status = 1;
  874. $hb->orderId = $return->id;
  875. $hb->save();
  876. }
  877. $staff = $this->shopAdmin;
  878. //售后开付款单,库存要变化,关系要建立,多处需要同步修改 sh_pay_change ssh
  879. OrderClass::shPayChange($return, $shop, $staff);
  880. //打印小票和语音播报等使用
  881. $id = $return->id ?? 0;
  882. $order = OrderClass::getById($id, true);
  883. //如果需要生成制作单
  884. $needWork = $post['needWork'] ?? 0;
  885. if ($needWork == 1) {
  886. $main = $this->main;
  887. WorkClass::needWork($order, $main);
  888. $has = WorkClass::getByCondition(['orderId' => $id], true);
  889. if (!empty($has)) {
  890. $return->hasWork = 1;
  891. $return->save();
  892. }
  893. }
  894. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  895. if ($order->getGoods == 1 && $order->sendType == 1 && $order->status == 2) {
  896. $order->status = 4;
  897. $order->save();
  898. }
  899. $transaction->commit();
  900. if ($order->fromType == 3 || $order->fromType == 4) {
  901. //除了客服号下单和美团下单,其它情况允许打小票
  902. } else {
  903. //前台打小票
  904. OrderClass::onlinePrint($order);
  905. }
  906. //订单发跑腿流程
  907. HdDeliveryOrderClass::prepareAskData($post, $order);
  908. //前台提示收款多少钱
  909. ShopExtClass::hdGatheringReport($order);
  910. //前台提醒出示付款码
  911. if (isset($order->status) && $order->status == 1) {
  912. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  913. ShopExtClass::pleasePayReport($order);
  914. }
  915. }
  916. $shopId = $order->shopId ?? 0;
  917. $shop = ShopClass::getById($shopId, true);
  918. WxMessageClass::gatheringIncomeInform($shop, $order);
  919. if ($needWork == 1) {
  920. //新制作单提示
  921. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  922. ShopExtClass::newWorkRemind($shopExt, $order);
  923. }
  924. util::success($return);
  925. } catch (\Exception $e) {
  926. $transaction->rollBack();
  927. Yii::error("下单失败原因:" . $e->getMessage());
  928. util::fail('下单失败');
  929. }
  930. }
  931. //下单要用到的相关信息 ssh 2019.12.6
  932. public function actionOrderRelate()
  933. {
  934. $regionTree = RegionService::tree();
  935. $shop = $this->shop->attributes;
  936. $freight = MerchantExtendService::getFreight($this->sjExtend);
  937. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  938. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  939. util::success($out);
  940. }
  941. //余额支付 ssh 2019.12.6
  942. public function actionBalancePay()
  943. {
  944. $post = Yii::$app->request->post();
  945. $orderSn = $post['orderSn'] ?? 0;
  946. $payPassword = $post['payPassword'] ?? 0;
  947. $couponId = $post['couponId'] ?? 0;
  948. $order = OrderService::getByOrderSn($orderSn);
  949. $userId = $this->adminId;
  950. $user = UserService::getUserInfo($userId);
  951. //验证支付密码是否正确
  952. UserService::validPayPassword($payPassword, $user);
  953. //支付前验证订单有效性
  954. OrderService::checkBeforePay($order);
  955. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  956. $totalFee = $order['prePrice'];
  957. $sourceType = 0;
  958. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  959. $actPrice = $discountData['price'];
  960. $callbackParams = [];
  961. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  962. $balance = $respond['balance'] ?? 0;
  963. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  964. }
  965. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  966. public function actionWxPay()
  967. {
  968. ini_set('date.timezone', 'Asia/Shanghai');
  969. $post = Yii::$app->request->post();
  970. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  971. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  972. $order = OrderService::getByOrderSn($orderSn);
  973. $orderId = $order['id'];
  974. //验证优惠券是否还有效
  975. if (!empty($couponId)) {
  976. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  977. }
  978. //支付前验证订单有效性
  979. OrderService::checkBeforePay($order);
  980. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  981. $totalFee = $order['realPrice'];
  982. //小程序使用miniOpenId
  983. if (httpUtil::isMiniProgram()) {
  984. $openId = $this->user['miniOpenId'];
  985. } else {
  986. $openId = $this->user['openId'];
  987. }
  988. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  989. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  990. $wxPayType = 0;
  991. if (httpUtil::isMiniProgram()) {
  992. $wxPayType = 1;
  993. }
  994. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  995. //订单30分钟后过期
  996. $now = time();
  997. $expireTime = $now + 1800;
  998. $wx = Yii::getAlias("@vendor/weixin");
  999. require_once($wx . '/lib/WxPay.Api.php');
  1000. require_once($wx . '/example/WxPay.JsApiPay.php');
  1001. $input = new \WxPayUnifiedOrder();
  1002. $input->SetBody($name);
  1003. $input->SetOut_trade_no($orderSn);
  1004. $input->SetTotal_fee($totalFee * 100);
  1005. $input->SetTime_start(date("YmdHis", $now));
  1006. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  1007. $input->SetTime_expire(date("YmdHis", $expireTime));
  1008. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1009. $input->SetTrade_type("JSAPI");
  1010. //花卉宝代为申请的微信支付
  1011. $merchantExtend = $this->sjExtend->attributes;
  1012. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1013. $input->SetSub_openid($openId);
  1014. } else {
  1015. $input->SetOpenid($openId);
  1016. }
  1017. //小程序使用miniAppId
  1018. if (httpUtil::isMiniProgram()) {
  1019. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1020. }
  1021. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1022. $tools = new \JsApiPay();
  1023. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1024. $newParams = json_decode($jsApiParameters, true);
  1025. //已请求微信不能修改价格
  1026. $updateData = [];
  1027. $updateData['modPrice'] = 0;
  1028. if (empty($order['deadline'])) {
  1029. $updateData['deadline'] = $expireTime;
  1030. }
  1031. OrderService::updateById($orderId, $updateData);
  1032. util::success($newParams);
  1033. }
  1034. //快捷付款订单
  1035. public function actionFastPay()
  1036. {
  1037. ini_set('date.timezone', 'Asia/Shanghai');
  1038. $post = Yii::$app->request->post();
  1039. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  1040. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  1041. //验证门店是否有效
  1042. $shopInfo = ShopService::getById($shopId);
  1043. ShopService::valid($shopInfo, $this->sjId);
  1044. $post['shopId'] = $shopId;
  1045. //默认门店订单
  1046. $store = isset($post['store']) ? $post['store'] : 1;
  1047. $post['store'] = $store;
  1048. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  1049. $sourceType = $this->isWx ? 0 : 1;
  1050. if (httpUtil::isMiniProgram()) {
  1051. $sourceType = 2;
  1052. }
  1053. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  1054. //兼容旧系统sourceType=3表示朋友圈来源
  1055. $fromType = $sourceType == 3 ? 2 : 0;
  1056. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  1057. $post['userId'] = $this->adminId;
  1058. $custom = $this->custom;
  1059. $post['bookName'] = $custom['userName'] ?? '';
  1060. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  1061. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  1062. $post['bookMobile'] = $bookMobile;
  1063. $prePrice = round($post['prePrice'], 2);
  1064. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1065. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1066. $actPrice = $discountData['price'];
  1067. $post['discountType'] = $discountData['discountType'];
  1068. $post['discountAmount'] = $discountData['discountAmount'];
  1069. $post['actPrice'] = $actPrice;
  1070. $post['realPrice'] = $actPrice;
  1071. $post['payStyle'] = 0;
  1072. $post['sjId'] = $this->sjId;
  1073. $now = time();
  1074. $expireTime = $now + 300;//订单5分钟后过期
  1075. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1076. $post['deadline'] = $expireTime;
  1077. if ($actPrice <= 0) {
  1078. util::fail('请填写正确的金额');
  1079. }
  1080. //微信支付订单提交不能修改价格
  1081. $post['modPrice'] = $this->isWx ? 0 : 1;
  1082. $post['sourceType'] = $sourceType;
  1083. $post['goodsNum'] = 1;
  1084. $post['fromType'] = $fromType;
  1085. $order = OrderService::addOrder($post);
  1086. $orderId = $order['id'];
  1087. $orderSn = $order['orderSn'];
  1088. $sjId = $this->sjId;
  1089. if ($payWay == 0) {
  1090. $orderId = $order['id'];
  1091. $name = '购买商品';
  1092. $totalFee = $actPrice;
  1093. $user = UserService::getById($this->adminId);
  1094. $openId = isset($user['openId']) ? $user['openId'] : 0;
  1095. if (httpUtil::isMiniProgram()) {
  1096. //小程序使用miniOpenId
  1097. $openId = $user['miniOpenId'];
  1098. }
  1099. if (empty($openId)) {
  1100. util::fail('没有找到客户的openId');
  1101. }
  1102. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1103. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1104. $wxPayType = 0;
  1105. if (httpUtil::isMiniProgram()) {
  1106. $wxPayType = 1;
  1107. }
  1108. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  1109. $wx = Yii::getAlias("@vendor/weixin");
  1110. require_once($wx . '/lib/WxPay.Api.php');
  1111. require_once($wx . '/example/WxPay.JsApiPay.php');
  1112. $input = new \WxPayUnifiedOrder();
  1113. $input->SetBody($name);
  1114. $input->SetOut_trade_no($orderSn);
  1115. $input->SetTotal_fee($totalFee * 100);
  1116. $input->SetTime_start(date("YmdHis", $now));
  1117. $input->SetAttach($attach);
  1118. //设置订单有效期5分钟
  1119. $input->SetTime_expire(date("YmdHis", $expireTime));
  1120. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1121. $input->SetTrade_type("JSAPI");
  1122. //花卉宝代为申请的微信支付
  1123. $merchantExtend = $this->sjExtend->attributes;
  1124. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1125. $input->SetSub_openid($openId);
  1126. } else {
  1127. $input->SetOpenid($openId);
  1128. }
  1129. //小程序使用miniAppId
  1130. if (httpUtil::isMiniProgram()) {
  1131. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1132. }
  1133. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  1134. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1135. $tools = new \JsApiPay();
  1136. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1137. $newParams = json_decode($jsApiParameters, true);
  1138. $newParams['orderId'] = $orderId;
  1139. util::success($newParams);
  1140. } elseif ($payWay == 1) {
  1141. $extend = MerchantExtendService::getBySjId($sjId);
  1142. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  1143. util::fail('支付宝付款即将开通...');
  1144. }
  1145. $config = [
  1146. //应用ID,您的APPID。
  1147. 'app_id' => $extend['alipayPId'],
  1148. //商户私钥,您的原始格式RSA私钥
  1149. 'merchant_private_key' => $extend['alipayKey'],
  1150. //异步通知地址
  1151. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  1152. //同步跳转
  1153. 'return_url' => "",
  1154. //编码格式
  1155. 'charset' => "UTF-8",
  1156. //签名方式
  1157. 'sign_type' => "RSA2",
  1158. //支付宝网关
  1159. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  1160. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  1161. 'alipay_public_key' => $extend['alipayPublicKey'],
  1162. ];
  1163. Yii::info(json_encode($config) . ' aplipay config');
  1164. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  1165. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  1166. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  1167. $totalFee = $order['realPrice'];
  1168. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  1169. $subject = '购买商品';//订单名称,必填
  1170. $total_amount = $totalFee;//付款金额,必填
  1171. $body = '';//商品描述,可空
  1172. $timeout_express = "1m";//超时时间
  1173. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1174. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  1175. $passBackParams = urlencode($passBackParams);
  1176. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  1177. $payRequestBuilder->setBody($body);
  1178. $payRequestBuilder->setSubject($subject);
  1179. $payRequestBuilder->setOutTradeNo($out_trade_no);
  1180. $payRequestBuilder->setTotalAmount($total_amount);
  1181. $payRequestBuilder->setTimeExpress($timeout_express);
  1182. //在异步通知时将该参数原样返回
  1183. $payRequestBuilder->setPassbackParams($passBackParams);
  1184. //同步通知
  1185. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  1186. //异步通知
  1187. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  1188. $payResponse = new \AlipayTradeService($config);
  1189. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  1190. //直接将支付宝的html返回给前端
  1191. echo $result;
  1192. } elseif ($payWay == 2) {
  1193. //余额支付
  1194. util::fail('暂不支持');
  1195. } else {
  1196. util::fail('无效的支付方式');
  1197. }
  1198. }
  1199. //订单评价
  1200. public function actionComment()
  1201. {
  1202. $post = Yii::$app->request->post();
  1203. $id = $post['id'];
  1204. $order = OrderService::getById($id);
  1205. OrderService::valid($order, $this->mainId);
  1206. if ($order['grade'] > 0) {
  1207. util::fail('您已经评过了');
  1208. }
  1209. OrderService::comment($post);
  1210. util::complete('提交成功');
  1211. }
  1212. //订单详情,不需要登陆可以查看,要有盐,给跑腿上查看订单信息用的
  1213. public function actionInfo()
  1214. {
  1215. $get = Yii::$app->request->get();
  1216. $id = $get['id'] ?? 0;
  1217. $salt = $get['salt'] ?? '';
  1218. $detail = OrderClass::getFullInfo($id);
  1219. if (empty($detail)) {
  1220. util::fail('没有找到订单');
  1221. }
  1222. if (empty($detail['salt'])) {
  1223. util::fail('没有找到订单信息');
  1224. }
  1225. if (empty($salt)) {
  1226. util::fail('请求参数错误呢');
  1227. }
  1228. if ($detail['salt'] != $salt) {
  1229. util::fail('不是你的订单');
  1230. }
  1231. util::success($detail);
  1232. }
  1233. //订单详情
  1234. public function actionDetail()
  1235. {
  1236. $id = Yii::$app->request->get('id', 0);
  1237. $detail = OrderClass::getFullInfo($id);
  1238. OrderService::valid($detail, $this->mainId);
  1239. $forwardMap = [];
  1240. if ($detail['forward'] == 1) {
  1241. //当前单如果已经是红冲订单,则取出其对应的原单
  1242. $map = OrderForwardClass::getByCondition(['shOrderId' => $id], true);
  1243. if (!empty($map)) {
  1244. $originOrderId = $map->orderId ?? 0;
  1245. $forwardMap['orderId'] = $originOrderId;
  1246. }
  1247. }
  1248. $detail['forwardMap'] = $forwardMap;
  1249. $shOrderMap = [];
  1250. if ($detail['hasForward'] == 1) {
  1251. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1252. }
  1253. $detail['shOrderMap'] = $shOrderMap;
  1254. $main = $this->main;
  1255. //是否走红冲订单模式判断 ssh
  1256. $ret = OrderClass::ifShPay($detail, $main, 0);
  1257. $shAddPay = $ret['shAddPay'];
  1258. $shAddPayReason = $ret['shAddPayReason'];
  1259. $detail['shAddPay'] = $shAddPay;
  1260. $detail['shAddPayReason'] = $shAddPayReason;
  1261. util::success($detail);
  1262. }
  1263. public function actionList()
  1264. {
  1265. $get = Yii::$app->request->get();
  1266. $searchText = $get['searchText'] ?? '';
  1267. $shopId = $this->shopId ?? 0;
  1268. if (empty($shopId)) {
  1269. //没有登录不显示数据
  1270. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  1271. }
  1272. $where = [];
  1273. $where['shopId'] = $shopId;
  1274. if (!empty($get['customId'])) {
  1275. $where['customId'] = $get['customId'];
  1276. }
  1277. if (!empty($get['ids'])) {
  1278. $stringIds = $get['ids'];
  1279. $newIds = explode(',', $stringIds);
  1280. $where['id'] = ['in', $newIds];
  1281. }
  1282. $status = $get['status'] ?? 0;
  1283. if (!empty($status)) {
  1284. $where['status'] = $get['status'];
  1285. }
  1286. $debt = $get['debt'] ?? -1;
  1287. if ($debt > -1) {
  1288. $where['debt'] = $debt;
  1289. }
  1290. if (!empty($get['shopAdminId'])) {
  1291. $where['shopAdminId'] = $get['shopAdminId'];
  1292. }
  1293. // 按搜索词自动识别:纯数字查货号,否则查姓名
  1294. if (!empty($searchText)) {
  1295. $this->appendOrderListSearchWhere($where, $searchText);
  1296. }
  1297. if (isset($get['repeat']) && $get['repeat'] > -1) {
  1298. $where['repeat'] = $get['repeat'];
  1299. }
  1300. if (!empty($get['searchTime'])) {
  1301. $startTime = $get['startTime'] ?? '';
  1302. $endTime = $get['endTime'] ?? '';
  1303. $period = dateUtil::formatTime($get['searchTime'], $startTime, $endTime);
  1304. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1305. }
  1306. $list = OrderService::getOrderList($where);
  1307. $list['shop'] = $this->shop->attributes ?? [];
  1308. util::success($list);
  1309. }
  1310. //订单归类 ssh 2019.12.17
  1311. public function actionClassify()
  1312. {
  1313. $post = Yii::$app->request->post();
  1314. $id = $post['id'] ?? 0;
  1315. $order = OrderService::getById($id);
  1316. OrderService::valid($order, $this->mainId);
  1317. $categoryId = $post['categoryId'];
  1318. $usageId = $post['usageId'];
  1319. OrderService::classify($id, $categoryId, $usageId);
  1320. util::complete();
  1321. }
  1322. //更新配送单 ssh 2019.12.17
  1323. public function actionUpdateSheet()
  1324. {
  1325. $post = Yii::$app->request->post();
  1326. $id = $post['id'] ?? 0;
  1327. unset($post['id']);
  1328. $order = OrderService::getById($id);
  1329. OrderService::valid($order, $this->mainId);
  1330. OrderService::updateSheet($order, $post);
  1331. util::complete('提交成功');
  1332. }
  1333. //商家收款与发货 ssh 2019.12.18
  1334. public function actionGathering()
  1335. {
  1336. $post = Yii::$app->request->post();
  1337. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  1338. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  1339. $userId = $post['userId'] ?? 0;
  1340. $userInfo = UserService::getById($userId);
  1341. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  1342. util::fail('您选择的客户无效');
  1343. }
  1344. if ($price <= 0) {
  1345. util::fail('请输入金额');
  1346. }
  1347. $post['prePrice'] = $price;
  1348. $post['actPrice'] = $price;
  1349. $post['payWay'] = $payWay;
  1350. $post['sourceType'] = 1;
  1351. $post['userId'] = $userId;
  1352. $post['goodsNum'] = 1;
  1353. $post['orderName'] = '商品';
  1354. $shopId = MerchantService::getDefaultShopId($this->sj);
  1355. $post['shopId'] = $shopId;
  1356. $order = OrderService::addOrder($post);
  1357. $id = $order['id'];
  1358. $orderSn = $order['orderSn'];
  1359. //流水类型列表
  1360. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1361. $callbackParams = [];
  1362. switch ($payWay) {
  1363. case 0:
  1364. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  1365. break;
  1366. case 1:
  1367. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  1368. break;
  1369. case 2:
  1370. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  1371. break;
  1372. default:
  1373. util::fail('无效支付方式');
  1374. }
  1375. util::success($order);
  1376. }
  1377. //免发货管理 ssh 2020.1.6
  1378. public function actionWithoutSend()
  1379. {
  1380. $id = Yii::$app->request->get('id');
  1381. $order = OrderService::getById($id);
  1382. OrderService::valid($order, $this->mainId);
  1383. //配送流程变更
  1384. $currentFlow = OrderSendClass::withoutSend($order);
  1385. util::success(['currentFlow' => $currentFlow]);
  1386. }
  1387. //修改价格 ssh 2020.1.6
  1388. public function actionUpdatePrice()
  1389. {
  1390. $id = Yii::$app->request->get('id');
  1391. $price = Yii::$app->request->get('price', 1);
  1392. $order = OrderService::getById($id);
  1393. OrderService::valid($order, $this->mainId);
  1394. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1395. util::fail('已发起支付,不能修改价格');
  1396. }
  1397. OrderService::updateById($id, ['actPrice' => $price]);
  1398. util::complete('修改成功');
  1399. }
  1400. //配送单 ssh 2020.2.29
  1401. public function actionGetDeliverDetail()
  1402. {
  1403. $id = Yii::$app->request->get('id', 0);
  1404. $order = OrderService::getById($id);
  1405. OrderService::valid($order, $this->mainId);
  1406. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  1407. $reachPeriodId = $order['reachPeriod'];
  1408. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  1409. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  1410. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  1411. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  1412. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  1413. $bookName = '--';
  1414. $bookMobile = '--';
  1415. }
  1416. $data = [
  1417. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  1418. 'orderSn' => $order['orderSn'],
  1419. 'receiveUserName' => $order['receiveUserName'],
  1420. 'receiveMobile' => $order['receiveMobile'],
  1421. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  1422. 'cardInfo' => $order['cardInfo'],
  1423. 'bookMobile' => $bookMobile,
  1424. 'bookName' => $bookName,
  1425. 'remark' => $order['remark'],
  1426. 'sendNum' => $order['sendNum'],
  1427. 'telephone' => 18030142050,
  1428. 'printTime' => '',
  1429. 'img' => '',
  1430. ];
  1431. util::success($data);
  1432. }
  1433. //运费计算 lqh 2021.4.12 暂反回固定
  1434. public function actionFreight()
  1435. {
  1436. util::success(['sedCost' => 10]);
  1437. }
  1438. /**
  1439. * 订单列表搜索条件:纯数字按货号精确匹配,否则按客户姓名模糊匹配
  1440. * @param array $where 查询条件(引用传递)
  1441. * @param string $searchText 搜索关键词
  1442. */
  1443. private function appendOrderListSearchWhere(&$where, $searchText)
  1444. {
  1445. $searchText = trim((string)$searchText);
  1446. if ($searchText === '') {
  1447. return;
  1448. }
  1449. if (preg_match('/^\d+$/', $searchText)) {
  1450. $where['sendNum'] = $searchText;
  1451. return;
  1452. }
  1453. $where['customName'] = ['like', $searchText];
  1454. }
  1455. }