OrderController.php 32 KB

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