RefillFactory.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. <?php
  2. namespace refill;
  3. require_once(BASE_HELPER_PATH . '/mtopcard/mtopcard.php');
  4. require_once(BASE_HELPER_PATH . '/rbridge/RBridgeFactory.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/CalcMerchantPrice.php');
  10. require_once(BASE_HELPER_PATH . '/refill/suhc/RefillOil.php');
  11. require_once(BASE_HELPER_PATH . '/refill/suhc/RefillPhone.php');
  12. require_once(BASE_HELPER_PATH . '/refill/suhc/RefillCallBack.php');
  13. require_once(BASE_HELPER_PATH . '/refill/suhctm/RefillOil.php');
  14. require_once(BASE_HELPER_PATH . '/refill/suhctm/RefillPhone.php');
  15. require_once(BASE_HELPER_PATH . '/refill/suhctm/RefillCallBack.php');
  16. require_once(BASE_HELPER_PATH . '/refill/beixt/RefillPhone.php');
  17. require_once(BASE_HELPER_PATH . '/refill/beixt/RefillCallBack.php');
  18. require_once(BASE_HELPER_PATH . '/refill/bxtwt/RefillPhone.php');
  19. require_once(BASE_HELPER_PATH . '/refill/bxtwt/RefillCallBack.php');
  20. require_once(BASE_HELPER_PATH . '/refill/bjb/RefillPhone.php');
  21. require_once(BASE_HELPER_PATH . '/refill/bjb/RefillCallBack.php');
  22. require_once(BASE_HELPER_PATH . '/refill/bdt/RefillPhone.php');
  23. require_once(BASE_HELPER_PATH . '/refill/bdt/RefillCallBack.php');
  24. require_once(BASE_HELPER_PATH . '/refill/zzx/RefillOil.php');
  25. require_once(BASE_HELPER_PATH . '/refill/zzx/RefillPhone.php');
  26. require_once(BASE_HELPER_PATH . '/refill/zzx/RefillCallBack.php');
  27. require_once(BASE_HELPER_PATH . '/refill/lx/RefillOil.php');
  28. require_once(BASE_HELPER_PATH . '/refill/lx/RefillPhone.php');
  29. require_once(BASE_HELPER_PATH . '/refill/lx/RefillCallBack.php');
  30. require_once(BASE_HELPER_PATH . '/refill/saihu/RefillOil.php');
  31. require_once(BASE_HELPER_PATH . '/refill/saihu/RefillPhone.php');
  32. require_once(BASE_HELPER_PATH . '/refill/saihu/RefillCallBack.php');
  33. require_once(BASE_HELPER_PATH . '/refill/yifa/RefillPhone.php');
  34. require_once(BASE_HELPER_PATH . '/refill/yifa/RefillCallBack.php');
  35. require_once(BASE_HELPER_PATH . '/refill/jc/RefillPhone.php');
  36. require_once(BASE_HELPER_PATH . '/refill/jc/RefillCallBack.php');
  37. require_once(BASE_HELPER_PATH . '/refill/xc/RefillPhone.php');
  38. require_once(BASE_HELPER_PATH . '/refill/xc/RefillCallBack.php');
  39. use Log;
  40. use mtopcard;
  41. use QueueClient;
  42. use member_info;
  43. use Exception;
  44. use rbridge\RBridgeFactory;
  45. class RefillFactory
  46. {
  47. private static $stInstance = null;
  48. public static function instance()
  49. {
  50. if (self::$stInstance == null) {
  51. self::$stInstance = new RefillFactory();
  52. }
  53. return self::$stInstance;
  54. }
  55. private $mOilProvider = [];
  56. private $mPhoneProvider = [];
  57. private $mProviderNames = [];
  58. private function __construct()
  59. {
  60. $this->load();
  61. }
  62. public function goods()
  63. {
  64. global $config;
  65. $oil = $this->combine_goods($config['oil_providers']);
  66. $phone = $this->combine_goods($config['phone_providers']);
  67. return array_merge($oil, $phone);
  68. }
  69. private function combine_goods($configs)
  70. {
  71. $result = [];
  72. foreach ($configs as $cfg) {
  73. $card_types = $cfg['card_type'] ?? [];
  74. $amounts = $cfg['amount'] ?? [];
  75. foreach ($card_types as $type) {
  76. if (array_key_exists($type, $result)) {
  77. $item = $result[$type];
  78. } else {
  79. $item = [];
  80. }
  81. foreach ($amounts as $amount => $val) {
  82. $item[] = $amount;
  83. }
  84. $item = array_unique($item);
  85. $result[$type] = $item;
  86. }
  87. }
  88. return $result;
  89. }
  90. private function load()
  91. {
  92. global $config;
  93. $oil_configs = $config['oil_providers'];
  94. $names = [];
  95. foreach ($oil_configs as $cfg) {
  96. $name = $cfg['name'];
  97. $names[] = $name;
  98. try {
  99. $class = "refill\\{$name}\\RefillOil";
  100. if (class_exists($class, false)) {
  101. $provider = new $class($cfg);
  102. $this->mOilProvider[] = $provider;
  103. } else {
  104. $error = "Base Error: class {$class} isn't exists!";
  105. throw new Exception($error);
  106. }
  107. } catch (Exception $ex) {
  108. Log::record($ex->getMessage(), Log::ERR);
  109. }
  110. }
  111. $pho_configs = $config['phone_providers'];
  112. foreach ($pho_configs as $cfg) {
  113. $name = $cfg['name'];
  114. $names[] = $name;
  115. try {
  116. $class = "refill\\{$name}\\RefillPhone";
  117. if (class_exists($class, false)) {
  118. $provider = new $class($cfg);
  119. $this->mPhoneProvider[] = $provider;
  120. } else {
  121. $error = "Base Error: class {$class} isn't exists!";
  122. throw new Exception($error);
  123. }
  124. } catch (Exception $ex) {
  125. Log::record($ex->getMessage(), Log::ERR);
  126. }
  127. }
  128. $this->mProviderNames = array_unique($names);
  129. }
  130. public function find_providers(int $amount, int $card_type): array
  131. {
  132. if ($card_type == mtopcard\SinopecCard || $card_type == mtopcard\PetroChinaCard) {
  133. return $this->find_oil($amount, $card_type);
  134. } elseif ($card_type == mtopcard\ChinaMobileCard || $card_type == mtopcard\ChinaUnicomCard || $card_type == mtopcard\ChinaTelecomCard) {
  135. return $this->find_phone($amount, $card_type);
  136. } else {
  137. return [];
  138. }
  139. }
  140. private function find_oil(int $amount, int $card_type): array
  141. {
  142. $providers = [];
  143. foreach ($this->mOilProvider as $provider) {
  144. $name = $provider->name();
  145. [$success, $err] = $provider->check($amount, $card_type);
  146. if ($success) {
  147. $providers[] = $provider;
  148. } else {
  149. Log::record("{$name} provider cannot match check,err:{$err}", Log::DEBUG);
  150. }
  151. }
  152. return $providers;
  153. }
  154. public function provider(string $chname, int $card_type)
  155. {
  156. if ($card_type == mtopcard\SinopecCard || $card_type == mtopcard\PetroChinaCard) {
  157. $providers = $this->mOilProvider;
  158. } elseif ($card_type == mtopcard\ChinaMobileCard || $card_type == mtopcard\ChinaUnicomCard || $card_type == mtopcard\ChinaTelecomCard) {
  159. $providers = $this->mPhoneProvider;
  160. } else {
  161. return null;
  162. }
  163. foreach ($providers as $provider) {
  164. if ($provider->name() == $chname) {
  165. return $provider;
  166. }
  167. }
  168. return null;
  169. }
  170. private function find_phone(int $amount, int $card_type): array
  171. {
  172. $providers = [];
  173. foreach ($this->mPhoneProvider as $provider) {
  174. $name = $provider->name();
  175. [$success, $err] = $provider->check($amount, $card_type);
  176. if ($success) {
  177. $providers[] = $provider;
  178. } else {
  179. Log::record("{$name} provider cannot match check,err:{$err}", Log::DEBUG);
  180. }
  181. }
  182. return $providers;
  183. }
  184. public function notify($chname, $input)
  185. {
  186. try {
  187. $class_name = "refill\\{$chname}\\RefillCallBack";
  188. if (class_exists($class_name, false)) {
  189. $caller = new $class_name();
  190. } else {
  191. $error = "Base Error: class {$class_name} isn't exists!";
  192. throw new Exception($error);
  193. }
  194. } catch (Exception $ex) {
  195. Log::record($ex->getMessage(), Log::ERR);
  196. return false;
  197. }
  198. if ($caller->verify($input)) {
  199. [$order_id, $success, $can_try, $need_handle] = $caller->notify($input);
  200. if (!$need_handle) {
  201. return true;
  202. }
  203. if ($order_id !== false) {
  204. $mod_order = Model('vr_order');
  205. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id]);
  206. $order_state = intval($order_info['order_state']);
  207. if ($order_state != ORDER_STATE_SEND) {
  208. return false;
  209. }
  210. $mod_refill = Model('refill_order');
  211. $refill_info = $mod_refill->getOrderInfo(['order_id' => $order_id]);
  212. $logic_vr_order = Logic("vr_order");
  213. if ($success) {
  214. $logic_vr_order->changeOrderStateSuccess($order_id);
  215. } elseif ($can_try) {
  216. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口回调通知失败,正在重试");
  217. if ($this->retry($refill_info, $order_info) !== false) {
  218. $mod_refill->edit($order_id, ['inner_status' => 1, 'notify_time' => time(), 'notify_state' => 1]);
  219. return true;
  220. }
  221. } else {
  222. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口回调通知失败,不可重试.");
  223. }
  224. $mod_refill->edit($order_id, ['notify_time' => time(), 'notify_state' => 1]);
  225. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id]);
  226. } else {
  227. Log::record("系统无此订单ID:{$order_id}", Log::ERR);
  228. }
  229. } else {
  230. Log::record("{$chname} 签名失败.");
  231. }
  232. return true;
  233. }
  234. private function retry(array $refill_info, array $order_info)
  235. {
  236. $checker = function ($refill, $order) {
  237. $state = intval($order['order_state']);
  238. if ($state !== ORDER_STATE_SEND) {
  239. return false;
  240. }
  241. // $times = intval($refill['commit_times']);
  242. // if ($times > 5) {
  243. // return false;
  244. // }
  245. $period = time() - $refill['order_time'];
  246. if ($period >= 10 * 60) {
  247. return false;
  248. }
  249. return true;
  250. };
  251. $can_try = $checker($refill_info, $order_info);
  252. if (!$can_try) {
  253. return false;
  254. }
  255. $mchid = $refill_info['mchid'];
  256. $buyer_id = $order_info['buyer_id'];
  257. $amount = $refill_info['refill_amount'];
  258. $card_no = $refill_info['card_no'];
  259. $mch_order = $refill_info['mch_order'];
  260. $notify_url = $refill_info['notify_url'];
  261. $commit_times = $refill_info['commit_times'] + 1;
  262. $order_time = $refill_info['order_time'];
  263. $idcard = $refill_info['idcard'] ?? '';
  264. $card_name = $refill_info['card_name'] ?? '';
  265. [$success, $err] = $this->add($mchid, $buyer_id, $amount, $card_no, $mch_order, $idcard, $card_name, $notify_url, $order_time, $commit_times);
  266. return ($success === true);
  267. }
  268. public function add($mchid, $buyer_id, $amount, $card_no, $mch_order, $idcard, $card_name, $notify_url, $order_time = 0, $commit_times = 0)
  269. {
  270. $card_type = mtopcard\card_type($card_no);
  271. $providers = $this->find_providers($amount, $card_type);
  272. if (empty($providers)) {
  273. return [202, "找不到合适的充值通道"];
  274. }
  275. if (empty($notify_url)) {
  276. $notify_url = "";
  277. }
  278. $minfo = new member_info($buyer_id);
  279. $calc = new CalcMerchantPrice($mchid, $amount, $card_type);
  280. $mch_amount = $calc->calc_vgoods_price([]);
  281. $available = $minfo->available_predeposit();
  282. if ($mch_amount > $available) {
  283. Log::record("下单时机构余额不足,可用余额为:{$available}", Log::DEBUG);
  284. return [203, "余额不足"];
  285. }
  286. if ($order_time === 0) {
  287. $order_time = time();
  288. }
  289. $ascending = function ($l, $r) use ($amount) {
  290. [$lid, $lprice] = $l->goods($amount);
  291. [$rid, $rprice] = $r->goods($amount);
  292. return $lprice < $rprice ? -1 : 1;
  293. };
  294. usort($providers, $ascending);
  295. $refill_state = false;
  296. foreach ($providers as $provider)
  297. {
  298. $channel_name = $provider->name();
  299. [$goods_id, $price] = $provider->goods($amount);
  300. if ($price > $mch_amount) continue;
  301. $input['goods_id'] = $goods_id;
  302. $input['quantity'] = 1;
  303. $input['price'] = $price;
  304. $input['buyer_phone'] = $minfo->mobile();
  305. $input['buyer_name'] = $minfo->truename();
  306. $input['buyer_msg'] = $_POST['buyer_msg'] ?? '';
  307. $input['order_from'] = 1;
  308. $input['pd_pay'] = true;
  309. $logic_buy_virtual = Logic('buy_virtual');
  310. $result = $logic_buy_virtual->buyStep3($input, $buyer_id, [$calc, 'calc_vorder_amount'], true);
  311. $mod_refill = Model('refill_order');
  312. if ($result['state'] === true)
  313. {
  314. $order_sn = $result['data']['order_sn'];
  315. $order_id = $result['data']['order_id'];
  316. if (empty($mch_order)) {
  317. $mch_order = $order_sn;
  318. }
  319. //虚拟订单表信息扩展
  320. $orderext = ['order_id' => $order_id, 'order_sn' => $order_sn, 'mchid' => $mchid,
  321. 'refill_amount' => $amount, 'mch_order' => $mch_order,
  322. 'idcard' => $idcard, 'card_name' => $card_name,
  323. 'notify_url' => $notify_url, 'channel_name' => $channel_name,
  324. 'mch_amount' => $mch_amount, 'channel_amount' => $price,
  325. 'order_time' => $order_time, 'commit_times' => $commit_times,
  326. 'card_type' => $card_type, 'card_no' => $card_no];
  327. $mod_refill->add_refill($orderext);
  328. } else {
  329. continue;
  330. }
  331. $params = ['order_sn' => $order_sn, 'idcard' => $idcard, 'card_name' => $card_name];
  332. [$state, $err] = $provider->add($card_no, $card_type, $amount, $params);
  333. if ($state)
  334. {
  335. $trade_no = $err;
  336. if ($provider->refill_type() == 'api') {
  337. $logic_vr_order = Logic("vr_order");
  338. $logic_vr_order->changeOrderStateSend($order_id);
  339. }
  340. $data = ['commit_time' => time(), 'ch_trade_no' => $trade_no];
  341. $mod_refill->edit($order_id, $data);
  342. $refill_state = true;
  343. //如果对方没有回调能力,则启动主动查询.
  344. if($provider->callback() === false) {
  345. QueueClient::async_push("QueryRefillState",['order_id' => $order_id],180);
  346. }
  347. break;
  348. } else {
  349. Log::record("channel:{$channel_name} err:{$err}");
  350. $logic_vr_order = Logic("vr_order");
  351. $order_info = Model('vr_order')->getOrderInfo(['order_id' => $order_id]);
  352. $logic_vr_order->changeOrderStateCancel($order_info, '', "调用{$channel_name}接口失败");
  353. $mod_refill->edit($order_id, ['commit_time' => time(), 'inner_status' => 1]);
  354. }
  355. }
  356. if ($refill_state) {
  357. return [true, $order_sn];
  358. } else {
  359. return [204, "充值失败."];
  360. }
  361. }
  362. private function is_url($url)
  363. {
  364. $checker = function ($haystack, $needle) {
  365. $length = strlen($needle);
  366. return (substr($haystack, 0, $length) === $needle);
  367. };
  368. return $checker($url, "http://") || $checker($url, "https://");
  369. }
  370. public function notify_merchant($order_id)
  371. {
  372. if ($order_id <= 0) {
  373. return [false, "订单ID小于0"];
  374. }
  375. $vr_order = Model('vr_order');
  376. $refill_order = Model('refill_order');
  377. $order_info = $vr_order->getOrderInfo(['order_id' => $order_id]);
  378. $refill_info = $refill_order->getOrderInfo(['order_id' => $order_id]);
  379. if (empty($order_info) || empty($refill_info)) {
  380. return [false, "无此订单"];
  381. }
  382. if ($refill_info['mch_notify_state'] != 0) {
  383. return [false, "已经通知客户方"];
  384. }
  385. $notify_url = $refill_info['notify_url'];
  386. if (empty($notify_url)) {
  387. $refill_order->edit($order_id, ['mch_notify_state' => 1, 'mch_notify_times' => 0]);
  388. return [false, "回调地址为空"];
  389. }
  390. $order_state = $order_info['order_state'];
  391. if ($order_state == ORDER_STATE_CANCEL) {
  392. $state = "CANCEL";
  393. } elseif ($order_state == ORDER_STATE_SUCCESS) {
  394. $state = "SUCCESS";
  395. } else {
  396. return [false, "错误的订单状态,不能通知."];
  397. }
  398. $mchid = $refill_info['mchid'];
  399. $mch_info = Model('merchant')->getMerchantInfo(['mchid' => $mchid]);
  400. [$params, $sign] = $this->body($state, $refill_info, $mch_info);
  401. $params['sign'] = $sign;
  402. //如果http请求内部,又发出回调自己的请求,在处理进程非动态扩容的情况下,容易造成阻塞.
  403. if ($this->is_url($notify_url)) {
  404. $resp = http_request($notify_url, $params, 'POST');
  405. } else {
  406. $resp = RBridgeFactory::instance()->notify($notify_url, $params);
  407. }
  408. if ($resp == "SUCCESS") {
  409. $refill_order->edit($order_id, ['mch_notify_state' => 1, 'mch_notify_times' => ['exp', 'mch_notify_times+1']]);
  410. return [true, ""];
  411. } else {
  412. $refill_order->edit($order_id, ['mch_notify_times' => ['exp', 'mch_notify_times+1']]);
  413. $times = $refill_info['mch_notify_times'] + 1;
  414. if ($times > 80) {
  415. $refill_order->edit($order_id, ['mch_notify_state' => 2]);
  416. } else {
  417. $N = intval($times / 5);
  418. $period = intval(pow(2, $N));
  419. QueueClient::async_push("NotifyMerchantComplete", ['order_id' => $order_id], $period);
  420. }
  421. return [false, "通知{$times}次,失败."];
  422. }
  423. }
  424. public function query($order_id)
  425. {
  426. $mod_refill = Model('refill_order');
  427. $refill_info = $mod_refill->getOrderInfo(['order_id' => $order_id,'inner_status' => 0]);
  428. $chname = $refill_info['channel_name'];
  429. $card_type = intval($refill_info['card_type']);
  430. $pthis = $this;
  431. $finder = function ($chname, $card_type) use ($pthis)
  432. {
  433. if ($card_type == mtopcard\SinopecCard || $card_type == mtopcard\PetroChinaCard) {
  434. $providers = $pthis->mOilProvider;
  435. } else {
  436. $providers = $pthis->mPhoneProvider;
  437. }
  438. foreach ($providers as $provider) {
  439. if ($chname == $provider->name()) {
  440. return $provider;
  441. }
  442. }
  443. return NULL;
  444. };
  445. $provider = $finder($chname, $card_type);
  446. [$state, $order_state] = $provider->query($refill_info);
  447. if ($state === true)
  448. {
  449. $notify_state = $refill_info['notify_state'];
  450. if($notify_state == 0)
  451. {
  452. $modify_able = true;
  453. if(!$provider->callback())
  454. {
  455. $logic_vr_order = Logic("vr_order");
  456. if ($order_state == ORDER_STATE_SUCCESS) {
  457. $logic_vr_order->changeOrderStateSuccess($order_id);
  458. } elseif ($order_state == ORDER_STATE_CANCEL) {
  459. $mod_order = Model('vr_order');
  460. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id]);
  461. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口查询失败,不再重试.");
  462. } else {
  463. $modify_able = false;
  464. QueueClient::async_push("QueryRefillState",['order_id' => $order_id],180);
  465. }
  466. }
  467. if($modify_able) {
  468. $mod_refill->edit($order_id, ['notify_time' => time(), 'notify_state' => 1]);
  469. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id]);
  470. }
  471. }
  472. return true;
  473. }
  474. else {
  475. return false;
  476. }
  477. }
  478. private function body($state, $refill_info, $mch_info)
  479. {
  480. $params = [
  481. "mchid" => $refill_info['mchid'],
  482. "order_sn" => $refill_info['mch_order'],
  483. "amount" => $refill_info['refill_amount'],
  484. "cardno" => $refill_info['card_no'],
  485. "trade_no" => $refill_info['order_sn'],
  486. "idcard" => $refill_info['idcard'] ?? "",
  487. "card_name" => $refill_info['card_name'] ?? "",
  488. 'official_sn' => $refill_info['official_sn'] ?? "",
  489. "state" => $state];
  490. $secure_key = $mch_info['secure_key'];
  491. $sign = $this->sign($params, $secure_key);
  492. return [$params, $sign];
  493. }
  494. private function sign($params, $key)
  495. {
  496. ksort($params);
  497. $body = "";
  498. $i = 0;
  499. foreach ($params as $k => $v) {
  500. if (false === $this->check_empty($v) && "@" != substr($v, 0, 1)) {
  501. if ($i == 0) {
  502. $body .= "{$k}" . "=" . urlencode($v);
  503. } else {
  504. $body .= "&" . "{$k}" . "=" . urlencode($v);
  505. }
  506. $i++;
  507. }
  508. }
  509. $body .= "&key={$key}";
  510. return md5($body);
  511. }
  512. private function check_empty($value)
  513. {
  514. if (!isset($value))
  515. return true;
  516. if ($value === null)
  517. return true;
  518. if (trim($value) === "")
  519. return true;
  520. return false;
  521. }
  522. }