RefillBase.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. namespace refill;
  3. require_once(BASE_HELPER_PATH . '/queue/rdispatcher.php');
  4. require_once(BASE_HELPER_PATH . '/mtopcard/mtopcard.php');
  5. require_once(BASE_HELPER_PATH . '/refill/IRefill.php');
  6. require_once(BASE_HELPER_PATH . '/refill/IRefillOil.php');
  7. require_once(BASE_HELPER_PATH . '/refill/IRefillPhone.php');
  8. require_once(BASE_HELPER_PATH . '/refill/IRefillCallBack.php');
  9. require_once(BASE_HELPER_PATH . '/refill/ProviderManager.php');
  10. require_once(BASE_HELPER_PATH . '/refill/CalcMerchantPrice.php');
  11. require_once(BASE_HELPER_PATH . '/refill/util.php');
  12. require_once(BASE_HELPER_PATH . '/refill/errcode.php');
  13. use Log;
  14. use mtopcard;
  15. use QueueClient;
  16. use member_info;
  17. use Exception;
  18. use trans_wapper;
  19. class RefillBase
  20. {
  21. protected $mPolicy;
  22. protected $mLimits = [];
  23. protected function __construct()
  24. {
  25. }
  26. public function allow($mchid,$card_type,$amount,$quality)
  27. {
  28. return $this->mPolicy->allow($mchid,$card_type,$amount,$quality);
  29. }
  30. public function goods()
  31. {
  32. return $this->mPolicy->goods();
  33. }
  34. public function load()
  35. {
  36. $this->mPolicy->load();
  37. }
  38. public function find_quality($mchid,$spec,$card_type,$org_quality,$times,$period): array {
  39. return $this->mPolicy->find_quality($mchid,$spec,$card_type,$org_quality,$times,$period);
  40. }
  41. public function notify($chname, $input)
  42. {
  43. $caller = $this->mPolicy->getCaller($chname);
  44. if($caller === false) {
  45. return false;
  46. }
  47. elseif ($caller->verify($input))
  48. {
  49. [$order_id, $success, $can_try, $need_handle] = $caller->notify($input);
  50. if (!$need_handle) {
  51. return true;
  52. }
  53. if ($order_id !== false) {
  54. return $this->proc_notify($order_id, $success, $can_try, $chname);
  55. } else {
  56. Log::record("系统无此订单ID:{$order_id}", Log::ERR);
  57. }
  58. }
  59. else {
  60. Log::record("{$chname} 签名失败.");
  61. }
  62. return true;
  63. }
  64. private function proc_notify($order_id,$success, $can_try,$chname)
  65. {
  66. $mod_order = Model('vr_order');
  67. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id]);
  68. $order_state = intval($order_info['order_state']);
  69. if ($order_state != ORDER_STATE_SEND) {
  70. return false;
  71. }
  72. $logic_vr_order = Logic("vr_order");
  73. $mod_refill = Model('refill_order');
  74. try
  75. {
  76. $tran = new trans_wapper($mod_order,'notify change order state trans');
  77. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id],'*',true,true);
  78. $order_state = intval($order_info['order_state']);
  79. if ($order_state != ORDER_STATE_SEND) {
  80. $tran->commit();
  81. return false;
  82. }
  83. $refill_info = $mod_refill->getOrderInfo(['order_id' => $order_id,'inner_status' => 0]);
  84. $quality = intval($refill_info['quality']);
  85. $card_type = intval($refill_info['card_type']);
  86. $spec = intval($refill_info['refill_amount']);
  87. if ($success) {
  88. util::incr_notify($chname, $card_type, $spec, $quality, true);
  89. $logic_vr_order->changeOrderStateSuccess($order_id);
  90. }
  91. elseif ($can_try)
  92. {
  93. if(!empty($refill_info))
  94. {
  95. util::incr_notify($chname, $card_type, $spec, $quality, false);
  96. util::decr_amount_lock($refill_info['mchiid'],$card_type,$refill_info['refill_amount']);
  97. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口回调通知失败,正在重试");
  98. [$can_retry,$params] = $this->retry($refill_info, $order_info);
  99. if ($can_retry)
  100. {
  101. $mod_refill->edit($order_id, ['is_retrying' => 1]);
  102. $tran->commit();
  103. // if(defined('USE_COROUTINE') && USE_COROUTINE) {
  104. // \Swoole\Coroutine::sleep(1);
  105. // }
  106. util::push_add($params);
  107. return true;
  108. }
  109. }
  110. }
  111. else {
  112. util::incr_notify($chname, $card_type, $spec, $quality, false);
  113. util::decr_amount_lock($refill_info['mchiid'],$card_type,$refill_info['refill_amount']);
  114. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口回调通知失败,不可重试.");
  115. }
  116. $tran->commit();
  117. }
  118. catch (Exception $ex) {
  119. $tran->rollback();
  120. Log::record("Error:" . $ex->getMessage(), Log::ERR);
  121. }
  122. $mod_refill->edit($order_id, ['notify_time' => time(), 'notify_state' => 1]);
  123. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id,'manual' => false]);
  124. return true;
  125. }
  126. private function retry(array $refill_info, array $order_info)
  127. {
  128. $mchid = intval($refill_info['mchid']);
  129. $spec = intval($refill_info['refill_amount']);
  130. $card_type = intval($refill_info['card_type']);
  131. $org_quality = intval($refill_info['org_quality']);
  132. $used_time = time() - intval($refill_info['order_time']);
  133. $commit_times = intval($refill_info['commit_times']);
  134. [$org_quality,$quality] = $this->find_quality($mchid,$spec,$card_type,$org_quality,$commit_times,$used_time);
  135. if($quality <= 0) return [false,null];
  136. $params = [ 'mchid' => $refill_info['mchid'],
  137. 'buyer_id' => $order_info['buyer_id'],
  138. 'amount' => $refill_info['refill_amount'],
  139. 'card_no' => $refill_info['card_no'],
  140. 'card_type' => $refill_info['card_type'],
  141. 'org_quality' => $org_quality,
  142. 'mch_order' => $refill_info['mch_order'],
  143. 'notify_url' => $refill_info['notify_url'],
  144. 'idcard' => $refill_info['idcard'] ?? '',
  145. 'card_name' => $refill_info['card_name'] ?? '',
  146. 'order_time' => $refill_info['order_time'],
  147. 'commit_times' => $refill_info['commit_times'] + 1,
  148. 'order_id' => $refill_info['order_id']
  149. ];
  150. return [true,$params];
  151. }
  152. public function zero_order($mchid, $buyer_id, $amount, $card_no,
  153. $mch_order, $idcard, $card_name, $notify_url,$quality,$org_quality,
  154. $order_time = 0, $commit_times = 0,$errmsg='')
  155. {
  156. $card_type = mtopcard\card_type($card_no);
  157. $minfo = new member_info($buyer_id);
  158. $calc = new ZeroMerchantPrice($mchid, $amount, $card_type,$quality);
  159. $mch_amount = $calc->calc_vgoods_price([]);
  160. $input['goods_id'] = ZERO_GOODS_ID;
  161. $input['quantity'] = 1; //数量
  162. $input['buyer_phone'] = $minfo->mobile();
  163. $input['buyer_name'] = $minfo->truename();
  164. $input['buyer_msg'] = $_POST['buyer_msg'] ?? '';
  165. $input['order_from'] = 1;
  166. $input['pd_pay'] = true;
  167. $logic_buy_virtual = Logic('buy_virtual');
  168. $result = $logic_buy_virtual->buyStep3($input, $buyer_id, [$calc, 'calc_vorder_amount'], true);
  169. $mod_refill = Model('refill_order');
  170. if ($result['state'] === true)
  171. {
  172. $order_sn = $result['data']['order_sn'];
  173. $order_id = $result['data']['order_id'];
  174. $logic_vr_order = Logic("vr_order");
  175. $order_info = Model('vr_order')->getOrderInfo(['order_id' => $order_id]);
  176. $logic_vr_order->changeOrderStateCancel($order_info, '', '无法下单创建0元订单');
  177. if (empty($mch_order)) {
  178. $mch_order = $order_sn;
  179. }
  180. //虚拟订单表信息扩展
  181. $orderext = ['order_id' => $order_id, 'order_sn' => $order_sn, 'mchid' => $mchid,
  182. 'refill_amount' => $amount, 'mch_order' => $mch_order,
  183. 'idcard' => $idcard, 'card_name' => $card_name,
  184. 'notify_url' => $notify_url, 'channel_name' => '',
  185. 'mch_amount' => $mch_amount, 'channel_amount' => 0,
  186. 'order_time' => $order_time, 'commit_times' => $commit_times,
  187. 'commit_time' => time(),'notify_state' => 1,'notify_time' => time(),
  188. 'card_type' => $card_type, 'card_no' => $card_no, 'quality' => $quality, 'org_quality' => $org_quality,
  189. 'err_msg' => $errmsg];
  190. $mod_refill->add_refill($orderext);
  191. return $order_id;
  192. }
  193. else {
  194. return 0;
  195. }
  196. }
  197. //$quality,质量
  198. //返回值:[ 错误码,错误信息,订单ID,是否是网络错误]
  199. //说明:错误码为true 表示成功
  200. // 其它情况,则需要判断订单ID
  201. public function add($mchid, $buyer_id, $amount, $card_no,
  202. $mch_order, $idcard, $card_name, $notify_url, $quality, $org_quality,
  203. $order_time, $commit_times, $last_orderid = 0, $card_type = 0)
  204. {
  205. if($card_type == 0) {
  206. $card_type = mtopcard\card_type($card_no);
  207. }
  208. [$providers,$overload] = $this->mPolicy->find_providers($amount,$card_type,$quality);
  209. if (empty($providers))
  210. {
  211. Log::record("canot find any providers",Log::DEBUG);
  212. if($overload) {
  213. return [errcode::PROVIDER_OVERLOAD, "匹配不到合适的充值通道",$last_orderid,false];
  214. }
  215. else {
  216. return [errcode::CANNOT_MATCH_PROVIDER, "匹配不到合适的充值通道",$last_orderid,false];
  217. }
  218. }
  219. if (empty($notify_url)) {
  220. $notify_url = "";
  221. }
  222. try {
  223. $minfo = new member_info($buyer_id);
  224. $calc = new CalcMerchantPrice($mchid, $amount, $card_type,$quality,$this->mPolicy);
  225. $mch_amount = $calc->calc_vgoods_price([]);
  226. }
  227. catch (Exception $ex) {
  228. return [errcode::MERCHANT_PRICE_UNSETTING, "没有协商商品价格",$last_orderid,false];
  229. }
  230. $available = $minfo->available_predeposit();
  231. if ($mch_amount > $available) {
  232. Log::record("下单时机构余额不足,可用余额为:{$available}", Log::DEBUG);
  233. return [errcode::MERCHANT_SHORT_MONEY, "余额不足支付订单",$last_orderid,false];
  234. }
  235. $refill_state = false;
  236. $order_success = false;
  237. foreach ($providers as $provider)
  238. {
  239. $channel_name = $provider->name();
  240. Log::record("select channel name = {$channel_name}",Log::DEBUG);
  241. //通道价格大于客户价格,换通道.
  242. [$goods_id, $price] = $provider->goods($quality,$amount,$card_type);
  243. if ($price >= $mch_amount) continue;
  244. Log::record("start create order",Log::DEBUG);
  245. $input['goods_id'] = $goods_id;
  246. $input['quantity'] = 1; //数量
  247. $input['buyer_phone'] = $minfo->mobile();
  248. $input['buyer_name'] = $minfo->truename();
  249. $input['buyer_msg'] = $_POST['buyer_msg'] ?? '';
  250. $input['order_from'] = 1;
  251. $input['pd_pay'] = true;
  252. $logic_buy_virtual = Logic('buy_virtual');
  253. $result = $logic_buy_virtual->buyStep3($input, $buyer_id, [$calc, 'calc_vorder_amount'], true);
  254. $mod_refill = Model('refill_order');
  255. if ($result['state'] === true)
  256. {
  257. $order_sn = $result['data']['order_sn'];
  258. $order_id = $result['data']['order_id'];
  259. if($last_orderid > 0) {
  260. $mod_refill->edit($last_orderid, ['inner_status' => 1]);
  261. }
  262. $last_orderid = $order_id;
  263. if (empty($mch_order)) {
  264. $mch_order = $order_sn;
  265. }
  266. //虚拟订单表信息扩展
  267. $orderext = ['order_id' => $order_id, 'order_sn' => $order_sn, 'mchid' => $mchid,
  268. 'refill_amount' => $amount, 'mch_order' => $mch_order,
  269. 'idcard' => $idcard, 'card_name' => $card_name,
  270. 'notify_url' => $notify_url, 'channel_name' => $channel_name,
  271. 'mch_amount' => $mch_amount, 'channel_amount' => $price,
  272. 'order_time' => $order_time, 'commit_times' => $commit_times,
  273. 'card_type' => $card_type, 'card_no' => $card_no,'quality' => $quality,'org_quality'=> $org_quality];
  274. $mod_refill->add_refill($orderext);
  275. if(!$this->pay_completed($order_sn)) {
  276. $logic_vr_order = Logic("vr_order");
  277. $order_info = Model('vr_order')->getOrderInfo(['order_id' => $order_id]);
  278. $logic_vr_order->changeOrderStateCancel($order_info, '', "预存款不足以支付该订单");
  279. break;
  280. }
  281. }
  282. else {
  283. Log::record("{$result['msg']}",Log::ERR);
  284. continue;
  285. }
  286. $order_success = true;
  287. $params = ['order_sn' => $order_sn, 'idcard' => $idcard, 'card_name' => $card_name,
  288. 'buyer_id' => $buyer_id,
  289. 'quality' => $quality,'order_id' => $order_id];
  290. util::incr_commit_pre($channel_name,$card_type,$amount,$quality);
  291. $start = microtime(true);
  292. [$state, $errmsg, $neterr] = $provider->add($card_no, $card_type, $amount, $params);
  293. Log::record(sprintf(" %s add request time=%.6f", $channel_name,microtime(true) - $start), Log::DEBUG);
  294. if ($state)
  295. {
  296. //提交成功
  297. util::incr_commit($channel_name,$card_type,$amount,$quality,true);
  298. util::incr_amount_lock($mchid,$card_type,$amount);
  299. $trade_no = $errmsg;
  300. if ($provider->refill_type() == 'api') {
  301. $logic_vr_order = Logic("vr_order");
  302. $logic_vr_order->changeOrderStateSend($order_id);
  303. }
  304. $data = ['commit_time' => time(), 'ch_trade_no' => $trade_no];
  305. $mod_refill->edit($order_id, $data);
  306. $refill_state = true;
  307. //如果对方没有回调能力,则启动主动查询.
  308. if($provider->callback() === false) {
  309. QueueClient::async_push("QueryRefillState",['order_id' => $order_id],180);
  310. }
  311. break;
  312. }
  313. else {
  314. //提交失败
  315. util::incr_commit($channel_name,$card_type,$amount,$quality,false);
  316. util::decr_amount_lock($mchid,$card_type,$amount);
  317. Log::record("channel:{$channel_name} err:{$errmsg}");
  318. $logic_vr_order = Logic("vr_order");
  319. $order_info = Model('vr_order')->getOrderInfo(['order_id' => $order_id]);
  320. $logic_vr_order->changeOrderStateCancel($order_info, '', "调用{$channel_name}接口失败");
  321. $mod_refill->edit($order_id, ['commit_time' => time()]);
  322. }
  323. }
  324. if ($refill_state) {
  325. return [true, '', $last_orderid,false];
  326. }
  327. elseif($order_success) {
  328. return [errcode::MERCHANT_REFILL_ERROR, "充值失败",$last_orderid,$neterr];
  329. }
  330. else {
  331. return [errcode::MERCHANT_REFILL_ERROR, "充值失败",$last_orderid,false];
  332. }
  333. }
  334. private function pay_completed($order_sn)
  335. {
  336. $logic_payment = Logic('payment');
  337. $order = $logic_payment->getVrOrderInfo($order_sn);
  338. $api_pay_amount = $order['data']['api_pay_amount'];
  339. return ($api_pay_amount == ncPriceFormat(0.00));
  340. }
  341. public function notify_merchant($order_id,$manual)
  342. {
  343. if ($order_id <= 0) {
  344. return [false, "订单ID小于0"];
  345. }
  346. $vr_order = Model('vr_order');
  347. $refill_order = Model('refill_order');
  348. $order_info = $vr_order->getOrderInfo(['order_id' => $order_id]);
  349. $refill_info = $refill_order->getOrderInfo(['order_id' => $order_id]);
  350. if (empty($order_info) || empty($refill_info)) {
  351. return [false, "无此订单"];
  352. }
  353. //手动通知,之所以不做尝试,是担心客户方状态处理不当
  354. if (!$manual && $refill_info['mch_notify_state'] != 0) {
  355. return [false, "已经通知客户方"];
  356. }
  357. $notify_url = $refill_info['notify_url'];
  358. if (empty($notify_url)) {
  359. $refill_order->edit($order_id, ['mch_notify_state' => 1, 'mch_notify_times' => 0]);
  360. return [false, "回调地址为空"];
  361. }
  362. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  363. $order_state = intval($order_info['order_state']);
  364. if ($order_state !== ORDER_STATE_CANCEL && $order_state !== ORDER_STATE_SUCCESS) {
  365. return [false, "错误的订单状态,不能通知."];
  366. }
  367. $resp = $this->mPolicy->notify($order_info,$refill_info);
  368. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  369. if ($resp) {
  370. $refill_order->edit($order_id, ['mch_notify_state' => 1, 'mch_notify_times' => ['exp', 'mch_notify_times+1']]);
  371. return [true, ""];
  372. }
  373. else {
  374. $refill_order->edit($order_id, ['mch_notify_times' => ['exp', 'mch_notify_times+1']]);
  375. $times = $refill_info['mch_notify_times'] + 1;
  376. if ($times > 80) {
  377. $refill_order->edit($order_id, ['mch_notify_state' => 2]);
  378. } else {
  379. $N = intval($times / 5);
  380. $period = intval(pow(2, $N));
  381. QueueClient::async_push("NotifyMerchantComplete", ['order_id' => $order_id,'manual' => false], $period);
  382. }
  383. return [false, "通知{$times}次,失败."];
  384. }
  385. }
  386. public function query($order_id)
  387. {
  388. $mod_order = Model('vr_order');
  389. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id]);
  390. if(empty($order_info)) return false;
  391. $mod_refill = Model('refill_order');
  392. $refill_info = $mod_refill->getOrderInfo(['order_id' => $order_id,'inner_status' => 0]);
  393. $chname = $refill_info['channel_name'];
  394. if($refill_info['notify_state'] == 1) {
  395. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id,'manual' => false]);
  396. return true;
  397. }
  398. try
  399. {
  400. $tran = new trans_wapper($mod_order,'query order state trans');
  401. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id],'*',true,true);
  402. if($refill_info['is_retrying'] == 1) {
  403. $query_able = false;
  404. }
  405. elseif($order_info['order_state'] == ORDER_STATE_SEND) {
  406. $query_able = true;
  407. }
  408. else {
  409. $query_able = false;
  410. }
  411. $tran->commit();
  412. }
  413. catch (Exception $ex) {
  414. $tran->rollback();
  415. Log::record($ex->getMessage(),Log::ERR);
  416. }
  417. if($query_able)
  418. {
  419. if(empty($chname)) return false;
  420. $provider = $this->mPolicy->provider($chname);
  421. if(empty($provider)) return false;
  422. [$state, $order_state] = $provider->query($refill_info);
  423. if(!$state) {
  424. QueueClient::async_push("QueryRefillState",['order_id' => $order_id],180);
  425. return false;
  426. }
  427. elseif($order_state == ORDER_STATE_SUCCESS) {
  428. $this->proc_notify($order_id,true,false,$chname);
  429. }
  430. elseif($order_state == ORDER_STATE_CANCEL) {
  431. $this->proc_notify($order_id,false,true,$chname);
  432. }
  433. else {
  434. QueueClient::async_push("QueryRefillState",['order_id' => $order_id],180);
  435. }
  436. }
  437. return true;
  438. }
  439. public function manual_success($order_id)
  440. {
  441. $order_id = intval($order_id);
  442. if($order_id <= 0) return false;
  443. try {
  444. $mod_order = Model('vr_order');
  445. $tran = new trans_wapper($mod_order,'manual_success r state trans');
  446. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id],'*',true,true);
  447. if(!empty($order_info) && $order_info['order_state'] == ORDER_STATE_SEND) {
  448. $tran->commit();
  449. $logic_vr_order = Logic("vr_order");
  450. $logic_vr_order->changeOrderStateSuccess($order_id);
  451. $refill_order = Model('refill_order');
  452. $refill_order->edit($order_id, ['notify_time' => time(), 'notify_state' => 1,'is_retrying' => 0]);
  453. mtopcard\cards_helper::assign($order_id);
  454. }
  455. else {
  456. $tran->commit();
  457. }
  458. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id,'manual' => true]);
  459. return true;
  460. }
  461. catch (Exception $ex) {
  462. $tran->rollback();
  463. Log::record("manual_success exception:{$ex->getMessage()}",Log::ERR);
  464. return false;
  465. }
  466. }
  467. public function manual_cancel($order_id)
  468. {
  469. $order_id = intval($order_id);
  470. if($order_id <= 0) return false;
  471. try {
  472. $mod_order = Model('vr_order');
  473. $tran = new trans_wapper($mod_order,'manual_cancel state trans');
  474. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id],'*',true,true);
  475. if(!empty($order_info) && $order_info['order_state'] == ORDER_STATE_SEND) {
  476. $tran->commit();
  477. $logic_vr_order = Logic("vr_order");
  478. $logic_vr_order->changeOrderStateCancel($order_info, '', "后台手动回调通知失败");
  479. $refill_order = Model('refill_order');
  480. $refill_order->edit($order_id, ['notify_time' => time(), 'notify_state' => 1,'is_retrying' => 0]);
  481. mtopcard\cards_helper::reuse($order_id);
  482. }
  483. else {
  484. $tran->commit();
  485. }
  486. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id,'manual' => true]);
  487. return true;
  488. }
  489. catch (Exception $ex) {
  490. $tran->rollback();
  491. Log::record("manual_cancel exception:{$ex->getMessage()}",Log::ERR);
  492. return false;
  493. }
  494. }
  495. }