OrderController.php 32 KB

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