OrderController.php 60 KB

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