OrderController.php 40 KB

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