RefillFactory.php 21 KB

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