RefillFactory.php 18 KB

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