RefillFactory.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. use Log;
  31. use mtopcard;
  32. use QueueClient;
  33. use member_info;
  34. use Exception;
  35. use rbridge\RBridgeFactory;
  36. class RefillFactory
  37. {
  38. private static $stInstance = null;
  39. public static function instance()
  40. {
  41. if (self::$stInstance == null) {
  42. self::$stInstance = new RefillFactory();
  43. }
  44. return self::$stInstance;
  45. }
  46. private $mOilProvider = [];
  47. private $mPhoneProvider = [];
  48. private $mProviderNames = [];
  49. private function __construct()
  50. {
  51. $this->load();
  52. }
  53. public function goods()
  54. {
  55. global $config;
  56. $oil = $this->combine_goods($config['oil_providers']);
  57. $phone = $this->combine_goods($config['phone_providers']);
  58. return array_merge($oil, $phone);
  59. }
  60. private function combine_goods($configs)
  61. {
  62. $result = [];
  63. foreach ($configs as $cfg)
  64. {
  65. $card_types = $cfg['card_type'] ?? [];
  66. $amounts = $cfg['amount'] ?? [];
  67. foreach ($card_types as $type)
  68. {
  69. if (array_key_exists($type, $result)) {
  70. $item = $result[$type];
  71. } else {
  72. $item = [];
  73. }
  74. foreach ($amounts as $amount => $val) {
  75. $item[] = $amount;
  76. }
  77. $item = array_unique($item);
  78. $result[$type] = $item;
  79. }
  80. }
  81. return $result;
  82. }
  83. private function load()
  84. {
  85. global $config;
  86. $oil_configs = $config['oil_providers'];
  87. $names = [];
  88. foreach ($oil_configs as $cfg)
  89. {
  90. $name = $cfg['name'];
  91. $names[] = $name;
  92. try
  93. {
  94. $class = "refill\\{$name}\\RefillOil";
  95. if(class_exists($class,false)) {
  96. $provider = new $class($cfg);
  97. $this->mOilProvider[] = $provider;
  98. } else {
  99. $error = "Base Error: class {$class} isn't exists!";
  100. throw new Exception($error);
  101. }
  102. }
  103. catch (Exception $ex)
  104. {
  105. Log::record($ex->getMessage(),Log::ERR);
  106. }
  107. }
  108. $pho_configs = $config['phone_providers'];
  109. foreach ($pho_configs as $cfg)
  110. {
  111. $name = $cfg['name'];
  112. $names[] = $name;
  113. try
  114. {
  115. $class = "refill\\{$name}\\RefillPhone";
  116. if(class_exists($class,false)) {
  117. $provider = new $class($cfg);
  118. $this->mPhoneProvider[] = $provider;
  119. } else {
  120. $error = "Base Error: class {$class} isn't exists!";
  121. throw new Exception($error);
  122. }
  123. }
  124. catch (Exception $ex)
  125. {
  126. Log::record($ex->getMessage(),Log::ERR);
  127. }
  128. }
  129. $this->mProviderNames = array_unique($names);
  130. }
  131. public function find_providers(int $amount, int $card_type): array
  132. {
  133. if ($card_type == mtopcard\SinopecCard || $card_type == mtopcard\PetroChinaCard) {
  134. return $this->find_oil($amount, $card_type);
  135. } elseif ($card_type == mtopcard\ChinaMobileCard || $card_type == mtopcard\ChinaUnicomCard || $card_type == mtopcard\ChinaTelecomCard) {
  136. return $this->find_phone($amount, $card_type);
  137. } else {
  138. return [];
  139. }
  140. }
  141. private function find_oil(int $amount, int $card_type): array
  142. {
  143. $providers = [];
  144. foreach ($this->mOilProvider as $provider) {
  145. $name = $provider->name();
  146. [$success, $err] = $provider->check($amount, $card_type);
  147. if ($success) {
  148. $providers[] = $provider;
  149. } else {
  150. Log::record("{$name} provider cannot match check,err:{$err}", Log::DEBUG);
  151. }
  152. }
  153. return $providers;
  154. }
  155. private function find_phone(int $amount, int $card_type): array
  156. {
  157. $providers = [];
  158. foreach ($this->mPhoneProvider as $provider) {
  159. $name = $provider->name();
  160. [$success, $err] = $provider->check($amount, $card_type);
  161. if ($success) {
  162. $providers[] = $provider;
  163. } else {
  164. Log::record("{$name} provider cannot match check,err:{$err}", Log::DEBUG);
  165. }
  166. }
  167. return $providers;
  168. }
  169. public function notify($chname, $input)
  170. {
  171. try
  172. {
  173. $class_name = "refill\\{$chname}\\RefillCallBack";
  174. if(class_exists($class_name,false)) {
  175. $caller = new $class_name();
  176. } else {
  177. $error = "Base Error: class {$class_name} isn't exists!";
  178. throw new Exception($error);
  179. }
  180. }
  181. catch (Exception $ex)
  182. {
  183. Log::record($ex->getMessage(),Log::ERR);
  184. return false;
  185. }
  186. if ($caller->verify($input))
  187. {
  188. [$order_id, $success, $can_try,$need_handle] = $caller->notify($input);
  189. if(!$need_handle) {
  190. return true;
  191. }
  192. if ($order_id !== false)
  193. {
  194. $mod_order = Model('vr_order');
  195. $order_info = $mod_order->getOrderInfo(['order_id' => $order_id]);
  196. $order_state = intval($order_info['order_state']);
  197. if ($order_state != ORDER_STATE_SEND) {
  198. return false;
  199. }
  200. $mod_refill = Model('refill_order');
  201. $refill_info = $mod_refill->getOrderInfo(['order_id' => $order_id]);
  202. $logic_vr_order = Logic("vr_order");
  203. if ($success) {
  204. $logic_vr_order->changeOrderStateSuccess($order_id);
  205. }
  206. elseif ($can_try)
  207. {
  208. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口回调通知失败,正在重试");
  209. if ($this->retry($refill_info, $order_info) !== false) {
  210. $mod_refill->edit($order_id, ['inner_status' => 1, 'notify_time' => time(), 'notify_state' => 1]);
  211. return true;
  212. }
  213. }
  214. else {
  215. $logic_vr_order->changeOrderStateCancel($order_info, '', "{$chname}接口回调通知失败,不可重试.");
  216. }
  217. $mod_refill->edit($order_id, ['notify_time' => time(), 'notify_state' => 1]);
  218. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id]);
  219. }
  220. else {
  221. Log::record("系统无此订单ID:{$order_id}", Log::ERR);
  222. }
  223. }
  224. else {
  225. Log::record("{$chname} 签名失败.");
  226. }
  227. return true;
  228. }
  229. private function retry(array $refill_info, array $order_info)
  230. {
  231. $checker = function ($refill, $order)
  232. {
  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. break;
  340. } else {
  341. Log::record("channel:{$channel_name} err:{$err}");
  342. $logic_vr_order = Logic("vr_order");
  343. $order_info = Model('vr_order')->getOrderInfo(['order_id' => $order_id]);
  344. $logic_vr_order->changeOrderStateCancel($order_info, '', "调用{$channel_name}接口失败");
  345. }
  346. }
  347. if ($refill_state) {
  348. return [true, $order_sn];
  349. } else {
  350. return [204, "充值失败."];
  351. }
  352. }
  353. private function is_url($url)
  354. {
  355. $checker = function ($haystack, $needle) {
  356. $length = strlen($needle);
  357. return (substr($haystack, 0, $length) === $needle);
  358. };
  359. return $checker($url,"http://") || $checker($url,"https://");
  360. }
  361. public function notify_merchant($order_id)
  362. {
  363. if ($order_id <= 0) {
  364. return [false, "订单ID小于0"];
  365. }
  366. $vr_order = Model('vr_order');
  367. $refill_order = Model('refill_order');
  368. $order_info = $vr_order->getOrderInfo(['order_id' => $order_id]);
  369. $refill_info = $refill_order->getOrderInfo(['order_id' => $order_id]);
  370. if (empty($order_info) || empty($refill_info)) {
  371. return [false, "无此订单"];
  372. }
  373. if ($refill_info['mch_notify_state'] != 0) {
  374. return [false, "已经通知客户方"];
  375. }
  376. $notify_url = $refill_info['notify_url'];
  377. if (empty($notify_url)) {
  378. $refill_order->edit($order_id, ['mch_notify_state' => 1, 'mch_notify_times' => 0]);
  379. return [false, "回调地址为空"];
  380. }
  381. $order_state = $order_info['order_state'];
  382. if ($order_state == ORDER_STATE_CANCEL) {
  383. $state = "CANCEL";
  384. } elseif ($order_state == ORDER_STATE_SUCCESS) {
  385. $state = "SUCCESS";
  386. } else {
  387. return [false, "错误的订单状态,不能通知."];
  388. }
  389. $mchid = $refill_info['mchid'];
  390. $mch_info = Model('merchant')->getMerchantInfo(['mchid' => $mchid]);
  391. [$params, $sign] = $this->body($state, $refill_info, $mch_info);
  392. $params['sign'] = $sign;
  393. //如果http请求内部,又发出回调自己的请求,在处理进程非动态扩容的情况下,容易造成阻塞.
  394. if($this->is_url($notify_url)) {
  395. $resp = http_request($notify_url, $params, 'POST');
  396. }
  397. else {
  398. $resp = RBridgeFactory::instance()->notify($notify_url,$params);
  399. }
  400. if ($resp == "SUCCESS") {
  401. $refill_order->edit($order_id, ['mch_notify_state' => 1, 'mch_notify_times' => ['exp', 'mch_notify_times+1']]);
  402. return [true, ""];
  403. } else {
  404. $refill_order->edit($order_id, ['mch_notify_times' => ['exp', 'mch_notify_times+1']]);
  405. $times = $refill_info['mch_notify_times'] + 1;
  406. if ($times > 80) {
  407. $refill_order->edit($order_id, ['mch_notify_state' => 2]);
  408. } else {
  409. $N = intval($times / 5);
  410. $period = intval(pow(2, $N));
  411. QueueClient::async_push("NotifyMerchantComplete", ['order_id' => $order_id], $period);
  412. }
  413. return [false, "通知{$times}次,失败."];
  414. }
  415. }
  416. public function query($order_id)
  417. {
  418. $mod_refill = Model('refill_order');
  419. $refill_info = $mod_refill->getOrderInfo(['order_id' => $order_id]);
  420. $chname = $refill_info['channel_name'];
  421. $card_type = intval($refill_info['card_type']);
  422. $pthis = $this;
  423. $finder = function ($chname, $card_type) use($pthis)
  424. {
  425. if ($card_type == mtopcard\SinopecCard || $card_type == mtopcard\PetroChinaCard) {
  426. $providers = $pthis->mOilProvider;
  427. } else {
  428. $providers = $pthis->mPhoneProvider;
  429. }
  430. foreach ($providers as $provider) {
  431. if ($chname == $provider->name()) {
  432. return $provider;
  433. }
  434. }
  435. return NULL;
  436. };
  437. $provider = $finder($chname,$card_type);
  438. [$state, $err] = $provider->query($refill_info);
  439. if($state === true) {
  440. $mod_refill->edit($order_id, ['notify_time' => time(), 'notify_state' => 1]);
  441. QueueClient::push("NotifyMerchantComplete", ['order_id' => $order_id]);
  442. return true;
  443. }
  444. else {
  445. return false;
  446. }
  447. }
  448. private function body($state, $refill_info, $mch_info)
  449. {
  450. $params = [
  451. "mchid" => $refill_info['mchid'],
  452. "order_sn" => $refill_info['mch_order'],
  453. "amount" => $refill_info['refill_amount'],
  454. "cardno" => $refill_info['card_no'],
  455. "trade_no" => $refill_info['order_sn'],
  456. "idcard" => $refill_info['idcard'] ?? "",
  457. "card_name" => $refill_info['card_name'] ?? "",
  458. "state" => $state];
  459. $secure_key = $mch_info['secure_key'];
  460. $sign = $this->sign($params, $secure_key);
  461. return [$params, $sign];
  462. }
  463. private function sign($params, $key)
  464. {
  465. ksort($params);
  466. $body = "";
  467. $i = 0;
  468. foreach ($params as $k => $v) {
  469. if (false === $this->check_empty($v) && "@" != substr($v, 0, 1)) {
  470. if ($i == 0) {
  471. $body .= "{$k}" . "=" . urlencode($v);
  472. } else {
  473. $body .= "&" . "{$k}" . "=" . urlencode($v);
  474. }
  475. $i++;
  476. }
  477. }
  478. $body .= "&key={$key}";
  479. return md5($body);
  480. }
  481. private function check_empty($value)
  482. {
  483. if (!isset($value))
  484. return true;
  485. if ($value === null)
  486. return true;
  487. if (trim($value) === "")
  488. return true;
  489. return false;
  490. }
  491. }