OrderController.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. <?php
  2. namespace hd\controllers;
  3. use biz\sj\services\MerchantAssetService;
  4. use biz\sj\services\MerchantExtendService;
  5. use biz\sj\services\MerchantService;
  6. use bizGhs\product\classes\ProductClass;
  7. use bizHd\custom\classes\CustomClass;
  8. use bizHd\goods\classes\GoodsClass;
  9. use bizHd\merchant\services\ShopService;
  10. use bizHd\order\classes\OrderClass;
  11. use bizHd\order\classes\OrderSendClass;
  12. use bizHd\order\services\OrderService;
  13. use bizHd\saas\services\RegionService;
  14. use bizHd\user\services\UserService;
  15. use bizGhs\order\classes\OrderItemClass;
  16. use common\components\dict;
  17. use common\components\dateUtil;
  18. use common\services\xhPayToolService;
  19. use Yii;
  20. use common\components\util;
  21. use common\components\stringUtil;
  22. use bizHd\goods\services\GoodsService;
  23. use bizHd\merchant\services\ExpressService;
  24. use bizHd\order\services\OrderGoodsService;
  25. use bizHd\promote\services\CouponService;
  26. use common\components\httpUtil;
  27. class OrderController extends BaseController
  28. {
  29. public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list'];
  30. //微信和支付宝付款码支付 ssh 2021.4.11
  31. public function actionCodePay()
  32. {
  33. $get = Yii::$app->request->get();
  34. util::success($get);
  35. /*
  36. ini_set('date.timezone', 'Asia/Shanghai');
  37. header("Content-type: text/html; charset=utf-8");
  38. $get = Yii::$app->request->get();
  39. $id = isset($get['id']) ? $get['id'] : 0;
  40. $order = OrderClass::getById($id, true);
  41. if (isset($order->status) == false || $order->status != 1) {
  42. util::fail('不是待付款订单');
  43. }
  44. OrderClass::valid($order, $this->shopId);
  45. $cgId = $order->purchaseId ?? 0;
  46. $cg = PurchaseClass::getById($cgId, true);
  47. $orderSn = $cg->orderSn ?? '';
  48. if (empty($orderSn)) {
  49. util::fail('没有找到采购单');
  50. }
  51. //付款码
  52. $authCode = (string)$get['authCode'] ?? '';
  53. if (empty($authCode)) {
  54. util::fail('支付失败');
  55. }
  56. $wxPrefix = ['10', '11', '12', '13', '14', '15'];
  57. $isWx = false;
  58. foreach ($wxPrefix as $wxId) {
  59. if (strpos($authCode, $wxId) === 0) {
  60. $isWx = true;
  61. }
  62. }
  63. $deadline = $cg->deadline;
  64. $current = date("Y-m-d H:i:s");
  65. if ((strtotime($deadline) + 20) < strtotime($current)) {
  66. util::fail('订单已经失效');
  67. }
  68. $totalFee = $cg->actPrice ?? 0;
  69. $outTradeNo = $orderSn;
  70. $subject = '购买商品';
  71. $totalAmount = $totalFee;
  72. $body = "门店";
  73. $capitalType = dict::getDict('capitalType', 'xhPurchase', 'id');
  74. if ($isWx) {
  75. $wxPayWay = dict::getDict('payWay', 'wxPay');
  76. $order->payWay = $wxPayWay;
  77. $order->save();
  78. $cg->payWay = $wxPayWay;
  79. $cg->save();
  80. $wx = Yii::getAlias("@vendor/wxPayApi_v3.0.10");
  81. require_once($wx . '/lib/WxPay.Api.php');
  82. require_once($wx . '/example/WxPay.MicroPay.php');
  83. $input = new \WxPayMicroPay();
  84. $input->SetAuth_code($authCode);
  85. $input->SetBody($subject);
  86. $input->SetTotal_fee($totalFee * 100);
  87. $input->SetOut_trade_no($orderSn);
  88. //获取微信商户号等信息
  89. $sjExtend = WxOpenClass::getWxInfo();
  90. $microPay = new \MicroPay();
  91. $res = $microPay->pay($input, $sjExtend);
  92. if (isset($res["return_code"]) && $res["return_code"] == "SUCCESS" && isset($res["result_code"]) && $res["result_code"] == 'SUCCESS') {
  93. $transactionId = $res['transaction_id'] ?? '';
  94. $openId = $res['openid'] ?? '';
  95. $aliUserId = '';
  96. $cg->onlinePay = dict::getDict('onlinePay', 'yes');
  97. $cg->codePay = 1;
  98. $cg->payOpenId = $openId;
  99. $cg->aliUserId = $aliUserId;
  100. //自取订单
  101. $cg->getType = PurchaseClass::GET_TYPE_SELF_GET;
  102. $cg->save();
  103. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  104. $order->codePay = 1;
  105. //自取订单
  106. $order->sendType = OrderClass::SEND_TYPE_NO;
  107. $order->save();
  108. $attach = '';
  109. payUtil::thirdPay($wxPayWay, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  110. util::success(['returnStatus' => 'SUCCESS']);
  111. } else {
  112. Yii::info(json_encode($res));
  113. $errCode = $res['err_code'] ?? '';
  114. $msg = '';
  115. if ($errCode == 'NOTENOUGH') {
  116. $msg = '余额不足';
  117. }
  118. if ($errCode == 'USERPAYING') {
  119. $msg = '等待客户输入支付密码';
  120. }
  121. util::success(['returnStatus' => 'FAILURE'], $msg);
  122. }
  123. } else {
  124. $aliPayWay = dict::getDict('payWay', 'alipay');
  125. $order->payWay = $aliPayWay;
  126. $order->save();
  127. $cg->payWay = $aliPayWay;
  128. $cg->save();
  129. $aliF2F = Yii::getAlias("@vendor/alipayF2F");
  130. require_once($aliF2F . '/f2fpay/model/builder/AlipayTradePayContentBuilder.php');
  131. require_once($aliF2F . '/f2fpay/service/AlipayTradeService.php');
  132. $aliPId = '2017041906821571';
  133. $aliKey = 'MIIEpAIBAAKCAQEAvbeu6o90L+0AilI+mbhuJJH0lUv7hWQCEC+XUc+cWlC9ulKC3cSVScVLJHpUc09aj6v/iD1p9iVfgMxjeADNVKiQC2RJyRshAjzyTq+2bTcODp619iV2y4qW8UM65VcP7Ide3P0uT5xC2ReW0HpkdHZgm4F+P7mh1VhGt9qOP3hjvoraAHhtGACvsGvy8H69HhSAG+CEmFt7f2tKNWJ8xEUvkfhDvys93PfTk4xMWj048hJE2r38+2mWI/Il5dFQHWXXTVl2x9yi7uhEEW42a+7s9Q3HgqEvZiQ2NI1FTeEAPLFBApiEsNLY/smaszwqqfWGAyTMvtQ6T4K96GcTLQIDAQABAoIBAHwYTj33n9RJfnT73x7F2KXrIsUVcmyKQh88QgqtdmRNNA1QM3HESLJ8bu5pZhwW5/HaW8dOBKWRRKsHBnlUbPrXV4FcFDeLm0fPfd+iZ/2AaZ1+ix962f3BpYIiq7+f9zaMRazfnw9L8x31pByyMktLs12EkoQ0dHsMxxUzzKAOiiPnvCn8Pv+Jb2qej8GXgCjefutCVNMWGsdwJtMVXEbpdmMa48Wvw+0In5ZS/UG39YAreFzgDqI9jWHE1ZhkGmB1+8hKpeIlEeVGAeYVveUgssMORdA/YY8SWHk26KSIFXBrmdKjAcRJ8Q7ZHUmzIqAV+IMV+RD4J5mZHeJgdAECgYEA8J+Hp1M6eYbT4CPLXa//yRP6Xo+qSzrKHaRB1LRAjYhvKpx/TQetYpNCJ5bWpa+Jp0T5R21pzuYaJkPuGlNEHA13b5T3r1l2ltomSEdaShvD5EZ9WtErYV5zpSv7FjjIGkbwa0H3A8Ydnvw5z4A9TZjjHLjC2GtVGJReqHGglMECgYEAydddA4NRPxmXvIjjmLb1Ft1qwHuyv3vvWhi50foGZXNEnBcfP/OkfyBDDpOEu34GZBMXK9ykHBs1l93OEFGXh7AwW0Lp5lARahBEfBZgPjq5yPO8TOJZrb5hVcuvoDdGjxpRh93XDnQDhWS/1IvUcBLcIsTcnVvfrkX4NLxF/W0CgYEAxamG+gD4rBQBwMImsRN+/2MV7M//iEUG+0qPeXeI/7rv9wUP3etMlwl48qSKNxj37xxN2ksa/Acxu/VZhu6XqKO3VUX+IWFQdaNGh2F13iLozIDLQOtKw3WfcjOq0xpZ5pwXq0RI8iSw+IUhyD8EHNZW2qU8CiRBhyt6hsywqQECgYBa8+06FAachI/XqWfF/UvcDdJ5AkS9/L8SvmmdsSkItjSIkfLHAqdxkbwl6Vu6kUOX/PJIFZjuAWTZFl4xBFNgFYj01uZHnnT6cnIp6HteD2CAqTSFAMqgfFWoL6zoaYAmJBnxO4oZPTYI+ilnQcts5VLFaChx0GCvS2BZgy2W0QKBgQDjP2VtRq4aVSLUq2z1KIDI7GJBbOM5KSW1OEj4sfEdViozPh3Ar/FQWiij1oCZF+iJdKkonHoDbDd+Q0ykcpQ+5Gv07iiT8wJYFR/0j8g2kfql7bVQhGSBeBMS5sawKR3CvkfW73WX+CNnf0PklTY0kTyt6WRXDnKSeyxFVwSZ7g==';
  134. $aliPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsz3m9juAR1xew4DY6c34gvbwNg8pZ92f932tseKs+4+pF0e+jTDiUo/xHImNDi1KXt1B+s3LxY9L/sxEksbavwmhgbz/igN1cAEwS2YM+Gnf0csDrxAPJhoKL5FTwxPEQ/8VSgroU+6GlF3LAx4VHa1qfn5MqRPfLroJcyPDyGfNe9vna2FnO4E/PH+hVbvPUAwX3XrUvJIm4OgY0JE3HYFlu+O7F4Ln6+Sl+Zv/ZE2nZAvNiyAwW5iVKhKXLieExqwd0NdrP28baBqkkIY+tmV7butGjB52iK1UbU0+1uiaPL4xBxRy6d0LZmYlvdVHp0JRUuwxBLChGgOCo/76DQIDAQAB';
  135. $config = array(
  136. //签名方式,默认为RSA2(RSA2048)
  137. 'sign_type' => "RSA2",
  138. //支付宝公钥
  139. 'alipay_public_key' => $aliPublicKey,
  140. //商户私钥
  141. 'merchant_private_key' => $aliKey,
  142. //编码格式
  143. 'charset' => "UTF-8",
  144. //支付宝网关
  145. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  146. //应用ID
  147. 'app_id' => $aliPId,
  148. //异步通知地址,只有扫码支付预下单可用
  149. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  150. //最大查询重试次数
  151. 'MaxQueryRetry' => "10",
  152. //查询间隔
  153. 'QueryDuration' => "3"
  154. );
  155. // 支付超时,线下扫码交易定义为5分钟
  156. $timeExpress = "5m";
  157. // 创建请求builder,设置请求参数
  158. $barPayRequestBuilder = new \AlipayTradePayContentBuilder();
  159. $barPayRequestBuilder->setOutTradeNo($outTradeNo);
  160. $barPayRequestBuilder->setTotalAmount($totalAmount);
  161. $barPayRequestBuilder->setAuthCode($authCode);
  162. $barPayRequestBuilder->setTimeExpress($timeExpress);
  163. $barPayRequestBuilder->setSubject($subject);
  164. $barPayRequestBuilder->setBody($body);
  165. // 调用barPay方法获取当面付应答
  166. $barPay = new \AlipayTradeService($config);
  167. $barPayResult = $barPay->barPay($barPayRequestBuilder);
  168. if ($barPayResult->getTradeStatus() == 'SUCCESS') {
  169. $respond = $barPayResult->getResponse();
  170. $openId = '';
  171. $aliUserId = $respond->buyer_user_id ?? '';
  172. $transactionId = $respond->trade_no ?? '';
  173. $cg->onlinePay = dict::getDict('onlinePay', 'yes');
  174. $cg->codePay = 1;
  175. $cg->payOpenId = $openId;
  176. $cg->aliUserId = $aliUserId;
  177. //自取订单
  178. $cg->getType = PurchaseClass::GET_TYPE_SELF_GET;
  179. $cg->save();
  180. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  181. $order->codePay = 1;
  182. //自取订单
  183. $order->sendType = OrderClass::SEND_TYPE_NO;
  184. $order->save();
  185. $attach = '';
  186. payUtil::thirdPay($aliPayWay, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  187. util::success(['returnStatus' => 'SUCCESS']);
  188. }
  189. util::success(['returnStatus' => 'FAILURE']);
  190. }
  191. */
  192. }
  193. //开单操作 ssh 20220316
  194. public function actionCreateOrder()
  195. {
  196. $post = Yii::$app->request->post();
  197. $post['sjId'] = $this->sjId;
  198. $post['shopId'] = $this->shopId;
  199. $post['payWay'] = $this->isWx == true ? 0 : 1;
  200. $post['mainId'] = $this->mainId ?? 0;
  201. $now = time();
  202. //订单30分钟后过期
  203. $expireTime = $now + 1800;
  204. $post['deadline'] = $expireTime;
  205. //商城
  206. $post['fromType'] = 1;
  207. //客户
  208. $customId = $post['customId'] ?? 0;
  209. if (empty($customId)) {
  210. $customId = isset($this->shop->skCustomId) ? $this->shop->skCustomId : 0;
  211. }
  212. if (empty($customId)) {
  213. util::fail('没有找到客户');
  214. }
  215. $custom = CustomClass::getById($customId);
  216. if (empty($custom)) {
  217. util::fail('没有找到客户哦');
  218. }
  219. $post['customId'] = $customId;
  220. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  221. $productJson = $post['product'] ?? '';
  222. if (empty($productJson)) {
  223. util::fail('请选择商品');
  224. }
  225. $productList = json_decode($productJson, true);
  226. if (empty($productList)) {
  227. util::fail('请选择商品');
  228. }
  229. $connection = Yii::$app->db;//事务处理
  230. $transaction = $connection->beginTransaction();
  231. try {
  232. $post['product'] = $productList;
  233. $post['deadline'] = date("Y-m-d H:i:s", strtotime('+360 day'));
  234. $return = OrderService::createFinishOrder($post, $custom, $hasPay);
  235. $transaction->commit();
  236. util::success($return);
  237. } catch (\Exception $e) {
  238. $transaction->rollBack();
  239. Yii::error("下单失败原因:" . $e->getMessage());
  240. util::fail('下单失败');
  241. }
  242. }
  243. //下单要用到的相关信息 ssh 2019.12.6
  244. public function actionOrderRelate()
  245. {
  246. $regionTree = RegionService::tree();
  247. $shop = $this->shop->attributes;
  248. $freight = MerchantExtendService::getFreight($this->sjExtend);
  249. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  250. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'txMapKey' => $mapKey, 'merchant' => $shop];
  251. util::success($out);
  252. }
  253. //余额支付 ssh 2019.12.6
  254. public function actionBalancePay()
  255. {
  256. $post = Yii::$app->request->post();
  257. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  258. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  259. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  260. //验证优惠券是否还有效
  261. if (!empty($couponId)) {
  262. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  263. }
  264. $order = OrderService::getByOrderSn($orderSn);
  265. $userId = $this->adminId;
  266. $user = UserService::getUserInfo($userId);
  267. //验证支付密码是否正确
  268. UserService::validPayPassword($payPassword, $user);
  269. //支付前验证订单有效性
  270. OrderService::checkBeforePay($order, $this->adminId);
  271. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  272. $totalFee = $order['prePrice'];
  273. $sourceType = 0;
  274. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  275. $actPrice = $discountData['price'];
  276. $callbackParams = [];
  277. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  278. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  279. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  280. }
  281. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  282. public function actionWxPay()
  283. {
  284. ini_set('date.timezone', 'Asia/Shanghai');
  285. $post = Yii::$app->request->post();
  286. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  287. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  288. $order = OrderService::getByOrderSn($orderSn);
  289. $orderId = $order['id'];
  290. //验证优惠券是否还有效
  291. if (!empty($couponId)) {
  292. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  293. }
  294. //支付前验证订单有效性
  295. OrderService::checkBeforePay($order, $this->adminId);
  296. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  297. $totalFee = $order['realPrice'];
  298. //小程序使用miniOpenId
  299. if (httpUtil::isMiniProgram()) {
  300. $openId = $this->user['miniOpenId'];
  301. } else {
  302. $openId = $this->user['openId'];
  303. }
  304. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  305. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  306. $wxPayType = 0;
  307. if (httpUtil::isMiniProgram()) {
  308. $wxPayType = 1;
  309. }
  310. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  311. //订单30分钟后过期
  312. $now = time();
  313. $expireTime = $now + 1800;
  314. $wx = Yii::getAlias("@vendor/weixin");
  315. require_once($wx . '/lib/WxPay.Api.php');
  316. require_once($wx . '/example/WxPay.JsApiPay.php');
  317. $input = new \WxPayUnifiedOrder();
  318. $input->SetBody($name);
  319. $input->SetOut_trade_no($orderSn);
  320. $input->SetTotal_fee($totalFee * 100);
  321. $input->SetTime_start(date("YmdHis", $now));
  322. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  323. $input->SetTime_expire(date("YmdHis", $expireTime));
  324. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  325. $input->SetTrade_type("JSAPI");
  326. //花卉宝代为申请的微信支付
  327. $merchantExtend = $this->sjExtend->attributes;
  328. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  329. $input->SetSub_openid($openId);
  330. } else {
  331. $input->SetOpenid($openId);
  332. }
  333. //小程序使用miniAppId
  334. if (httpUtil::isMiniProgram()) {
  335. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  336. }
  337. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  338. $tools = new \JsApiPay();
  339. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  340. $newParams = json_decode($jsApiParameters, true);
  341. //已请求微信不能修改价格
  342. $updateData = [];
  343. $updateData['modPrice'] = 0;
  344. if (empty($order['deadline'])) {
  345. $updateData['deadline'] = $expireTime;
  346. }
  347. OrderService::updateById($orderId, $updateData);
  348. util::success($newParams);
  349. }
  350. //快捷付款订单
  351. public function actionFastPay()
  352. {
  353. ini_set('date.timezone', 'Asia/Shanghai');
  354. $post = Yii::$app->request->post();
  355. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  356. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  357. //验证门店是否有效
  358. $shopInfo = ShopService::getById($shopId);
  359. ShopService::valid($shopInfo, $this->sjId);
  360. $post['shopId'] = $shopId;
  361. //默认门店订单
  362. $store = isset($post['store']) ? $post['store'] : 1;
  363. $post['store'] = $store;
  364. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  365. $sourceType = $this->isWx ? 0 : 1;
  366. if (httpUtil::isMiniProgram()) {
  367. $sourceType = 2;
  368. }
  369. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  370. //兼容旧系统sourceType=3表示朋友圈来源
  371. $fromType = $sourceType == 3 ? 2 : 0;
  372. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  373. $post['userId'] = $this->adminId;
  374. $custom = $this->custom;
  375. $post['bookName'] = $custom['userName'] ?? '';
  376. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  377. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  378. $post['bookMobile'] = $bookMobile;
  379. $prePrice = round($post['prePrice'], 2);
  380. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  381. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  382. $actPrice = $discountData['price'];
  383. $post['discountType'] = $discountData['discountType'];
  384. $post['discountAmount'] = $discountData['discountAmount'];
  385. $post['actPrice'] = $actPrice;
  386. $post['realPrice'] = $actPrice;
  387. $post['payStyle'] = 0;
  388. $post['sjId'] = $this->sjId;
  389. $now = time();
  390. $expireTime = $now + 300;//订单5分钟后过期
  391. $post['createTime'] = date("Y-m-d H:i:s", $now);
  392. $post['deadline'] = $expireTime;
  393. if ($actPrice <= 0) {
  394. util::fail('请填写正确的金额');
  395. }
  396. //微信支付订单提交不能修改价格
  397. $post['modPrice'] = $this->isWx ? 0 : 1;
  398. $post['sourceType'] = $sourceType;
  399. $post['goodsNum'] = 1;
  400. $post['fromType'] = $fromType;
  401. $order = OrderService::addOrder($post);
  402. $orderId = $order['id'];
  403. $orderSn = $order['orderSn'];
  404. $sjId = $this->sjId;
  405. if ($payWay == 0) {
  406. $orderId = $order['id'];
  407. $name = '购买商品';
  408. $totalFee = $actPrice;
  409. $user = UserService::getById($this->adminId);
  410. $openId = isset($user['openId']) ? $user['openId'] : 0;
  411. if (httpUtil::isMiniProgram()) {
  412. //小程序使用miniOpenId
  413. $openId = $user['miniOpenId'];
  414. }
  415. if (empty($openId)) {
  416. util::fail('没有找到客户的openId');
  417. }
  418. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  419. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  420. $wxPayType = 0;
  421. if (httpUtil::isMiniProgram()) {
  422. $wxPayType = 1;
  423. }
  424. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  425. $wx = Yii::getAlias("@vendor/weixin");
  426. require_once($wx . '/lib/WxPay.Api.php');
  427. require_once($wx . '/example/WxPay.JsApiPay.php');
  428. $input = new \WxPayUnifiedOrder();
  429. $input->SetBody($name);
  430. $input->SetOut_trade_no($orderSn);
  431. $input->SetTotal_fee($totalFee * 100);
  432. $input->SetTime_start(date("YmdHis", $now));
  433. $input->SetAttach($attach);
  434. //设置订单有效期5分钟
  435. $input->SetTime_expire(date("YmdHis", $expireTime));
  436. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  437. $input->SetTrade_type("JSAPI");
  438. //花卉宝代为申请的微信支付
  439. $merchantExtend = $this->sjExtend->attributes;
  440. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  441. $input->SetSub_openid($openId);
  442. } else {
  443. $input->SetOpenid($openId);
  444. }
  445. //小程序使用miniAppId
  446. if (httpUtil::isMiniProgram()) {
  447. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  448. }
  449. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  450. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  451. $tools = new \JsApiPay();
  452. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  453. $newParams = json_decode($jsApiParameters, true);
  454. $newParams['orderId'] = $orderId;
  455. util::success($newParams);
  456. } elseif ($payWay == 1) {
  457. $extend = MerchantExtendService::getBySjId($sjId);
  458. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  459. util::fail('支付宝付款即将开通...');
  460. }
  461. $config = [
  462. //应用ID,您的APPID。
  463. 'app_id' => $extend['alipayPId'],
  464. //商户私钥,您的原始格式RSA私钥
  465. 'merchant_private_key' => $extend['alipayKey'],
  466. //异步通知地址
  467. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  468. //同步跳转
  469. 'return_url' => "",
  470. //编码格式
  471. 'charset' => "UTF-8",
  472. //签名方式
  473. 'sign_type' => "RSA2",
  474. //支付宝网关
  475. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  476. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  477. 'alipay_public_key' => $extend['alipayPublicKey'],
  478. ];
  479. Yii::info(json_encode($config) . ' aplipay config');
  480. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  481. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  482. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  483. $totalFee = $order['realPrice'];
  484. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  485. $subject = '购买商品';//订单名称,必填
  486. $total_amount = $totalFee;//付款金额,必填
  487. $body = '';//商品描述,可空
  488. $timeout_express = "1m";//超时时间
  489. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  490. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  491. $passBackParams = urlencode($passBackParams);
  492. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  493. $payRequestBuilder->setBody($body);
  494. $payRequestBuilder->setSubject($subject);
  495. $payRequestBuilder->setOutTradeNo($out_trade_no);
  496. $payRequestBuilder->setTotalAmount($total_amount);
  497. $payRequestBuilder->setTimeExpress($timeout_express);
  498. //在异步通知时将该参数原样返回
  499. $payRequestBuilder->setPassbackParams($passBackParams);
  500. //同步通知
  501. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  502. //异步通知
  503. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  504. $payResponse = new \AlipayTradeService($config);
  505. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  506. //直接将支付宝的html返回给前端
  507. echo $result;
  508. } elseif ($payWay == 2) {
  509. //余额支付,验证支付密码是否正确
  510. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  511. $user = UserService::getUserInfo($this->adminId);
  512. UserService::validPayPassword($payPassword, $user);
  513. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  514. $callbackParams = [];
  515. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  516. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  517. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'orderSn' => $orderSn, 'orderId' => $orderId, 'balance' => $balance]);
  518. } else {
  519. util::fail('无效的支付方式');
  520. }
  521. }
  522. //订单评价
  523. public function actionComment()
  524. {
  525. $post = Yii::$app->request->post();
  526. $id = $post['id'];
  527. $order = OrderService::getById($id);
  528. OrderService::valid($order, $this->shopId);
  529. if ($order['grade'] > 0) {
  530. util::fail('您已经评过了');
  531. }
  532. OrderService::comment($post);
  533. util::complete('提交成功');
  534. }
  535. //订单详情 ssh 2019.12.16
  536. public function actionDetail()
  537. {
  538. $id = Yii::$app->request->get('id', 0);
  539. $orderSn = Yii::$app->request->get('orderSn', '');
  540. $detail = [];
  541. if (!empty($id)) {
  542. $detail = OrderService::getOrderById($id);
  543. }
  544. if (!empty($orderSn)) {
  545. $detail = OrderService::getOrderBySn($orderSn);
  546. }
  547. OrderService::valid($detail, $this->shopId);
  548. //因前端未修改,这里先做一下兼容,好像打印时要调用到
  549. $detail['receiveProvince'] = $detail['province'] ?? '';
  550. $detail['receiveCity'] = $detail['city'] ?? '';
  551. $detail['receiveAddress'] = $detail['address'] ?? '';
  552. $detail['receiveFloor'] = $detail['floor'] ?? '';
  553. util::success($detail);
  554. }
  555. public function actionList()
  556. {
  557. $get = Yii::$app->request->get();
  558. $search = isset($get['search']) ? $get['search'] : '';
  559. $shopId = $this->shopId ?? 0;
  560. if (empty($shopId)) {
  561. //没有登录不显示数据
  562. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  563. }
  564. $where = [];
  565. $where['shopId'] = $shopId;
  566. $status = $get['status'] ?? 0;
  567. if (!empty($status)) {
  568. $where['status'] = $get['status'];
  569. }
  570. if (!empty($search)) {
  571. if (stringUtil::isMobile($search)) {
  572. $where['bookMobile'] = $search;
  573. } else {
  574. $where['orderSn'] = $search;
  575. }
  576. }
  577. $searchTime = $get['searchTime'] ?? '';
  578. if (!empty($searchTime)) {
  579. $startTime = $get['startTime'] ?? '';
  580. $endTime = $get['endTime'] ?? '';
  581. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  582. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  583. }
  584. $list = OrderService::getOrderList($where);
  585. $list['shop'] = $this->shop->attributes ?? [];
  586. util::success($list);
  587. }
  588. //订单归类 ssh 2019.12.17
  589. public function actionClassify()
  590. {
  591. $post = Yii::$app->request->post();
  592. $id = isset($post['id']) ? $post['id'] : 0;
  593. $order = OrderService::getById($id);
  594. OrderService::valid($order, $this->shopId);
  595. $categoryId = isset($post['categoryId']) ? $post['categoryId'] : $post['categoryId'];
  596. $usageId = isset($post['usageId']) ? $post['usageId'] : $post['usageId'];
  597. OrderService::classify($id, $categoryId, $usageId);
  598. util::complete();
  599. }
  600. //更新配送单 ssh 2019.12.17
  601. public function actionUpdateSheet()
  602. {
  603. $post = Yii::$app->request->post();
  604. $id = isset($post['id']) ? $post['id'] : 0;
  605. unset($post['id']);
  606. $order = OrderService::getById($id);
  607. OrderService::valid($order, $this->shopId);
  608. OrderService::updateSheet($order, $post);
  609. util::complete('提交成功');
  610. }
  611. //商家收款与发货 ssh 2019.12.18
  612. public function actionGathering()
  613. {
  614. $post = Yii::$app->request->post();
  615. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  616. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  617. $userId = isset($post['userId']) ? $post['userId'] : 0;
  618. $userInfo = UserService::getById($userId);
  619. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  620. util::fail('您选择的客户无效');
  621. }
  622. if ($price <= 0) {
  623. util::fail('请输入金额');
  624. }
  625. $post['prePrice'] = $price;
  626. $post['actPrice'] = $price;
  627. $post['payWay'] = $payWay;
  628. $post['sourceType'] = 1;
  629. $post['userId'] = $userId;
  630. $post['goodsNum'] = 1;
  631. $post['orderName'] = '商品';
  632. $shopId = MerchantService::getDefaultShopId($this->sj);
  633. $post['shopId'] = $shopId;
  634. $order = OrderService::addOrder($post);
  635. $id = $order['id'];
  636. $orderSn = $order['orderSn'];
  637. //流水类型列表
  638. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  639. $callbackParams = [];
  640. switch ($payWay) {
  641. case 0:
  642. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  643. break;
  644. case 1:
  645. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  646. break;
  647. case 2:
  648. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  649. break;
  650. default:
  651. util::fail('无效支付方式');
  652. }
  653. util::success($order);
  654. }
  655. //免发货管理 ssh 2020.1.6
  656. public function actionWithoutSend()
  657. {
  658. $id = Yii::$app->request->get('id');
  659. $order = OrderService::getById($id);
  660. OrderService::valid($order, $this->shopId);
  661. //配送流程变更
  662. $currentFlow = OrderSendClass::withoutSend($order);
  663. util::success(['currentFlow' => $currentFlow]);
  664. }
  665. //修改价格 ssh 2020.1.6
  666. public function actionUpdatePrice()
  667. {
  668. $id = Yii::$app->request->get('id');
  669. $price = Yii::$app->request->get('price', 1);
  670. $order = OrderService::getById($id);
  671. OrderService::valid($order, $this->shopId);
  672. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  673. util::fail('已发起支付,不能修改价格');
  674. }
  675. OrderService::updateById($id, ['actPrice' => $price]);
  676. util::complete('修改成功');
  677. }
  678. //配送单 ssh 2020.2.29
  679. public function actionGetDeliverDetail()
  680. {
  681. $id = Yii::$app->request->get('id', 0);
  682. $order = OrderService::getById($id);
  683. OrderService::valid($order, $this->shopId);
  684. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  685. $reachPeriodId = $order['reachPeriod'];
  686. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  687. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  688. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  689. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  690. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  691. $bookName = '--';
  692. $bookMobile = '--';
  693. }
  694. $data = [
  695. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  696. 'orderSn' => $order['orderSn'],
  697. 'receiveUserName' => $order['receiveUserName'],
  698. 'receiveMobile' => $order['receiveMobile'],
  699. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  700. 'cardInfo' => $order['cardInfo'],
  701. 'bookMobile' => $bookMobile,
  702. 'bookName' => $bookName,
  703. 'remark' => $order['remark'],
  704. 'sendNum' => $order['sendNum'],
  705. 'telephone' => 18030142050,
  706. 'printTime' => '',
  707. 'img' => '',
  708. ];
  709. util::success($data);
  710. }
  711. //运费计算 lqh 2021.4.12 暂反回固定
  712. public function actionFreight()
  713. {
  714. util::success(['sedCost' => 10]);
  715. }
  716. }