ShopController.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/2/24
  6. * Time: 下午12:48
  7. */
  8. namespace frontendApi\modules\v1\controllers;
  9. use common\helpers\Alarm;
  10. use common\helpers\Cache;
  11. use common\helpers\Date;
  12. use common\helpers\DingTalk;
  13. use common\helpers\Form;
  14. use common\helpers\LoggerTool;
  15. use common\helpers\Logistics;
  16. use common\helpers\Tool;
  17. use common\helpers\user\Info;
  18. use common\models\ApproachOrder;
  19. use common\models\ApproachOrderGoods;
  20. use common\models\DecOrder;
  21. use common\models\forms\ApproachOrderForm;
  22. use common\models\forms\DeclarationForm;
  23. use common\models\forms\OrderForm;
  24. use common\models\Order;
  25. use common\models\OrderGoods;
  26. use common\models\ReceiveAddress;
  27. use common\models\Region;
  28. use common\models\ShopGoods;
  29. use common\models\User;
  30. use common\models\UserBonus;
  31. use common\models\UserWallet;
  32. use Exception;
  33. use Yii;
  34. use yii\data\Pagination;
  35. use yii\db\Query;
  36. use yii\web\HttpException;
  37. class ShopController extends BaseController {
  38. public $modelClass = DecOrder::class;
  39. const TRANSACTION_TYPE_PAYMENT = 'payment';
  40. /**
  41. * 商品列表
  42. * @return mixed
  43. * @throws \yii\web\HttpException
  44. */
  45. public function actionIndex() {
  46. $condition = ' AND STATUS=1 AND (FIND_IN_SET(2,GIFT_TYPE)>0';
  47. // $isStudio = User::getEnCodeInfo(\Yii::$app->user->id)['IS_STUDIO'];
  48. // if($isStudio==1){
  49. // $condition.= " OR FIND_IN_SET(4,GIFT_TYPE)>0";
  50. // }
  51. $condition.=")";
  52. $data = ShopGoods::lists($condition, [], [
  53. 'orderBy' => 'SORT ASC,CREATED_AT DESC',
  54. 'from' => ShopGoods::tableName(),
  55. ]);
  56. foreach ($data['list'] as $key => $value) {
  57. $data['list'][$key]['DISCOUNT'] = $value['SELL_DISCOUNT']*100;
  58. $data['list'][$key]['CATE'] = ShopGoods::GOODS_TYPE[$value['CATE_ID']]['name'] ?? '';
  59. }
  60. return static::notice($data);
  61. }
  62. /**
  63. * 获取商品详情
  64. * @return mixed
  65. * @throws \yii\web\HttpException
  66. */
  67. public function actionGoodsDetail(){
  68. $id = \Yii::$app->request->get('id');
  69. $data = null;
  70. if($id){
  71. $data = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=>$id]);
  72. }
  73. return static::notice($data);
  74. }
  75. /**
  76. * 购物车订单展示
  77. * @throws \yii\web\HttpException
  78. */
  79. public function actionShowCart(){
  80. $userId = \Yii::$app->user->id;
  81. $payList = ShopGoods::payTypes();
  82. $allAddress = ReceiveAddress::findAllAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
  83. if($allAddress) {
  84. foreach ($allAddress as $key => $row) {
  85. $allAddress[$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
  86. $allAddress[$key]['CITY_NAME'] = Region::getCnName($row['CITY']);
  87. $allAddress[$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
  88. }
  89. }
  90. $userBalance = [
  91. 'points' => 0,
  92. 'cash' => 0,
  93. 'exchange' => 0
  94. ];
  95. if ($userBonusResult = UserBonus::findOneAsArray(['USER_ID' => $userId])) {
  96. $userBalance['points'] = $userBonusResult['RECONSUME_POINTS'];
  97. $userBalance['exchange'] = $userBonusResult['EXCHANGE_POINTS'];
  98. }
  99. if ($userCashResult = UserWallet::findOneAsArray(['USER_ID' => $userId])) {
  100. $userBalance['cash'] = $userCashResult['CASH'];
  101. }
  102. return static::notice(['payList'=>$payList,'allAddress'=>$allAddress,'userBalance'=>$userBalance]);
  103. }
  104. /**
  105. * 确认订单
  106. */
  107. public function actionSureOrder(){
  108. if (\Yii::$app->request->isPost) {
  109. $formModel = new OrderForm();
  110. $formModel->scenario = 'userOrder';
  111. $formModel->remark = '复销备注';
  112. $post = \Yii::$app->request->post();
  113. $post['type'] = DeclarationForm::TYPE_FX;
  114. if ($formModel->load($post, '') && $formModel->add()) {
  115. return static::notice('购物成功');
  116. } else {
  117. return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
  118. }
  119. }
  120. }
  121. /**
  122. * 订单支付成功
  123. * @throws \yii\web\HttpException
  124. */
  125. public function actionPaySuccess(){
  126. $orderSn = \Yii::$app->request->get('orderSn');
  127. $data = null;
  128. if($orderSn){
  129. $data = Order::findOneAsArray('SN=:SN', [':SN'=>$orderSn]);
  130. }
  131. return static::notice($data);
  132. }
  133. /**
  134. * 我的报单
  135. * @return mixed
  136. * @throws \yii\web\HttpException
  137. */
  138. public function actionDecOrderList() {
  139. $condition = ' AND USER_ID=:USER_ID AND IS_DEL=0';
  140. $params[':USER_ID'] = \Yii::$app->user->id;
  141. $data = DecOrder::lists($condition, $params, [
  142. 'select' => 'DO.*,U.USER_NAME USER_NAME,U.REAL_NAME REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME,OG.*',
  143. 'orderBy' => 'DO.CREATED_AT DESC',
  144. 'from' => DecOrder::tableName() . ' AS DO',
  145. 'join' => [
  146. ['LEFT JOIN', User::tableName() . ' AS U', 'DO.TO_USER_ID=U.ID'],
  147. ['LEFT JOIN', User::tableName() . ' AS RU', 'DO.REC_USER_ID=RU.ID'],
  148. ['LEFT JOIN', User::tableName() . ' AS CU', 'DO.CON_USER_ID=CU.ID'],
  149. ['LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=DO.ORDER_SN'],
  150. ],
  151. ]);
  152. return static::notice($data);
  153. }
  154. /**
  155. * 我的订单
  156. * @return mixed
  157. * @throws \yii\web\HttpException
  158. */
  159. public function actionOrderList() {
  160. $uname = Info::getUserNameByUserId(\Yii::$app->user->id);
  161. $condition = " AND IS_DELETE=0 AND ORDER_TYPE='FX' AND (USER_ID=:USER_ID OR CREATE_USER='$uname')";
  162. $params[':USER_ID'] = \Yii::$app->user->id;
  163. $data = Order::lists($condition, $params, [
  164. 'select' => 'O.*,U.REAL_NAME,OG.*',
  165. 'orderBy' => 'O.CREATED_AT DESC',
  166. 'from' => Order::tableName() . ' AS O',
  167. 'join' => [
  168. ['LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID'],
  169. ['LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN'],
  170. ],
  171. ]);
  172. foreach ($data['list'] as $key => $value) {
  173. if($value['ORDER_TYPE']=='ZC'){
  174. $data['list'][$key]['ORDER_TYPE'] = '首单';
  175. }else{
  176. // $data['list'][$key]['ORDER_TYPE'] = in_array($value['PAY_TYPE'], ['cash', 'paystack']) ? '复消': '积分';
  177. $data['list'][$key]['ORDER_TYPE'] = '复消';
  178. }
  179. //$data['list'][$key]['PROVINCE_NAME'] = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  180. //$data['list'][$key]['CITY_NAME'] = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  181. //$data['list'][$key]['COUNTY_NAME'] = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  182. $data['list'][$key]['PAY_AT'] = Date::convert($value['PAY_AT'],'Y-m-d H:i:s');
  183. // $data['list'][$key]['PAY_TYPE'] = $value['PAY_TYPE'] == 'cash' ? '消费点数' : ($value['PAY_TYPE'] == 'exchange' ? '兑换点数' : '复消点数');
  184. $data['list'][$key]['PAY_TYPE'] = ShopGoods::payTypes()[$value['PAY_TYPE']]['name'] ?? '';
  185. $data['list'][$key]['STATUS'] = \Yii::$app->params['orderStatus'][$value['STATUS']]['label'] ?? '';
  186. }
  187. return static::notice($data);
  188. }
  189. // /**
  190. // * 我的订单
  191. // * @return mixed
  192. // * @throws \yii\web\HttpException
  193. // */
  194. // public function actionOrderList() {
  195. // $uname = Info::getUserNameByUserId(\Yii::$app->user->id);
  196. // $condition = " O.IS_DELETE = 0 AND O.ORDER_TYPE='FX' AND (O.USER_ID=:USER_ID OR O.CREATE_USER='$uname')";
  197. // $params[':USER_ID'] = \Yii::$app->user->id;
  198. // $orderQuery = Order::find()
  199. // ->alias('O')
  200. // ->where($condition, $params)
  201. // ->select('O.*,U.REAL_NAME,OG.REAL_PRICE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV,OG.ORDER_SN,OG.GOODS_ID')
  202. // ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  203. // ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  204. // ->orderBy('O.CREATED_AT DESC');
  205. //
  206. // // 订单中间表只查询待支付和支付失败的订单
  207. // $params[':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  208. // $params[':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  209. // $orderStandardQuery = ApproachOrder::find()
  210. // ->alias('O')
  211. // ->where($condition . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $params)
  212. // ->select('O.*,U.REAL_NAME,OG.REAL_PRICE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV,OG.ORDER_SN,OG.GOODS_ID')
  213. // ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  214. // ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  215. // ->orderBy('O.CREATED_AT DESC');
  216. //
  217. // $queryAll = $orderQuery->union($orderStandardQuery, true);
  218. // $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  219. //
  220. // $totalCount = $query->count();
  221. // $pagination = new Pagination(['totalCount' => $totalCount, 'pageSize' => \Yii::$app->request->get('pageSize')]);
  222. // $lists = $query->offset($pagination->offset)->limit($pagination->limit)->all();
  223. //
  224. // $data = [
  225. // 'list' => $lists,
  226. // 'currentPage'=>$pagination->page,
  227. // 'totalPages'=>$pagination->pageCount,
  228. // 'startNum' => $pagination->page * $pagination->pageSize + 1,
  229. // 'totalCount' => $pagination->totalCount,
  230. // 'pageSize' => $pagination->pageSize,
  231. // ];
  232. //
  233. // foreach ($data['list'] as $key => $value) {
  234. // $data['list'][$key]['ORDER_TYPE'] = $value['ORDER_TYPE'] == 'ZC' ? '首单' : '复消';
  235. // $data['list'][$key]['PAY_AT'] = $value['PAY_AT'] ? Date::convert($value['PAY_AT'],'Y-m-d H:i:s') : '';
  236. // $data['list'][$key]['PAY_TYPE'] = ShopGoods::payTypes()[$value['PAY_TYPE']]['name'] ?? '';
  237. // $data['list'][$key]['STATUS'] = \Yii::$app->params['orderStatus'][$value['STATUS']]['label'] ?? '';
  238. // }
  239. //
  240. // return $data;
  241. // }
  242. /**
  243. * 会员复消
  244. */
  245. public function actionReconsume() {
  246. $isStudio = User::getEnCodeInfo(\Yii::$app->user->id)['IS_STUDIO'];
  247. $condition = " AND STATUS=1";
  248. if($isStudio==1){
  249. $condition .= " AND (FIND_IN_SET(4,GIFT_TYPE)>0)";
  250. }
  251. // $condition.= ")";
  252. $data = ShopGoods::lists($condition, [], [
  253. 'orderBy' => 'SORT ASC,CREATED_AT DESC',
  254. 'from' => ShopGoods::tableName(),
  255. ]);
  256. foreach ($data['list'] as $key => $value) {
  257. $data['list'][$key]['DISCOUNT'] = $value['SELL_DISCOUNT']*100;
  258. }
  259. return static::notice($data);
  260. }
  261. /**
  262. * 帮会员复消购物车
  263. * @throws \yii\web\HttpException
  264. */
  265. public function actionReconsumeCart(){
  266. $userId = \Yii::$app->user->id;
  267. $payList = ['cash'=>['name'=>'消费点数支付'],];
  268. $userBalance = [
  269. 'points' => 0,
  270. 'cash' => 0
  271. ];
  272. if ($userBonusResult = UserBonus::findOneAsArray(['USER_ID' => $userId])) {
  273. $userBalance['points'] = $userBonusResult['RECONSUME_POINTS'];
  274. }
  275. if ($userCashResult = UserWallet::findOneAsArray(['USER_ID' => $userId])) {
  276. $userBalance['cash'] = $userCashResult['CASH'];
  277. }
  278. return static::notice(['payList'=>$payList,'userBalance'=>$userBalance]);
  279. }
  280. /**
  281. * 帮会员复消确认订单
  282. */
  283. public function actionReconsumeSureOrder(){
  284. if (\Yii::$app->request->isPost) {
  285. $formModel = new OrderForm();
  286. $formModel->scenario = 'reconsumeOrder';
  287. $formModel->remark = '帮会员复销';
  288. $post = \Yii::$app->request->post();
  289. $post['type'] = DeclarationForm::TYPE_FX;
  290. if ($formModel->load($post, '') && $formModel->reconsumeAdd()) {
  291. return static::notice('帮会员复消成功');
  292. } else {
  293. return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
  294. }
  295. }
  296. return static::notice('无效请求');
  297. }
  298. /**
  299. * 确认订单
  300. */
  301. public function actionSureApproachOrder(){
  302. if (\Yii::$app->request->isPost) {
  303. $formModel = new ApproachOrderForm();
  304. $formModel->scenario = 'userOrder';
  305. $formModel->remark = '复销备注';
  306. $post = \Yii::$app->request->post();
  307. $post['type'] = DeclarationForm::TYPE_FX;
  308. if ($formModel->load($post, '') && $order = $formModel->add()) {
  309. return static::notice($order);
  310. } else {
  311. return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
  312. }
  313. }
  314. return static::notice('无效请求');
  315. }
  316. /**
  317. * iPay88支付成功的webhook.
  318. * @throws HttpException
  319. * @throws \Exception
  320. */
  321. public function actionVerifyApproachOrder() {
  322. // iPay88支付成功的webhook.
  323. $rawPostData = file_get_contents('php://input');
  324. LoggerTool::notice(['actionVerifyApproachOrder', $rawPostData]);
  325. $data = [];
  326. if (strlen($rawPostData) > 0) {
  327. $rawPostArray = explode('&', $rawPostData);
  328. foreach ($rawPostArray as $raw) {
  329. $raw = explode('=', $raw);
  330. if (count($raw) == 2)
  331. $data[$raw[0]] = urldecode($raw[1]);
  332. }
  333. }
  334. // 支付webhook回调日志
  335. //Tool::approachOrderCall($data);
  336. try {
  337. // 订单状态
  338. $orderStatus = ($data['Status'] == '1') ? \Yii::$app->params['orderStatus']['paid']['value'] : \Yii::$app->params['orderStatus']['failPaid']['value'];
  339. $oderSn = $data['RefNo'] ?? '';
  340. $formModel = new ApproachOrderForm();
  341. $formModel->scenario = 'verifyPay';
  342. $load = [
  343. 'sn' => $oderSn,
  344. 'scenario' => 'verifyPay',
  345. 'status' => $orderStatus,
  346. 'note' => [
  347. 'MerchantCode' => $data['MerchantCode'],
  348. 'PaymentId' => $data['PaymentId'],
  349. 'status' => $data['Status'],
  350. 'Signature' => $data['Signature'],
  351. 'Currency' => $data['Currency'],
  352. 'Amount' => $data['Amount'],
  353. 'TransId' => $data['TransId'],
  354. 'TranDate' => $data['TranDate'],
  355. 'BankMID' => $data['BankMID'],
  356. 'CCNo' => $data['CCNo'],
  357. ],
  358. ];
  359. if ($formModel->load($load, '') && $result = $formModel->verifyPayOnline()) {
  360. LoggerTool::info($result);
  361. echo 'RECEIVEOK';
  362. return http_response_code('RECEIVEOK');
  363. } else {
  364. echo 'RECEIVEOK';
  365. LoggerTool::error(Form::formatErrorsForApi($formModel->getErrors()));
  366. return http_response_code('RECEIVEOK');
  367. }
  368. } catch (\Exception $e) {
  369. echo 'RECEIVEOK';
  370. LoggerTool::error(sprintf('actionVerifyApproachOrderError: File[%s], Line:[%s], Message[%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
  371. return http_response_code('RECEIVEOK');
  372. }
  373. }
  374. public function actionReQueryPayment()
  375. {
  376. // 每天巡查一次,查询近24小时的未支付订单. 支付参数记录在NOTE字段中,如没有此数据,则不能进行查询.(待支付、支付方式online、当天订单、未删除)
  377. $orderList = ApproachOrder::find()
  378. ->where('STATUS=:STATUS AND PAY_TYPE=:PAY_TYPE AND CREATED_AT>=:CREATED_AT AND DELETED_AT=0',
  379. [':STATUS' => 0, ':PAY_TYPE' => 'online', ':CREATED_AT' => strtotime(date('Y-m-d', time()))])
  380. ->andWhere(['not', ['NOTE' => null]])
  381. ->asArray()
  382. ->all();
  383. if (!$orderList) {
  384. return static::notice('no record');
  385. }
  386. foreach ($orderList as $order) {
  387. $message = '';
  388. // 支付参数记录在NOTE字段中,如没有此数据,则不能进行查询
  389. $orderPayment = json_decode($order['NOTE'], true);
  390. $rawPostData = "MerchantCode={$orderPayment['MerchantCode']}&RefNo={$orderPayment['RefNo']}&Amount={$orderPayment['Amount']}";
  391. try {
  392. $ch = curl_init();
  393. $url = 'https://payment.ipay88.com.my/epayment/enquiry.asp' . '?' . $rawPostData;
  394. curl_setopt($ch, CURLOPT_URL, $url);
  395. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  396. $result = curl_exec($ch);
  397. switch ($result) {
  398. case '00': // Successful payment.
  399. $paymentParams = [
  400. 'RefNo' => $orderPayment['RefNo'],
  401. 'Amount' => $orderPayment['Amount'],
  402. 'PaymentId' => '182',
  403. 'ProdDesc' => 'Pay for sales',
  404. 'UserName' => 'MY32',
  405. 'SignatureType' => 'SHA256',
  406. 'UserEmail' => 'ek_dummy25@elken.com',
  407. 'UserContact' => '60172249692',
  408. ];
  409. $paymentFields = \Yii::$app->iPay88->getPaymentFields($paymentParams, self::TRANSACTION_TYPE_PAYMENT);
  410. $formModel = new ApproachOrderForm();
  411. $formModel->scenario = 'verifyPay';
  412. $load = [
  413. 'sn' => $orderPayment['RefNo'],
  414. 'scenario' => 'verifyPay',
  415. 'status' => \Yii::$app->params['orderStatus']['paid']['value'],
  416. 'note' => [
  417. 'MerchantCode' => $orderPayment['MerchantCode'],
  418. 'PaymentId' => $paymentFields['PaymentId'],
  419. 'status' => \Yii::$app->params['orderStatus']['paid']['value'],
  420. 'Signature' => $paymentFields['Signature'],
  421. 'Currency' => $paymentFields['Currency'],
  422. 'Amount' => $paymentFields['Amount'],
  423. 'TransId' => '',
  424. 'TranDate' => '',
  425. 'BankMID' => '',
  426. 'CCNo' => '',
  427. ],
  428. ];
  429. if ($formModel->load($load, '') && $result = $formModel->verifyPayOnline()) {
  430. LoggerTool::info($result);
  431. }
  432. $message = '(ReQueryIPay88Payment). orderSN{%s} 00: Successful payment';
  433. break;
  434. case 'Invalid parameters':
  435. ApproachOrder::updateAll(
  436. ['STATUS' => \Yii::$app->params['orderStatus']['failPaid']['value'], 'REMARK' => 'Invalid parameters: Parameters pass in incorrect'],
  437. 'SN=:SN', [':SN' => $order['SN']]
  438. );
  439. $message = '(ReQueryIPay88Payment). orderSN{%s} Invalid parameters: Parameters pass in incorrect';
  440. break;
  441. case 'Record not found':
  442. ApproachOrder::updateAll(
  443. ['STATUS' => \Yii::$app->params['orderStatus']['failPaid']['value'], 'REMARK' => 'Record not found: Cannot found the record'],
  444. 'SN=:SN', [':SN' => $order['SN']]
  445. );
  446. $message = '(ReQueryIPay88Payment). orderSN{%s} Record not found: Cannot found the record';
  447. break;
  448. case 'Incorrect amount':
  449. $message = '(ReQueryIPay88Payment). orderSN{%s} Incorrect amount: Amount different';
  450. ApproachOrder::updateAll(
  451. ['STATUS' => \Yii::$app->params['orderStatus']['failPaid']['value'], 'REMARK' => 'Incorrect amount: Amount different'],
  452. 'SN=:SN', [':SN' => $order['SN']]
  453. );
  454. break;
  455. case 'Payment fail':
  456. ApproachOrder::updateAll(
  457. ['STATUS' => \Yii::$app->params['orderStatus']['failPaid']['value'], 'REMARK' => 'Payment fail: Payment fail'],
  458. 'SN=:SN', [':SN' => $order['SN']]
  459. );
  460. $message = '(ReQueryIPay88Payment). orderSN{%s} Payment fail: Payment fail';
  461. break;
  462. case 'M88Admin':
  463. ApproachOrder::updateAll(
  464. ['STATUS' => \Yii::$app->params['orderStatus']['failPaid']['value'], 'REMARK' => 'M88Admin: Payment status updated by iPay88 Admin(Fail)'],
  465. 'SN=:SN', [':SN' => $order['SN']]
  466. );
  467. $message = '(ReQueryIPay88Payment). orderSN{%s} M88Admin: Payment status updated by iPay88 Admin(Fail)';
  468. break;
  469. default:
  470. }
  471. curl_close($ch);
  472. // 推送消息到预警平台
  473. Alarm::reportAlarm(['brand' => 'MSG', 'message' => sprintf($message, $orderPayment['RefNo'])]);
  474. } catch (exception $e) {
  475. curl_close($ch);
  476. LoggerTool::error('err. ' . $e->getMessage());
  477. Alarm::reportAlarm(['brand' => 'MSG', 'message' => sprintf('err. (ReQueryIPay88Payment). orderSN{%s}. %s', $orderPayment['RefNo'], $e->getMessage())]);
  478. }
  479. }
  480. return static::notice('');
  481. }
  482. /**
  483. * 删除准订单
  484. */
  485. public function actionDeleteApproachOrder()
  486. {
  487. $orderSn = \Yii::$app->request->post('orderSn');
  488. // 订单中间表更新订单状态为取消
  489. ApproachOrder::updateAll(
  490. [
  491. 'STATUS' => \Yii::$app->params['orderStatus']['cancel']['value'],
  492. 'DELETED_AT' => Date::nowTime(),
  493. 'REMARK' => 'Member cancel order',
  494. ],
  495. 'SN=:SN',
  496. [':SN' => $orderSn]);
  497. return static::notice('');
  498. }
  499. /**
  500. * iPay88支付
  501. * @return mixed
  502. * @throws HttpException
  503. */
  504. public function actionIPay88()
  505. {
  506. // 订单ID
  507. $paymentParams['RefNo'] = \Yii::$app->request->post('RefNo');
  508. // 订单
  509. $order = ApproachOrder::findOne(['SN' => $paymentParams['RefNo']]);
  510. if (!$order->toArray()) {
  511. return static::notice('订单编号无效');
  512. }
  513. // 转为分
  514. $money = $order['PAY_AMOUNT'];
  515. // 订单金额,元=>分
  516. // $money = \Yii::$app->request->post('Amount');
  517. // 马来币汇率
  518. $exchangeRateMYR = floatval(Cache::getSystemConfig()['exchangeRateMYR']['VALUE'] ?? 0);
  519. // 计算马来币
  520. $amount = number_format(round($money * $exchangeRateMYR), 2, '.', '');
  521. // $amount = number_format($money, 2, '.', '');
  522. // $amount = number_format(1, 2, '.', ''); // TODO: 测试
  523. $paymentParams['Amount'] = str_replace('.', '', $amount);
  524. // (Optional) (int)
  525. $paymentParams['PaymentId'] = '182'; // 2=信用卡 182=银联
  526. // Product description. (length 100)
  527. $paymentParams['ProdDesc'] = 'Pay for sales';
  528. // Customer name. (length 100)
  529. $paymentParams['UserName'] = 'MY32';
  530. $paymentParams['SignatureType'] = 'SHA256';
  531. // Customer email. (length 100)
  532. $paymentParams['UserEmail'] = 'ek_dummy25@elken.com';
  533. // Customer contact. (length 20)
  534. $paymentParams['UserContact'] = '60172249692';
  535. // (Optional) Merchant remarks. (length 100)
  536. //$paymentParams['Remark'] = 'Here is the description';
  537. //merchantkey + merchantcode+ reference Number + amount in cent + currency_code
  538. $paymentFields = \Yii::$app->iPay88->getPaymentFields($paymentParams, self::TRANSACTION_TYPE_PAYMENT);
  539. $transactionUrl = \Yii::$app->iPay88->getTransactionUrl(self::TRANSACTION_TYPE_PAYMENT);
  540. $paymentFields['Amount'] = $amount;
  541. $res = [
  542. 'paymentFields' => $paymentFields,
  543. 'transactionUrl' => $transactionUrl,
  544. ];
  545. // 支付信息写入note
  546. $order->NOTE = json_encode([
  547. 'MerchantCode' => $paymentFields['MerchantCode'],
  548. 'PaymentId' => $paymentFields['PaymentId'],
  549. 'RefNo' => $paymentFields['RefNo'],
  550. 'Amount' => $paymentFields['Amount'],
  551. 'Currency' => $paymentFields['Currency'],
  552. 'Signature' => $paymentFields['Signature'],
  553. ]);
  554. $order->update();
  555. return static::notice($res);
  556. }
  557. /**
  558. * 推送订单到wst仓储系统
  559. * @throws HttpException
  560. * @throws \Exception
  561. */
  562. public function actionLogistics()
  563. {
  564. $orderSn = \Yii::$app->request->get('sn');
  565. $order = Order::find()
  566. ->where('SN=:ORDER_SN', [':ORDER_SN' => $orderSn])
  567. ->asArray()
  568. ->one();
  569. if (!$order) {
  570. return static::notice('订单【' . $orderSn . '】不存在');
  571. }
  572. if ($order['SEND_AT'] > 0) {
  573. return static::notice('订单【' . $orderSn . '】不可重复推送');
  574. }
  575. $logistics = new Logistics();
  576. $response = $logistics->createOrder($order);
  577. LoggerTool::info(['actionLogistics', $response]);
  578. if ($response['success'] == 1) {
  579. // 更新db中订单推送成功状态
  580. if (Order::updateAll(['SEND_AT' => time()], 'SN=:SN', [':SN' => $orderSn])) {
  581. return static::notice($response);
  582. } else {
  583. return static::notice($orderSn . ' 推送wst系统成功, 更新状态失败');
  584. }
  585. }
  586. return static::notice($orderSn . ' 推送wst系统失败');
  587. }
  588. /**
  589. * @throws HttpException
  590. * @throws \Exception
  591. */
  592. public function actionLogisticsAuto()
  593. {
  594. $createdAtEnd = strtotime(date('Y-m-d')) - 1;
  595. // 早0点推送,前一天0-24点的订单
  596. $orderList = Order::find()
  597. ->where(
  598. '(CREATED_AT <= :CREATED_AT_END) AND STATUS=:STATUS AND SEND_AT=:SEND_AT AND PAY_TYPE=:PAY_TYPE AND IS_DELETE = 0',
  599. [
  600. ':CREATED_AT_END' => $createdAtEnd,
  601. ':STATUS' => \Yii::$app->params['orderStatus']['paid']['value'],
  602. ':SEND_AT' => 0,
  603. ':PAY_TYPE' => 'online',
  604. ]
  605. )
  606. ->asArray()
  607. ->all();
  608. if (!$orderList) {
  609. // 发送预警通知
  610. $alarm = [
  611. 'stance' => 2,
  612. 'brand' => 'MSG',
  613. 'message' => '跨境商品推送淘布斯系统终止,原因:无订单',
  614. ];
  615. Alarm::reportAlarm($alarm);
  616. return static::notice('推送wst系统终止,原因:无订单');
  617. }
  618. $orderSnSuccess = [];
  619. $orderSnFailed = [];
  620. $logistics = new Logistics();
  621. foreach ($orderList as $order) {
  622. // 发送wst仓库系统
  623. $response = $logistics->createOrder($order);
  624. LoggerTool::info($response);
  625. if ($response['success'] == 1) {
  626. // 写入mongo
  627. Tool::wstOrderCall($response['data']);
  628. $orderSnSuccess[] = $order['SN'];
  629. } else {
  630. // 记录推送结果
  631. $orderSnFailed[] = $order['SN'];
  632. // 发送预警通知
  633. $alarm = [
  634. 'stance' => 5,
  635. 'brand' => 'MSG',
  636. 'message' => sprintf('跨境商品推送淘布斯系统失败. 订单号[%s], error[%s]', $order['SN'], $response),
  637. ];
  638. Alarm::reportAlarm($alarm);
  639. }
  640. }
  641. $notify = '跨境商品推送淘布斯系统结束. ';
  642. // 更新db中订单推送成功状态
  643. if (count($orderSnSuccess) > 0) {
  644. $orderSnSuccessIds = implode("','", $orderSnSuccess);
  645. Order::updateAll(['SEND_AT' => time()], "SN IN ('" . $orderSnSuccessIds . "')");
  646. $notify .= sprintf('成功订单数{%d}, 订单号[%s];', count($orderSnSuccess), implode(', ', $orderSnSuccess));
  647. }
  648. if (count($orderSnFailed) > 0) {
  649. $notify .= sprintf('失败订单数{%d}, 订单号[%s]', count($orderSnFailed), implode(', ', $orderSnFailed));
  650. }
  651. // 发送预警通知
  652. $alarm = [
  653. 'stance' => 2,
  654. 'brand' => 'MSG',
  655. 'message' => $notify,
  656. ];
  657. Alarm::reportAlarm($alarm);
  658. return static::notice($notify);
  659. }
  660. }