仰望星辰工作室

better-staridc-MNBT

Z zfhsh first commit 2 个月前
1<?php
2/**
3 * zjmfmanager_reserve 插件 - 上游服务层
4 *
5 * 封装对魔方财务(cube_finance)的所有上游调用,供订单开通、主机操作、
6 * 商品同步、升级使用。所有方法均按供应商行($supplier)路由,
7 * 每个供应商独立客户端实例与独立 JWT 缓存(runtime/cache/s{id})。
8 * 上游响应字段因版本/定制站存在差异,解析均为防御式,
9 * 联调时以实际站点返回为准(见 PRD §3.3 / §12 Q1、Q3)。
10 */
11
12if (!defined('IN_CRONLITE')) {
13 exit;
14}
15
16require_once __DIR__ . '/CubeFinanceClient.php';
17
18/**
19 * 开通流程(按魔方财务官方 API 文档,前台会员中心接口,无 v1 前缀):
20 * 1. POST /cart/add_to_shop 添加产品至购物车(pid/billingcycle/qty/host/password)→ data.i 购物车位置
21 * 2. POST /cart/settle 结算购物车(pos[]=[i]、checkout=1 直接结算)→ data.invoiceid
22 * 3. POST /apply_credit 使用余额支付账单(invoiceid、use_credit=1、enough=1)
23 * 4. GET /invoices/{id} 账单详情,取 host[].num 得到主机 ID(产品 ID)
24 * 5. GET /host/header 查询主机信息(username/password/productname/nextduedate)
25 * 接口与响应字段以官方文档为准(docs/zjmf-api-doc/zjmf-api.md);
26 * 上游版本/定制站存在差异时,失败信息会带出上游返回详情便于联调适配(见 PRD §3.3 / §12 Q1)。
27 */
28
29class ZjmfUpstream
30{
31 /**
32 * 创建上游客户端(按供应商行);连接信息不完整返回 null。
33 * JWT 缓存目录按供应商 ID 隔离,避免多供应商凭证串扰。
34 *
35 * @param array|null $supplier MN_plugin_zjmf_supplier 行
36 * @param int|null $timeout 覆盖超时秒数(null 用供应商配置 api_timeout)
37 * @return CubeFinanceClient|null
38 */
39 public static function client($supplier, $timeout = null)
40 {
41 if (!is_array($supplier)) {
42 return null;
43 }
44 $apiUrl = (string)($supplier['api_url'] ?? '');
45 $username = (string)($supplier['api_username'] ?? '');
46 $password = (string)($supplier['api_password'] ?? '');
47 if ($apiUrl === '' || $username === '' || $password === '') {
48 return null;
49 }
50 $t = (int)($supplier['api_timeout'] ?? 30);
51 $t = $t > 0 ? $t : 30;
52 if ($timeout !== null && (int)$timeout > 0) {
53 $t = (int)$timeout;
54 }
55 $supplierId = (int)($supplier['id'] ?? 0);
56 $cacheDir = mnbt_plugin_path('zjmfmanager_reserve')
57 . 'runtime/cache/s' . $supplierId;
58 // JWT 缓存目录防 Web 直接访问:.htaccess 拒绝 + 空 index.html 防目录列举
59 if (!is_dir($cacheDir)) {
60 @mkdir($cacheDir, 0755, true);
61 }
62 $ht = $cacheDir . '/.htaccess';
63 if (!is_file($ht)) {
64 @file_put_contents($ht, "Deny from all\n");
65 }
66 $ix = $cacheDir . '/index.html';
67 if (!is_file($ix)) {
68 @file_put_contents($ix, '');
69 }
70 // 解密 API 密钥:新数据为 v2: AES 密文;历史数据为明文直取
71 // (不经 authcode 解密,避免把明文误当乱码密文解出无效值)
72 $apiPassword = strpos($password, 'v2:') === 0 ? zjmf_decrypt($password) : $password;
73 return new CubeFinanceClient([
74 'url' => $apiUrl,
75 'username' => $username,
76 'password' => $apiPassword,
77 'timeout' => $t,
78 'cache_dir' => $cacheDir,
79 // TODO: install.sql 供应商表暂无 verify_ssl 配置字段,先默认强制
80 // 校验证书;后续加字段后改为按供应商配置读取(默认 true)
81 'verify_ssl' => true,
82 ]);
83 }
84
85 /** 连通性测试(登录 + 商品列表),按供应商。 */
86 public static function testConnection($supplier)
87 {
88 $client = self::client($supplier);
89 if (!$client) {
90 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
91 }
92 return $client->testConnection();
93 }
94
95 /**
96 * 查询供应商上游账户余额(GET /index → data.client[].credit)。
97 * user_info 的 data.credit 是信用卡信息而非余额,故优先取首页客户数据,
98 * 失败再兜底 user_info。
99 *
100 * @param array $supplier 供应商行
101 * @return array ['ok'=>bool, 'msg'=>string, 'credit'=>string, 'currency'=>string]
102 */
103 public static function balance($supplier)
104 {
105 $client = self::client($supplier);
106 if (!$client) {
107 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
108 }
109 try {
110 $res = $client->homeIndex();
111 if (self::respOk($res)) {
112 $clients = $res['data']['client'] ?? [];
113 // 兼容单对象(非数组)形态
114 if (is_array($clients) && !isset($clients[0]) && ($clients['credit'] ?? '') !== '') {
115 return [
116 'ok' => true,
117 'msg' => 'ok',
118 'credit' => (string)$clients['credit'],
119 'currency' => (string)($clients['currency'] ?? ''),
120 ];
121 }
122 if (is_array($clients)) {
123 foreach ($clients as $c) {
124 if (is_array($c) && ($c['credit'] ?? '') !== '') {
125 return [
126 'ok' => true,
127 'msg' => 'ok',
128 'credit' => (string)$c['credit'],
129 'currency' => (string)($c['currency'] ?? ''),
130 ];
131 }
132 }
133 }
134 }
135 // 兜底:GET /user_info(部分版本 credit 即余额)
136 $res = $client->userInfo();
137 if (!self::respOk($res)) {
138 return ['ok' => false, 'msg' => self::respErr('获取上游账户信息失败', $res)];
139 }
140 $data = $res['data'] ?? [];
141 $credit = $data['credit'] ?? null;
142 if ($credit === null || $credit === '') {
143 $credit = $data['credit_balance'] ?? null; // 兼容字段
144 }
145 return [
146 'ok' => true,
147 'msg' => 'ok',
148 'credit' => (string)$credit,
149 'currency' => (string)($data['currency'] ?? ''),
150 ];
151 } catch (CubeFinanceException $e) {
152 return ['ok' => false, 'msg' => $e->getMessage()];
153 }
154 }
155
156 /* ============================================================
157 * 商品同步
158 * ============================================================ */
159
160 /** 上游商品列表(同步弹窗拉取,不做入库)。 */
161 public static function upstreamProducts($supplier)
162 {
163 $client = self::client($supplier);
164 if (!$client) {
165 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
166 }
167 try {
168 $res = $client->productList();
169 if (($res['status'] ?? 0) != 200) {
170 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '上游返回异常')];
171 }
172 return ['ok' => true, 'data' => $res['data'] ?? []];
173 } catch (CubeFinanceException $e) {
174 return ['ok' => false, 'msg' => $e->getMessage()];
175 }
176 }
177
178 /**
179 * 按供应商同步单个商品(手动添加后拉取代理价与各周期价格)。
180 * 幂等:按 supplier_id + up_product_id upsert。
181 *
182 * @param array $supplier 供应商行
183 * @param int $upProductId 上游商品 ID
184 * @return array ['ok'=>bool, 'msg'=>string]
185 */
186 public static function syncOneProductBySupplier($supplier, $upProductId)
187 {
188 @set_time_limit(0);
189 $client = self::client($supplier);
190 if (!$client) {
191 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
192 }
193 try {
194 $upId = (int)$upProductId;
195 // 优先从列表取真实条目(含 billingcycle/price 等周期信息,同 pid 可能每周期一行),失败再退回详情
196 $rows = [];
197 $currency = '';
198 try {
199 $res = $client->productList();
200 if (($res['status'] ?? 0) == 200 && !empty($res['data']['list'])) {
201 $currency = (string)($res['data']['currency_code'] ?? '');
202 foreach ($res['data']['list'] as $row) {
203 if ((int)($row['id'] ?? 0) === $upId) {
204 $rows[] = $row;
205 }
206 }
207 }
208 } catch (CubeFinanceException $e) {
209 // 列表失败忽略,退回详情
210 }
211 if ($rows === []) {
212 $detail = $client->productDetail($upId, 'agent');
213 $prod = $detail['data']['product'] ?? ($detail['data'] ?? []);
214 $rows = [[
215 'id' => $upId,
216 'name' => (string)($prod['name'] ?? ''),
217 'description' => (string)($prod['description'] ?? ''),
218 ]];
219 $currency = (string)($detail['data']['currency_code'] ?? $currency);
220 }
221 $ok = self::syncOneProduct(
222 $client, (int)($supplier['id'] ?? 0), $upId, $rows, $currency
223 );
224 return $ok
225 ? ['ok' => true, 'msg' => '商品价格已同步']
226 : ['ok' => false, 'msg' => '商品写入失败'];
227 } catch (CubeFinanceException $e) {
228 return ['ok' => false, 'msg' => $e->getMessage()];
229 }
230 }
231
232 /** 上游商品详情(代理价),供手动添加 / 单品刷新。 */
233 public static function productDetail($supplier, $upProductId)
234 {
235 $client = self::client($supplier);
236 if (!$client) {
237 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
238 }
239 try {
240 $res = $client->productDetail((int)$upProductId, 'agent');
241 if (($res['status'] ?? 0) != 200) {
242 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '获取商品详情失败')];
243 }
244 return ['ok' => true, 'data' => $res['data'] ?? []];
245 } catch (CubeFinanceException $e) {
246 return ['ok' => false, 'msg' => $e->getMessage()];
247 }
248 }
249
250 /**
251 * 同步商品(按供应商,可选勾选商品 ID 列表)。
252 * 列表 + 代理价详情 + 各周期试算价。
253 * 幂等:按 supplier_id + up_product_id upsert,
254 * 不覆盖管理员加价/上架/排序。$upIds 为空表示同步全部。
255 *
256 * @param array $supplier 供应商行
257 * @param array $upIds 勾选的上游商品 ID 列表
258 * @return array ['ok'=>bool, 'msg'=>string]
259 */
260 public static function syncProducts($supplier, array $upIds = [])
261 {
262 @set_time_limit(0);
263 $client = self::client($supplier);
264 if (!$client) {
265 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
266 }
267 $supplierId = (int)($supplier['id'] ?? 0);
268 try {
269 $res = $client->productList();
270 if (($res['status'] ?? 0) != 200 || empty($res['data']['list'])) {
271 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '上游返回异常')];
272 }
273 $currency = (string)($res['data']['currency_code'] ?? '');
274 $count = 0;
275 $fail = 0;
276 $skip = 0;
277 // 上游列表可能每个周期一行(同 pid 多行),按 pid 分组后合并周期,避免相互覆盖
278 $grouped = [];
279 foreach ($res['data']['list'] as $item) {
280 $upId = (int)($item['id'] ?? 0);
281 if ($upId <= 0) {
282 continue;
283 }
284 if ($upIds && !in_array($upId, $upIds, true)) {
285 $skip++;
286 continue;
287 }
288 $grouped[$upId][] = $item;
289 }
290 foreach ($grouped as $upId => $rows) {
291 if (self::syncOneProduct($client, $supplierId, (int)$upId, $rows, $currency)) {
292 $count++;
293 } else {
294 $fail++;
295 }
296 }
297 $msg = "同步完成:更新 {$count} 个,失败 {$fail} 个";
298 if ($skip > 0) {
299 $msg .= ",跳过 {$skip} 个";
300 }
301 return ['ok' => true, 'msg' => $msg];
302 } catch (CubeFinanceException $e) {
303 return ['ok' => false, 'msg' => $e->getMessage()];
304 }
305 }
306
307 /** 同步单个商品(rows 为同一 pid 的列表行,可能每周期一行)。 */
308 protected static function syncOneProduct($client, $supplierId, $upId, array $rows, $currency)
309 {
310 global $DB, $date;
311 $now = $date ?: date('Y-m-d H:i:s');
312 $item = $rows[0] ?? [];
313
314 // 代理价(详情接口,失败回退列表项 price)
315 $agentCents = 0;
316 $detail = null;
317 try {
318 $detail = $client->productDetail($upId, 'agent');
319 $prod = $detail['data']['product'] ?? ($detail['data'] ?? []);
320 $agentCents = self::toCents(self::pickPrice($prod));
321 } catch (CubeFinanceException $e) {
322 // 详情失败不致命,仅代理价缺失
323 }
324 if ($agentCents <= 0) {
325 foreach ($rows as $row) {
326 $agentCents = self::itemPrice($row);
327 if ($agentCents > 0) {
328 break;
329 }
330 }
331 }
332
333 // 各周期价:列表行 → 详情 → 购物车算价,逐级补充合并(列表常只有单周期字段)
334 $cycles = [];
335 foreach ($rows as $row) {
336 foreach (self::parseItemCycles($row) as $k => $entry) {
337 if (!isset($cycles[$k])) {
338 $cycles[$k] = $entry;
339 }
340 }
341 }
342 if ($detail) {
343 foreach (self::parseDetailCycles($detail) as $k => $entry) {
344 if (!isset($cycles[$k])) {
345 $cycles[$k] = $entry;
346 }
347 }
348 }
349 // 探测购物车配置接口:一次请求拿到全部可选周期的真实 billingcycle 键与价格。
350 // 列表/详情已有周期保持不变;仅补充缺失周期,并给缺失 up_cycle 的条目补上真实键。
351 $probedKeys = [];
352 foreach (self::probeCycles($client, $upId, $detail) as $key => $cfg) {
353 $entry = self::cycleEntry($key, (int)($cfg['price_cents'] ?? 0), (string)($cfg['name'] ?? ''));
354 $k = $entry['cycle'];
355 $probedKeys[$k] = (string)$key;
356 if (isset($cycles[$k])) {
357 if ((string)($cycles[$k]['up_cycle'] ?? '') === '') {
358 $cycles[$k]['up_cycle'] = (string)$key;
359 }
360 continue;
361 }
362 if ($entry['agent_price_cents'] <= 0) {
363 continue;
364 }
365 $cycles[$k] = $entry;
366 }
367 // 兜底:购物车算价补充缺失周期。先探测一个周期,失败即放弃该商品试算
368 //(避免对每个缺失周期都发请求,商品多时同步被拖垮)
369 $trialOn = false;
370 foreach (zjmf_cycles() as $cycle => $cfg) {
371 if (isset($cycles[$cycle])) {
372 continue;
373 }
374 if (!$trialOn) {
375 $probe = self::trialPrice($client, $upId, $cycle);
376 if ($probe <= 0) {
377 break;
378 }
379 $trialOn = true;
380 $cycles[$cycle] = [
381 'cycle' => $cycle,
382 'up_cycle' => $probedKeys[$cycle] ?? strtolower($cycle),
383 'name' => $cfg['name'],
384 'agent_price_cents' => $probe,
385 ];
386 continue;
387 }
388 $price = self::trialPrice($client, $upId, $cycle);
389 if ($price > 0) {
390 $cycles[$cycle] = [
391 'cycle' => $cycle,
392 'up_cycle' => $probedKeys[$cycle] ?? strtolower($cycle),
393 'name' => $cfg['name'],
394 'agent_price_cents' => $price,
395 ];
396 }
397 }
398 $cyclesJson = json_encode(array_values($cycles), JSON_UNESCAPED_UNICODE);
399
400 $existing = zjmf_product_get_by_up($supplierId, $upId);
401 if ($existing) {
402 // 同步不覆盖管理员手动设置的售价(override)
403 $oldCycles = zjmf_product_cycles($existing);
404 $changed = false;
405 foreach ($cycles as $k => &$cfg) {
406 if (isset($oldCycles[$k]['override']) && (int)$oldCycles[$k]['override'] > 0) {
407 $cfg['override'] = (int)$oldCycles[$k]['override'];
408 $cfg['price_cents'] = (int)$oldCycles[$k]['override'];
409 $changed = true;
410 }
411 }
412 unset($cfg);
413 if ($changed) {
414 $cyclesJson = json_encode(array_values($cycles), JSON_UNESCAPED_UNICODE);
415 }
416 }
417 if ($existing) {
418 // 重复同步仅刷新价格/周期,不覆盖本地已修改的名称与简介
419 $ok = $DB->query_prepare(
420 "UPDATE MN_plugin_zjmf_product
421 SET currency=?, agent_price_cents=?, cycles=?, synced_at=?, updated_at=?
422 WHERE id=?",
423 [
424 $currency,
425 $agentCents,
426 $cyclesJson,
427 $now,
428 $now,
429 (int)$existing['id'],
430 ]
431 );
432 } else {
433 $ok = $DB->query_prepare(
434 "INSERT INTO MN_plugin_zjmf_product
435 (supplier_id, up_product_id, name, description, currency,
436 agent_price_cents, cycles, status, sort, synced_at,
437 created_at, updated_at)
438 VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
439 [
440 $supplierId,
441 $upId,
442 (string)($item['name'] ?? ''),
443 zjmf_render_description((string)($item['description'] ?? '')),
444 $currency,
445 $agentCents,
446 $cyclesJson,
447 0,
448 50,
449 $now,
450 $now,
451 $now,
452 ]
453 );
454 }
455 if (!$ok) {
456 return false;
457 }
458 // 重算本地售价(保持已有加价配置不变)
459 $targetId = $existing ? (int)$existing['id'] : self::lastProductId($supplierId);
460 if ($targetId > 0) {
461 zjmf_product_recalc_price($targetId);
462 }
463 return true;
464 }
465
466 /** 取指定供应商内最近插入的商品 ID。 */
467 protected static function lastProductId($supplierId)
468 {
469 global $DB;
470 $row = $DB->get_row_prepare(
471 "SELECT id FROM MN_plugin_zjmf_product
472 WHERE supplier_id=? ORDER BY id DESC LIMIT 1",
473 [(int)$supplierId]
474 );
475 return $row ? (int)$row['id'] : 0;
476 }
477
478 /* ============================================================
479 * 开通(代理商直通)
480 * ============================================================ */
481
482 /**
483 * 上游开通主机(按订单所属供应商路由)。
484 * 流程:add_to_shop 加购 → settle 结算 → apply_credit 余额支付 → 账单详情取主机 ID → host/header 查信息。
485 * 端点与响应字段以官方文档为准(Q1),调整仅需改动本方法。
486 *
487 * @param array $order MN_plugin_zjmf_order 行
488 * @param array $supplier MN_plugin_zjmf_supplier 行
489 * @return array ['ok'=>bool, 'msg'=>string, 'up_order_id'=>int, 'up_host_id'=>int,
490 * 'username'=>string, 'password'=>string, 'name'=>string,
491 * 'renew_date'=>string]
492 */
493 public static function purchase($order, $supplier)
494 {
495 $client = self::client($supplier);
496 if (!$client) {
497 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
498 }
499
500 $upProductId = (int)($order['up_product_id'] ?? 0);
501 $cycle = (string)($order['cycle'] ?? '');
502 $extra = json_decode((string)($order['order_params'] ?? ''), true);
503 if (!is_array($extra)) {
504 $extra = [];
505 }
506
507 try {
508 // 0. 清空购物车:该版本 settle(checkout=1) 会结算整辆购物车,
509 // 若残留历史测试商品会把多件一起结算开通(曾实测一次开出多台机器)。
510 // 清空失败时确认购物车为空或仅含本次商品才继续,否则中断开通,
511 // 避免残留项被一起结算。
512 try {
513 $client->cartClear();
514 } catch (CubeFinanceException $e) {
515 if (!self::cartSafeForSettle($client, $upProductId)) {
516 return ['ok' => false, 'msg' => '上游购物车清空失败且无法确认购物车为空,'
517 . '为避免残留商品被一起结算已中断本次开通:' . $e->getMessage()];
518 }
519 }
520
521 // 1. 添加产品至购物车(官方:POST /cart/add_to_shop)→ data.i 购物车位置
522 $upCycle = self::upstreamCycle((int)($order['supplier_id'] ?? 0), $upProductId, $cycle);
523 $genHost = (string)($extra['host'] ?? '') !== ''
524 ? (string)$extra['host'] : self::randHost();
525 $addParams = [
526 'pid' => $upProductId,
527 'billingcycle' => $upCycle,
528 'qty' => 1,
529 'host' => $genHost,
530 'password' => (string)($extra['password'] ?? self::randPassword()),
531 ];
532 foreach (['configoption', 'customfield', 'serverid', 'os', 'currencyid'] as $k) {
533 if (isset($extra[$k]) && $extra[$k] !== '') {
534 $addParams[$k] = $extra[$k];
535 }
536 }
537 // 缺少 currencyid / configoption 时探测上游默认配置:
538 // 有配置项的商品必须传 configoption(子项ID/数量),否则计价失败报
539 // "此周期未配置价格或价格错误,请重新选择周期"(实测上游前台抓包确认)
540 if (!isset($addParams['currencyid']) || !isset($addParams['configoption'])) {
541 $cfgDefaults = self::probeConfigDefaults($client, $upProductId);
542 if (!isset($addParams['currencyid']) && !empty($cfgDefaults['currencyid'])) {
543 $addParams['currencyid'] = (int)$cfgDefaults['currencyid'];
544 }
545 if (!isset($addParams['configoption']) && !empty($cfgDefaults['configoption'])) {
546 $addParams['configoption'] = $cfgDefaults['configoption'];
547 }
548 }
549 $res = $client->post('cart/add_to_shop', $addParams);
550 if (!self::respOk($res)) {
551 // 上游拒绝(多为"此周期未配置价格"):探测商品真实周期键,命中则重试一次,
552 // 并把正确键写回商品周期(后续购买直接可用)
553 $avail = [];
554 if (self::isCyclePriceError($res)) {
555 $avail = self::probeCycles($client, $upProductId);
556 $matched = self::matchUpCycle($cycle, $avail);
557 if ($matched !== '' && $matched !== $upCycle) {
558 $addParams['billingcycle'] = $matched;
559 self::persistUpCycle(
560 (int)($order['supplier_id'] ?? 0),
561 $upProductId,
562 $cycle,
563 $matched
564 );
565 $upCycle = $matched;
566 $res = $client->post('cart/add_to_shop', $addParams);
567 }
568 }
569 if (!self::respOk($res)) {
570 $msg = self::respErr('上游添加购物车失败(周期: ' . $upCycle . ')', $res);
571 if ($avail !== []) {
572 $msg .= self::formatAvailable($avail);
573 }
574 return ['ok' => false, 'msg' => $msg];
575 }
576 }
577 $position = self::findPosition($res);
578 if ($position < 0) {
579 // 该版本 add_to_shop 不返回位置(响应仅 status/msg/is_aff):
580 // 从购物车数据(GET /cart/get_shop_data,数组键/序号即位置 i)定位刚添加的产品
581 $position = self::cartPosition($client, $upProductId, $upCycle);
582 }
583 if ($position < 0) {
584 $raw = json_encode($res['data'] ?? $res, JSON_UNESCAPED_UNICODE);
585 return ['ok' => false, 'msg' => '上游添加购物车后无法定位购物车位置(响应: '
586 . self::truncate((string)$raw, 300) . ')'];
587 }
588
589 // 2. 结算购物车(官方:POST /cart/settle,checkout=1 直接结算)→ data.invoiceid
590 $checkout = $client->post('cart/settle', [
591 'pos[]' => [$position],
592 'checkout' => 1,
593 ]);
594 if (!self::respOk($checkout)) {
595 return ['ok' => false, 'msg' => self::respErr('上游结算失败', $checkout)];
596 }
597 $checkoutData = is_array($checkout['data'] ?? null) ? $checkout['data'] : [];
598 $invoiceId = self::findId($checkoutData);
599 $hostId = self::findHostId($checkoutData);
600
601 // 3. 使用余额支付账单(官方:POST /apply_credit)。
602 // 仅当账单确认已支付且已生成主机记录时才跳过支付,防止把结算
603 // 响应中其他 ID 误判为主机 ID 而漏付;确认失败则正常走支付。
604 $skipPay = false;
605 if ($invoiceId > 0 && $hostId <= 0) {
606 $paid = self::invoiceInfo($client, $invoiceId, 1);
607 if ($paid && self::isPaidStatus($paid['status']) && (int)$paid['host_id'] > 0) {
608 $skipPay = true;
609 $hostId = (int)$paid['host_id'];
610 }
611 }
612 if ($invoiceId > 0 && !$skipPay) {
613 $credit = $client->post('apply_credit', [
614 'invoiceid' => $invoiceId,
615 'use_credit' => 1,
616 'enough' => 1,
617 ]);
618 if (!self::respOk($credit)) {
619 // 账单可能已被自动扣款,确认已支付后再继续
620 $info = self::invoiceInfo($client, $invoiceId, 1);
621 if (!$info || !self::isPaidStatus($info['status'])) {
622 // 支付未确认:明确失败(订单将被标 failed),不得继续当作开通成功
623 return ['ok' => false, 'msg' => self::respErr('上游余额支付失败', $credit)];
624 }
625 }
626 }
627
628 // 4. 账单已支付,轮询账单详情取主机 ID(主机创建可能异步)
629 if ($hostId <= 0 && $invoiceId > 0) {
630 $info = self::invoiceInfo($client, $invoiceId);
631 if ($info) {
632 $hostId = (int)$info['host_id'];
633 }
634 }
635
636 // 5. 拿到主机 ID → 查询主机信息(官方:GET /host/header)
637 if ($hostId > 0) {
638 $header = self::safeHostHeader($client, $hostId);
639 return [
640 'ok' => true,
641 'msg' => '开通成功',
642 'up_order_id' => $invoiceId,
643 'up_host_id' => $hostId,
644 // 本次开通使用的本地生成主机标识(host 参数,供确定性回填)
645 'host' => $genHost,
646 'username' => $header['username'],
647 'password' => $header['password'],
648 'name' => $header['name'],
649 'renew_date' => $header['renew_date'],
650 ];
651 }
652
653 // 6. 订单已创建/支付但未拿到主机:人工核对(不判失败,避免误退款)
654 return [
655 'ok' => true,
656 'msg' => '上游订单已创建,但未返回主机 ID,请到上游后台核对',
657 'up_order_id' => $invoiceId,
658 'up_host_id' => 0,
659 // 同上,保存主机标识供回填确定性匹配
660 'host' => $genHost,
661 'username' => '',
662 'password' => '',
663 'name' => (string)($order['product_name'] ?? ''),
664 'renew_date' => '',
665 ];
666 } catch (CubeFinanceException $e) {
667 $detail = '';
668 if (is_array($e->response) && !empty($e->response['body'])) {
669 $detail = '(响应: ' . self::truncate((string)$e->response['body'], 300) . ')';
670 }
671 return ['ok' => false, 'msg' => $e->getMessage() . $detail];
672 }
673 }
674
675 /* ============================================================
676 * 主机查询与操作
677 * ============================================================ */
678
679 /** 拉取上游我的主机列表(GET host/list),按供应商。用户端读取用短超时,避免拖垮页面。 */
680 public static function hostList($supplier, array $extra = [])
681 {
682 $client = self::client($supplier, 8);
683 if (!$client) {
684 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
685 }
686 try {
687 $res = $client->hostList($extra);
688 if (!self::respOk($res)) {
689 return ['ok' => false, 'msg' => self::respErr('获取上游主机列表失败', $res)];
690 }
691 return ['ok' => true, 'data' => $res['data'] ?? []];
692 } catch (CubeFinanceException $e) {
693 return ['ok' => false, 'msg' => $e->getMessage()];
694 }
695 }
696
697 /** 主机头信息(状态/账号/到期),按主机所属供应商。用户端读取用短超时,避免拖垮页面。 */
698 public static function hostInfo($supplier, $upHostId)
699 {
700 $client = self::client($supplier, 8);
701 if (!$client) {
702 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
703 }
704 // host/product 优先(状态等字段更稳定),失败回退 host/header
705 foreach (['hostProduct', 'hostHeader'] as $method) {
706 try {
707 $res = $client->{$method}((int)$upHostId);
708 if (($res['status'] ?? 0) == 200) {
709 $resData = $res['data'] ?? [];
710 $data = self::pickHostData($resData);
711 return [
712 'ok' => true,
713 'data' => $data,
714 'config_options' => isset($resData['config_options']) && is_array($resData['config_options'])
715 ? $resData['config_options'] : [],
716 'custom_fields' => isset($resData['custom_field_data']) && is_array($resData['custom_field_data'])
717 ? $resData['custom_field_data'] : [],
718 'dcim' => isset($resData['dcim']) && is_array($resData['dcim'])
719 ? $resData['dcim'] : [],
720 'status' => self::mapHostStatus($data),
721 ];
722 }
723 } catch (CubeFinanceException $e) {
724 // 尝试下一个端点
725 }
726 }
727 return ['ok' => false, 'msg' => '查询失败'];
728 }
729
730 /** 流量使用,按主机所属供应商。用户端读取用短超时,避免拖垮页面。 */
731 public static function hostTraffic($supplier, $upHostId)
732 {
733 $client = self::client($supplier, 8);
734 if (!$client) {
735 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
736 }
737 try {
738 $res = $client->hostTrafficUsage((int)$upHostId);
739 if (($res['status'] ?? 0) != 200) {
740 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '查询失败')];
741 }
742 return ['ok' => true, 'data' => $res['data'] ?? []];
743 } catch (CubeFinanceException $e) {
744 return ['ok' => false, 'msg' => $e->getMessage()];
745 }
746 }
747
748 /** 主机操作(provision/default,func 由调用方传入)。 */
749 public static function hostAction($supplier, $upHostId, $func, $extra = [])
750 {
751 $client = self::client($supplier);
752 if (!$client) {
753 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
754 }
755 try {
756 $params = array_merge([
757 'id' => (int)$upHostId,
758 'func' => $func,
759 'is_api' => 1,
760 ], $extra);
761 $res = $client->provisionDefault($params);
762 if (($res['status'] ?? 0) == 200) {
763 return ['ok' => true, 'msg' => (string)($res['msg'] ?? '操作成功')];
764 }
765 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '操作失败')];
766 } catch (CubeFinanceException $e) {
767 return ['ok' => false, 'msg' => $e->getMessage()];
768 }
769 }
770
771 /**
772 * DCIM 综合信息(交换机端口 / 电源状态 / 重装次数 / 任务进度)。
773 * 单项失败不致命,仅用于展示;非 DCIM 产品会全部为空。
774 */
775 public static function hostDcimInfo($supplier, $upHostId)
776 {
777 // 短超时,避免叠加请求拖慢详情页
778 $client = self::client($supplier, 5);
779 if (!$client) {
780 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
781 }
782 $out = [
783 'detail' => [],
784 'power' => '',
785 'power_msg' => '',
786 'reinstall' => [],
787 'task' => [],
788 ];
789 $tasks = [
790 'detail' => function () use ($client, $upHostId) { return $client->dcimDetail((int)$upHostId); },
791 'power' => function () use ($client, $upHostId) { return $client->dcimPowerStatus((int)$upHostId); },
792 'reinstall' => function () use ($client, $upHostId) { return $client->dcimCheckReinstall((int)$upHostId); },
793 'task' => function () use ($client, $upHostId) { return $client->dcimReinstallStatus((int)$upHostId); },
794 ];
795 foreach ($tasks as $k => $fn) {
796 try {
797 $res = $fn();
798 if (($res['status'] ?? 0) == 200) {
799 $d = $res['data'] ?? [];
800 if ($k === 'power') {
801 $out['power'] = (string)($d['power'] ?? '');
802 $out['power_msg'] = (string)($d['msg'] ?? '');
803 } else {
804 $out[$k] = $d;
805 }
806 }
807 } catch (CubeFinanceException $e) {
808 // 单项失败忽略
809 }
810 }
811 return ['ok' => true, 'data' => $out];
812 }
813
814 /** DCIM 专用操作(rescue/bmc/cancel_task/reinstall/crack_pass 等)。 */
815 public static function hostDcimAction($supplier, $upHostId, $action, $extra = [])
816 {
817 $client = self::client($supplier);
818 if (!$client) {
819 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
820 }
821 try {
822 $res = $client->dcimAction($action, (int)$upHostId, $extra);
823 if (($res['status'] ?? 0) == 200) {
824 return ['ok' => true, 'msg' => (string)($res['msg'] ?? '操作成功')];
825 }
826 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '操作失败')];
827 } catch (CubeFinanceException $e) {
828 return ['ok' => false, 'msg' => $e->getMessage()];
829 }
830 }
831
832 /** 重装可选系统列表(GET host/dedicatedserver),按上游主机 ID 获取。 */
833 public static function hostDedicatedOs($supplier, $upHostId)
834 {
835 $client = self::client($supplier, 8);
836 if (!$client) {
837 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
838 }
839 try {
840 $res = $client->hostDedicatedServer((int)$upHostId);
841 if (($res['status'] ?? 0) != 200) {
842 error_log('[zjmfmanager_reserve] hostDedicatedServer failed: '
843 . 'host_id=' . (int)$upHostId . ' status=' . ($res['status'] ?? '')
844 . ' msg=' . ($res['msg'] ?? ''));
845 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '获取系统列表失败')];
846 }
847 $data = $res['data'] ?? [];
848 return [
849 'ok' => true,
850 'os_list' => is_array($data['cloud_os'] ?? null) ? $data['cloud_os'] : [],
851 'groups' => is_array($data['cloud_os_group'] ?? null) ? $data['cloud_os_group'] : [],
852 ];
853 } catch (CubeFinanceException $e) {
854 error_log('[zjmfmanager_reserve] hostDedicatedServer exception: ' . $e->getMessage());
855 return ['ok' => false, 'msg' => $e->getMessage()];
856 }
857 }
858
859 /** 只读获取升级选项(配置项或可升降级产品列表)。 */
860 public static function upgradeOptions($supplier, $upHostId, $kind)
861 {
862 $client = self::client($supplier);
863 if (!$client) {
864 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
865 }
866 try {
867 $res = $kind === 'product'
868 ? $client->upgradeProduct((int)$upHostId)
869 : $client->upgradeIndex((int)$upHostId);
870 if (($res['status'] ?? 0) != 200) {
871 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '获取升级选项失败')];
872 }
873 return ['ok' => true, 'data' => $res['data'] ?? []];
874 } catch (CubeFinanceException $e) {
875 return ['ok' => false, 'msg' => $e->getMessage()];
876 }
877 }
878
879 /**
880 * 试算升级差额(GET 页面端点,只读不提交)。
881 * 端点联调确认 Q1;selection 结构:
882 * config → ['configoption' => [option_id => value]]
883 * product → ['newpid' => id, 'billingcycle' => cycle]
884 *
885 * @param array $supplier 供应商行
886 * @param string $kind config|product
887 * @param int $upHostId 上游主机 ID
888 * @param array $selection
889 * @return array ['ok'=>bool, 'msg'=>string, 'price_cents'=>int, 'data'=>array]
890 */
891 public static function upgradePreview($supplier, $kind, $upHostId, $selection)
892 {
893 $client = self::client($supplier);
894 if (!$client) {
895 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
896 }
897 try {
898 $path = $kind === 'product'
899 ? 'upgrade/upgrade_product_page'
900 : 'upgrade/upgrade_config_page';
901 $params = array_merge(
902 ['hid' => (int)$upHostId, 'price_basis' => 'agent'],
903 $selection
904 );
905 $res = $client->get($path, $params);
906 if (($res['status'] ?? 0) != 200) {
907 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '试算失败')];
908 }
909 return [
910 'ok' => true,
911 'msg' => (string)($res['msg'] ?? ''),
912 'price_cents' => self::parseTrialPrice($res),
913 'data' => is_array($res['data'] ?? null) ? $res['data'] : [],
914 ];
915 } catch (CubeFinanceException $e) {
916 return ['ok' => false, 'msg' => $e->getMessage()];
917 }
918 }
919
920 /**
921 * 提交升级(确认,POST 端点)。
922 * 调用方需先扣款;提交失败由调用方负责退款。
923 *
924 * @param array $supplier 供应商行
925 * @param string $kind config|product
926 * @param int $upHostId 上游主机 ID
927 * @param array $selection
928 * @return array ['ok'=>bool, 'msg'=>string, 'price_cents'=>int,
929 * 'up_order_id'=>int, 'up_host_id'=>int]
930 */
931 public static function upgradeSubmit($supplier, $kind, $upHostId, $selection)
932 {
933 $client = self::client($supplier);
934 if (!$client) {
935 return ['ok' => false, 'msg' => '供应商连接信息不完整'];
936 }
937 try {
938 $params = array_merge(['hid' => (int)$upHostId], $selection);
939 $res = $kind === 'product'
940 ? $client->upgradeProductPost($params)
941 : $client->upgradeConfigPost($params);
942 if (($res['status'] ?? 0) != 200) {
943 return ['ok' => false, 'msg' => (string)($res['msg'] ?? '升级提交失败')];
944 }
945 $data = is_array($res['data'] ?? null) ? $res['data'] : [];
946 return [
947 'ok' => true,
948 'msg' => (string)($res['msg'] ?? '提交成功'),
949 'price_cents' => self::parseTrialPrice($res),
950 'up_order_id' => self::findId($data),
951 'up_host_id' => (int)$upHostId,
952 ];
953 } catch (CubeFinanceException $e) {
954 return ['ok' => false, 'msg' => $e->getMessage()];
955 }
956 }
957
958 /* ============================================================
959 * 响应解析辅助(防御式,字段以实际上游返回为准)
960 * ============================================================ */
961
962 /**
963 * 购物车算价:优先官方价格计算接口 POST /cart/get_total,
964 * 失败回退配置页 GET /cart/set_config。
965 */
966 protected static function trialPrice($client, $upId, $cycle)
967 {
968 $bc = strtolower($cycle);
969 try {
970 $price = self::parseTrialPrice($client->cartGetTotal([
971 'pid' => $upId,
972 'billingcycle' => $bc,
973 'qty' => 1,
974 ]));
975 if ($price > 0) {
976 return $price;
977 }
978 } catch (CubeFinanceException $e) {
979 // 忽略,走回退
980 }
981 try {
982 return self::parseTrialPrice($client->cartSetConfig([
983 'pid' => $upId,
984 'billingcycle' => $bc,
985 ]));
986 } catch (CubeFinanceException $e) {
987 return 0;
988 }
989 }
990
991 protected static function parseTrialPrice($res)
992 {
993 $data = $res['data'] ?? [];
994 if (!is_array($data)) {
995 return 0;
996 }
997 // 官方 get_total 响应:data.products[](signal_price 为单个产品周期费用)
998 if (isset($data['products']) && is_array($data['products'])) {
999 foreach ($data['products'] as $p) {
1000 if (!is_array($p)) {
1001 continue;
1002 }
1003 foreach (['signal_price', 'product_price', 'price_total', 'total', 'amount', 'subtotal'] as $k) {
1004 if (isset($p[$k]) && $p[$k] !== '' && $p[$k] !== null) {
1005 $c = self::toCents($p[$k]);
1006 if ($c > 0) {
1007 return $c;
1008 }
1009 }
1010 }
1011 }
1012 }
1013 foreach (['price', 'money', 'total', 'amount', 'subtotal', 'renewal_price'] as $k) {
1014 if (isset($data[$k]) && $data[$k] !== '' && $data[$k] !== null) {
1015 $c = self::toCents($data[$k]);
1016 if ($c > 0) {
1017 return $c;
1018 }
1019 }
1020 }
1021 foreach (['cart', 'order', 'product', 'host'] as $k) {
1022 if (isset($data[$k]) && is_array($data[$k])) {
1023 $c = self::toCents(self::pickPrice($data[$k]));
1024 if ($c > 0) {
1025 return $c;
1026 }
1027 }
1028 }
1029 return 0;
1030 }
1031
1032 /** 从数组取价格字段(元),取首个非空值。 */
1033 protected static function pickPrice($arr)
1034 {
1035 if (!is_array($arr)) {
1036 return 0;
1037 }
1038 foreach (['price', 'renew_price', 'setup_fee', 'total', 'amount'] as $k) {
1039 if (isset($arr[$k]) && $arr[$k] !== '' && $arr[$k] !== null) {
1040 return $arr[$k];
1041 }
1042 }
1043 return 0;
1044 }
1045
1046 /**
1047 * 从列表行提取各周期价格(分)。
1048 * 兼容三种结构(优先完整结构,避免单周期字段提前返回漏掉其余周期):
1049 * a. 完整周期:cycle/pricing 为数组或映射
1050 * b. 并行数组:billingcycle[] + billingcycle_price[](+ billingcycle_zh[])
1051 * c. 单周期:billingcycle + price + billingcycle_zh(仅作最后兜底)
1052 * 解析失败返回空数组。
1053 */
1054 protected static function parseItemCycles($item)
1055 {
1056 if (!is_array($item)) {
1057 return [];
1058 }
1059 // a. 完整周期结构:cycle/pricing 为数组或映射
1060 $raw = $item['cycle'] ?? $item['pricing'] ?? null;
1061 if (is_string($raw)) {
1062 $decoded = json_decode($raw, true);
1063 $raw = is_array($decoded) ? $decoded : null;
1064 }
1065 if (is_array($raw) && $raw !== []) {
1066 $out = self::parseCycleMap($raw);
1067 if ($out !== []) {
1068 return $out;
1069 }
1070 }
1071 // b. 并行数组结构:billingcycle[] + billingcycle_price[](v10 列表常见)
1072 $out = self::parseParallelCycles($item);
1073 if ($out !== []) {
1074 return $out;
1075 }
1076 // c. 单周期结构:billingcycle + price + billingcycle_zh
1077 $key = (string)($item['billingcycle'] ?? '');
1078 if ($key !== '') {
1079 $cents = self::toCents(self::pickPrice($item));
1080 if ($cents > 0) {
1081 $entry = self::cycleEntry($key, $cents, (string)($item['billingcycle_zh'] ?? ''));
1082 return [$entry['cycle'] => $entry];
1083 }
1084 }
1085 return [];
1086 }
1087
1088 /**
1089 * 并行数组结构:billingcycle[] + billingcycle_price[](+ billingcycle_zh[])。
1090 * 若任一数组缺失或长度不一致,返回空数组。
1091 */
1092 protected static function parseParallelCycles($item)
1093 {
1094 $keys = $item['billingcycle'] ?? null;
1095 $prices = $item['billingcycle_price'] ?? $item['billingcycleprices'] ?? null;
1096 if (!is_array($keys) || $keys === [] || !is_array($prices)) {
1097 return [];
1098 }
1099 $names = $item['billingcycle_zh'] ?? null;
1100 if (!is_array($names)) {
1101 $names = null;
1102 }
1103 $out = [];
1104 foreach ($keys as $i => $k) {
1105 $k = (string)$k;
1106 if ($k === '' || !isset($prices[$i])) {
1107 continue;
1108 }
1109 $cents = self::toCents($prices[$i]);
1110 if ($cents <= 0) {
1111 continue;
1112 }
1113 $name = $names ? (string)($names[$i] ?? '') : '';
1114 $entry = self::cycleEntry($k, $cents, $name);
1115 if (!isset($out[$entry['cycle']])) {
1116 $out[$entry['cycle']] = $entry;
1117 }
1118 }
1119 return $out;
1120 }
1121
1122 /**
1123 * 从商品详情响应提取各周期价格(分)。
1124 * 魔方财务详情接口将各周期价格放在 data.product.cycle(结构与列表项一致)。
1125 */
1126 protected static function parseDetailCycles($detail)
1127 {
1128 $data = $detail['data'] ?? [];
1129 if (!is_array($data)) {
1130 return [];
1131 }
1132 $prod = is_array($data['product'] ?? null) ? $data['product'] : $data;
1133 $out = self::parseParallelCycles($prod);
1134 if ($out !== []) {
1135 return $out;
1136 }
1137 $raw = $prod['cycle'] ?? $data['cycle'] ?? null;
1138 if (is_string($raw)) {
1139 $decoded = json_decode($raw, true);
1140 $raw = is_array($decoded) ? $decoded : null;
1141 }
1142 if (!is_array($raw) || $raw === []) {
1143 return [];
1144 }
1145 return self::parseCycleMap($raw);
1146 }
1147
1148 /* ============================================================
1149 * 周期键探测(add_to_shop 失败时定位上游真实 billingcycle 键)
1150 * ============================================================ */
1151
1152 /**
1153 * 探测上游商品可选周期(真实 billingcycle 键 + 中文名 + 价格)。
1154 * 优先 GET /cart/get_product_config(含该产品可选周期数据),
1155 * 失败回退商品详情。返回 [billingcycle键 => ['name'=>, 'price_cents'=>]];
1156 * 无结果返回 []。
1157 *
1158 * @param CubeFinanceClient $client
1159 * @param int $upId
1160 * @param array|null $detail 已抓取的详情响应(避免重复请求)
1161 */
1162 protected static function probeCycles($client, $upId, $detail = null)
1163 {
1164 $out = [];
1165 try {
1166 $res = $client->cartGetProductConfig((int)$upId);
1167 if (self::respOk($res)) {
1168 $out = self::parseConfigCycles($res);
1169 }
1170 } catch (CubeFinanceException $e) {
1171 $out = [];
1172 }
1173 if ($out !== []) {
1174 return $out;
1175 }
1176 if ($detail === null) {
1177 try {
1178 $detail = $client->productDetail((int)$upId, 'agent');
1179 } catch (CubeFinanceException $e) {
1180 return [];
1181 }
1182 }
1183 return self::parseDetailCycleList($detail);
1184 }
1185
1186 /**
1187 * 解析购物车配置接口响应中的周期列表。
1188 * 兼容 data.products(数组或单产品)与 data.product 两种外壳;
1189 * 周期可来自 cycle(JSON 串/数组/映射)、pricing 映射、并行数组。
1190 */
1191 protected static function parseConfigCycles($res)
1192 {
1193 $data = $res['data'] ?? [];
1194 if (!is_array($data)) {
1195 return [];
1196 }
1197 $products = $data['products'] ?? $data['product'] ?? null;
1198 if (!is_array($products)) {
1199 return [];
1200 }
1201 if (isset($products['cycle']) || isset($products['pricing'])
1202 || isset($products['billingcycle']) || isset($products['id'])) {
1203 $products = [$products];
1204 }
1205 $out = [];
1206 foreach ($products as $prod) {
1207 if (!is_array($prod)) {
1208 continue;
1209 }
1210 foreach (self::cycleSourceCandidates($prod) as $item) {
1211 $key = (string)($item['billingcycle'] ?? '');
1212 if ($key === '') {
1213 continue;
1214 }
1215 $cents = self::toCents(
1216 $item['price'] ?? $item['product_price'] ?? $item['price_total'] ?? 0
1217 );
1218 $name = (string)($item['billingcycle_zh'] ?? '');
1219 if (!isset($out[$key])) {
1220 $out[$key] = ['name' => $name, 'price_cents' => max(0, $cents)];
1221 } elseif ($cents > 0 && $out[$key]['price_cents'] <= 0) {
1222 $out[$key]['price_cents'] = max(0, $cents);
1223 }
1224 }
1225 }
1226 return $out;
1227 }
1228
1229 /**
1230 * 从单个产品数据提取周期条目数组 [{billingcycle, billingcycle_zh, price}]。
1231 * 优先完整周期(cycle/pricing),其次并行数组(billingcycle[]+billingcycle_price[])。
1232 */
1233 protected static function cycleSourceCandidates($prod)
1234 {
1235 $items = [];
1236 $raw = $prod['cycle'] ?? $prod['pricing'] ?? null;
1237 if (is_string($raw)) {
1238 $decoded = json_decode($raw, true);
1239 $raw = is_array($decoded) ? $decoded : null;
1240 }
1241 if (is_array($raw)) {
1242 if (isset($raw[0]) && is_array($raw[0])) {
1243 // 数组形式:[{billingcycle, price, billingcycle_zh}]
1244 foreach ($raw as $it) {
1245 if (is_array($it) && (string)($it['billingcycle'] ?? '') !== '') {
1246 $items[] = $it;
1247 }
1248 }
1249 } else {
1250 // 映射形式:{cycle: 价格 或 {price:...}}
1251 foreach ($raw as $k => $v) {
1252 $items[] = is_array($v)
1253 ? array_merge($v, ['billingcycle' => (string)$k])
1254 : ['billingcycle' => (string)$k, 'price' => $v];
1255 }
1256 }
1257 }
1258 if ($items !== []) {
1259 return $items;
1260 }
1261 // 并行数组形式
1262 $keys = $prod['billingcycle'] ?? null;
1263 $prices = $prod['billingcycle_price'] ?? $prod['billingcycleprices'] ?? null;
1264 if (is_array($keys) && is_array($prices)) {
1265 $names = is_array($prod['billingcycle_zh'] ?? null) ? $prod['billingcycle_zh'] : null;
1266 foreach ($keys as $i => $k) {
1267 $items[] = [
1268 'billingcycle' => (string)$k,
1269 'billingcycle_zh' => $names ? (string)($names[$i] ?? '') : '',
1270 'price' => $prices[$i] ?? 0,
1271 ];
1272 }
1273 }
1274 return $items;
1275 }
1276
1277 /** 详情响应 → [billingcycle键 => ['name'=>, 'price_cents'=>]]。 */
1278 protected static function parseDetailCycleList($detail)
1279 {
1280 $out = [];
1281 foreach (self::parseDetailCycles($detail) as $entry) {
1282 $key = (string)($entry['up_cycle'] ?? '');
1283 if ($key === '') {
1284 continue;
1285 }
1286 $out[$key] = [
1287 'name' => (string)($entry['name'] ?? ''),
1288 'price_cents' => (int)($entry['agent_price_cents'] ?? 0),
1289 ];
1290 }
1291 return $out;
1292 }
1293
1294 /* ============================================================
1295 * 配置项默认值探测(add_to_shop 需要 currencyid + configoption)
1296 * ============================================================ */
1297
1298 /**
1299 * 探测商品默认配置(货币ID + 配置项默认选择),用于 add_to_shop 计价。
1300 * 优先 GET /cart/get_product_config,失败回退商品详情。
1301 * 返回 ['currencyid'=>int, 'configoption'=>[optionId=>子项ID或数量]];
1302 * 探测不到 configoption 时至少带回 currencyid。
1303 *
1304 * @param CubeFinanceClient $client
1305 * @param int $upId
1306 * @param array|null $detail 已抓取的详情响应(避免重复请求)
1307 */
1308 protected static function probeConfigDefaults($client, $upId, $detail = null)
1309 {
1310 try {
1311 $res = $client->cartGetProductConfig((int)$upId);
1312 if (self::respOk($res)) {
1313 $out = self::parseConfigDefaults($res);
1314 if (!empty($out['configoption'])) {
1315 return $out;
1316 }
1317 }
1318 } catch (CubeFinanceException $e) {
1319 // 忽略,走详情回退
1320 }
1321 if ($detail === null) {
1322 try {
1323 $detail = $client->productDetail((int)$upId, 'agent');
1324 } catch (CubeFinanceException $e) {
1325 return ['currencyid' => 0, 'configoption' => []];
1326 }
1327 }
1328 return self::parseConfigDefaults($detail);
1329 }
1330
1331 /**
1332 * 从响应中解析 currencyid 与 configoption 默认选择。
1333 * 兼容 data.products(数组/单产品)与 data.product 外壳;
1334 * 配置项结构兼容数组组/映射组/扁平默认值/数量型多种形态。
1335 */
1336 protected static function parseConfigDefaults($res)
1337 {
1338 $data = $res['data'] ?? [];
1339 if (!is_array($data)) {
1340 return ['currencyid' => 0, 'configoption' => []];
1341 }
1342 $out = ['currencyid' => 0, 'configoption' => []];
1343 if (isset($data['default_currency']) && is_numeric($data['default_currency'])) {
1344 $out['currencyid'] = (int)$data['default_currency'];
1345 }
1346 $currencies = $data['currencies'] ?? null;
1347 if (is_array($currencies)) {
1348 foreach ($currencies as $c) {
1349 if (is_array($c) && isset($c['id']) && is_numeric($c['id'])) {
1350 if ($out['currencyid'] <= 0) {
1351 $out['currencyid'] = (int)$c['id'];
1352 }
1353 break;
1354 }
1355 }
1356 }
1357 $products = $data['products'] ?? $data['product'] ?? null;
1358 if (!is_array($products)) {
1359 if ($out['currencyid'] <= 0) {
1360 $out['currencyid'] = 1;
1361 }
1362 return $out;
1363 }
1364 if (isset($products['id']) || isset($products['pid'])
1365 || isset($products['configoption']) || isset($products['config_option'])) {
1366 $products = [$products];
1367 }
1368 $groups = [];
1369 foreach ($products as $prod) {
1370 if (!is_array($prod)) {
1371 continue;
1372 }
1373 // 产品级 currencyid(映射形式取首个键)
1374 if ($out['currencyid'] <= 0 && isset($prod['currencyid']) && is_array($prod['currencyid'])) {
1375 foreach ($prod['currencyid'] as $cid => $cfg) {
1376 if (is_numeric($cid) && (int)$cid > 0) {
1377 $out['currencyid'] = (int)$cid;
1378 break;
1379 }
1380 }
1381 }
1382 $co = $prod['configoption'] ?? $prod['config_option'] ?? null;
1383 if (is_array($co)) {
1384 $groups = array_merge($groups, self::normalizeConfigGroups($co));
1385 }
1386 }
1387 foreach ($groups as $g) {
1388 if (!is_array($g)) {
1389 continue;
1390 }
1391 $oid = (int)($g['id'] ?? $g['configoption_id'] ?? 0);
1392 if ($oid <= 0) {
1393 continue;
1394 }
1395 $val = self::pickConfigDefault($g);
1396 if ($val !== null && $val !== '') {
1397 $out['configoption'][(string)$oid] = (string)$val;
1398 }
1399 }
1400 if ($out['currencyid'] <= 0) {
1401 $out['currencyid'] = 1; // 兜底默认货币
1402 }
1403 return $out;
1404 }
1405
1406 /** 将 configoption 数据规范化为配置组列表。 */
1407 protected static function normalizeConfigGroups($co)
1408 {
1409 $groups = [];
1410 if (isset($co[0]) && is_array($co[0])) {
1411 return $co; // 数组组形式
1412 }
1413 foreach ($co as $k => $v) {
1414 if (!is_array($v)) {
1415 // 扁平:optionId => 默认值
1416 $groups[] = ['id' => is_numeric($k) ? $k : 0, '_flat_value' => $v];
1417 continue;
1418 }
1419 if (isset($v['option']) || isset($v['options']) || isset($v['id']) || isset($v['configoption_id'])) {
1420 if (!isset($v['id']) && !isset($v['configoption_id']) && is_numeric($k)) {
1421 $v['id'] = (int)$k;
1422 }
1423 $groups[] = $v;
1424 continue;
1425 }
1426 // 映射:optionId => 子项数组
1427 $groups[] = ['id' => is_numeric($k) ? (int)$k : 0, 'option' => $v];
1428 }
1429 return $groups;
1430 }
1431
1432 /**
1433 * 从单个配置组取默认子项值(子项ID或数量)。
1434 * 优先 checked/selected/default 标记,否则取第一个子项。
1435 */
1436 protected static function pickConfigDefault($g)
1437 {
1438 if (array_key_exists('_flat_value', $g)) {
1439 return (string)$g['_flat_value'];
1440 }
1441 $type = strtolower((string)($g['type'] ?? ''));
1442 if (in_array($type, ['qty', 'quantity', 'number'], true)) {
1443 $q = $g['qty'] ?? $g['quantity'] ?? $g['value'] ?? 1;
1444 return (string)$q;
1445 }
1446 $subs = $g['option'] ?? $g['options'] ?? $g['sub_option']
1447 ?? $g['suboption'] ?? $g['child'] ?? $g['values'] ?? null;
1448 if (!is_array($subs)) {
1449 return null;
1450 }
1451 $first = null;
1452 foreach ($subs as $s) {
1453 if (!is_array($s)) {
1454 continue;
1455 }
1456 if ($first === null) {
1457 $first = $s;
1458 }
1459 foreach (['checked', 'selected', 'default', 'is_check', 'is_default'] as $f) {
1460 if (isset($s[$f]) && ((int)$s[$f] === 1 || (string)$s[$f] === '1')) {
1461 $first = $s;
1462 break 2;
1463 }
1464 }
1465 }
1466 if ($first === null) {
1467 return null;
1468 }
1469 $id = $first['id'] ?? $first['suboption_id'] ?? $first['value'] ?? null;
1470 return $id === null ? null : (string)$id;
1471 }
1472
1473 /** 上游失败信息是否与周期/价格相关(命中才触发探测重试)。 */
1474 protected static function isCyclePriceError($res)
1475 {
1476 $msg = (string)($res['msg'] ?? '');
1477 return $msg !== '' && (
1478 strpos($msg, '未配置价格') !== false
1479 || strpos($msg, '价格错误') !== false
1480 || strpos($msg, '周期') !== false
1481 || stripos($msg, 'cycle') !== false
1482 );
1483 }
1484
1485 /**
1486 * 本地周期键 → 上游真实 billingcycle 键。
1487 * 忽略大小写并按别名(monthly/month、quarterly/quarter 等)匹配,
1488 * 也匹配中文名(月付/月/季付…);找不到返回原键。
1489 */
1490 protected static function matchUpCycle($localCycle, array $available)
1491 {
1492 $localCycle = (string)$localCycle;
1493 if ($localCycle === '' || $available === []) {
1494 return $localCycle;
1495 }
1496 $aliases = self::cycleAliases($localCycle);
1497 foreach ($available as $key => $cfg) {
1498 $candidate = (string)$key;
1499 if (in_array(self::normKey($candidate), $aliases, true)) {
1500 return $candidate;
1501 }
1502 $name = (string)($cfg['name'] ?? '');
1503 if ($name !== '' && in_array(self::normKey($name), $aliases, true)) {
1504 return $candidate;
1505 }
1506 }
1507 $normLocal = self::normKey($localCycle);
1508 foreach ($available as $key => $cfg) {
1509 if (self::normKey((string)$key) === $normLocal) {
1510 return (string)$key;
1511 }
1512 }
1513 return $localCycle;
1514 }
1515
1516 /** 本地周期键的别名集合(归一化后,含中文名)。 */
1517 protected static function cycleAliases($localCycle)
1518 {
1519 $norm = self::normKey($localCycle);
1520 $map = [
1521 'monthly' => ['monthly', 'month', 'm', '月', '月付'],
1522 'quarterly' => ['quarterly', 'quarter', 'q', '季', '季付'],
1523 'semiannually' => ['semiannually', 'semiannual', 'halfyear', 'half_year', 'half', 'semi', '半年', '半年付'],
1524 'annually' => ['annually', 'annual', 'yearly', 'year', 'y', '年', '年付'],
1525 'biennially' => ['biennially', 'biennial', 'biennium', 'twoyear', 'two_year', '两年', '两年付'],
1526 'triennially' => ['triennially', 'triennial', 'triennium', 'threeyear', 'three_year', '三年', '三年付'],
1527 ];
1528 foreach ($map as $k => $list) {
1529 if ($norm === $k || in_array($norm, $list, true)) {
1530 return $list;
1531 }
1532 }
1533 return [$norm];
1534 }
1535
1536 /** 键归一化:小写 + 去非字母数字(保留中文)。 */
1537 protected static function normKey($key)
1538 {
1539 return strtolower(preg_replace('/[^a-z0-9\x{4e00}-\x{9fa5}]/iu', '', (string)$key));
1540 }
1541
1542 /** 可用周期列表渲染为可读文案(供失败信息展示)。 */
1543 protected static function formatAvailable(array $avail)
1544 {
1545 $parts = [];
1546 foreach ($avail as $key => $cfg) {
1547 $name = (string)($cfg['name'] ?? '');
1548 $parts[] = $name !== '' ? $key . '(' . $name . ')' : $key;
1549 }
1550 return $parts === [] ? '' : ';上游可用周期:' . implode('、', $parts);
1551 }
1552
1553 /**
1554 * 将本地周期对应的上游键写回商品 cycles JSON(后续购买直接使用)。
1555 */
1556 protected static function persistUpCycle($supplierId, $upProductId, $localCycle, $upCycle)
1557 {
1558 global $DB;
1559 $product = zjmf_product_get_by_up((int)$supplierId, (int)$upProductId);
1560 if (!$product) {
1561 return;
1562 }
1563 $cycles = json_decode((string)($product['cycles'] ?? ''), true);
1564 if (!is_array($cycles)) {
1565 return;
1566 }
1567 $changed = false;
1568 foreach ($cycles as &$cfg) {
1569 if (is_array($cfg) && (string)($cfg['cycle'] ?? '') === (string)$localCycle) {
1570 if ((string)($cfg['up_cycle'] ?? '') !== (string)$upCycle) {
1571 $cfg['up_cycle'] = (string)$upCycle;
1572 $changed = true;
1573 }
1574 break;
1575 }
1576 }
1577 unset($cfg);
1578 if ($changed) {
1579 $DB->query_prepare(
1580 "UPDATE MN_plugin_zjmf_product SET cycles=?, updated_at=?
1581 WHERE id=?",
1582 [
1583 json_encode($cycles, JSON_UNESCAPED_UNICODE),
1584 date('Y-m-d H:i:s'),
1585 (int)$product['id'],
1586 ]
1587 );
1588 }
1589 }
1590
1591 /** 构建单个周期条目(键归一化 + 名称兜底)。 */
1592 protected static function cycleEntry($key, $cents, $name = '')
1593 {
1594 $norm = self::normalizeCycleKey($key);
1595 $known = zjmf_cycles();
1596 return [
1597 'cycle' => $norm,
1598 // 上游原始 billingcycle 值(如 monthly),购买时原样回传
1599 'up_cycle' => (string)$key,
1600 'name' => $name !== '' ? $name : ($known[$norm]['name'] ?? $norm),
1601 'agent_price_cents' => max(0, (int)$cents),
1602 ];
1603 }
1604
1605 /** 周期键归一化:忽略大小写匹配内置周期(monthly → Monthly)。 */
1606 protected static function normalizeCycleKey($key)
1607 {
1608 $key = (string)$key;
1609 if ($key === '') {
1610 return '';
1611 }
1612 foreach (array_keys(zjmf_cycles()) as $k) {
1613 if (strcasecmp($k, $key) === 0) {
1614 return $k;
1615 }
1616 }
1617 return $key;
1618 }
1619
1620 /** 解析周期映射/数组,返回 ['Monthly' => ['cycle','name','agent_price_cents']]。 */
1621 protected static function parseCycleMap($raw)
1622 {
1623 $out = [];
1624 // 数组形式:[{billingcycle: 'monthly', billingcycle_zh: '月', price: '25.00'}, ...]
1625 if (isset($raw[0]) && is_array($raw[0])) {
1626 foreach ($raw as $item) {
1627 if (!is_array($item)) {
1628 continue;
1629 }
1630 $key = (string)($item['billingcycle'] ?? $item['cycle'] ?? '');
1631 if ($key === '') {
1632 continue;
1633 }
1634 $cents = self::toCents(self::pickPrice($item));
1635 if ($cents <= 0) {
1636 continue;
1637 }
1638 $name = (string)($item['name'] ?? $item['billingcycle_zh'] ?? '');
1639 $out[self::normalizeCycleKey($key)] = self::cycleEntry($key, $cents, $name);
1640 }
1641 } else {
1642 // 映射形式:{'monthly': '25.00' 或 {price: '25.00'}}
1643 foreach ($raw as $key => $v) {
1644 $key = (string)$key;
1645 if ($key === '') {
1646 continue;
1647 }
1648 $cents = self::toCents(is_array($v) ? self::pickPrice($v) : $v);
1649 if ($cents <= 0) {
1650 continue;
1651 }
1652 $name = is_array($v) ? (string)($v['name'] ?? $v['billingcycle_zh'] ?? '') : '';
1653 $out[self::normalizeCycleKey($key)] = self::cycleEntry($key, $cents, $name);
1654 }
1655 }
1656 return $out;
1657 }
1658
1659 /** 金额(元)→ 分。 */
1660 protected static function toCents($val)
1661 {
1662 return (int)round((float)$val * 100);
1663 }
1664
1665 /** 上游列表项价格(分),支持嵌套 pricing 结构,无价格返回 0。 */
1666 public static function itemPrice($item)
1667 {
1668 if (!is_array($item)) {
1669 return 0;
1670 }
1671 $cents = self::toCents(self::pickPrice($item));
1672 if ($cents <= 0 && isset($item['pricing']) && is_array($item['pricing'])) {
1673 foreach ($item['pricing'] as $v) {
1674 $cents = self::toCents(is_array($v) ? self::pickPrice($v) : $v);
1675 if ($cents > 0) {
1676 break;
1677 }
1678 }
1679 }
1680 return $cents;
1681 }
1682
1683 /** 上游列表项模块类型(魔方财务列表返回字段为 type),无则返回空串。 */
1684 public static function itemModule($item)
1685 {
1686 if (!is_array($item)) {
1687 return '';
1688 }
1689 return (string)($item['type'] ?? $item['module'] ?? $item['module_name'] ?? '');
1690 }
1691
1692 /**
1693 * 从购物车数据中定位刚添加产品的购物车位置。
1694 * 部分版本 add_to_shop 不返回位置 i,需 GET /cart/get_shop_data 后
1695 * 按 productid 匹配(购物车数组的键/序号即位置 i;同商品取最后一项,即刚添加的)。
1696 *
1697 * @param CubeFinanceClient $client
1698 * @param int $upProductId
1699 * @param string $upCycle 上游 billingcycle 键
1700 * @return int 位置,找不到返回 -1
1701 */
1702 protected static function cartPosition($client, $upProductId, $upCycle)
1703 {
1704 try {
1705 $res = $client->cartGetShopData();
1706 } catch (CubeFinanceException $e) {
1707 return -1;
1708 }
1709 if (!self::respOk($res)) {
1710 return -1;
1711 }
1712 $products = $res['data']['cart_products'] ?? null;
1713 if (!is_array($products)) {
1714 return -1;
1715 }
1716 $wantPid = (string)$upProductId;
1717 $wantCycle = strtolower((string)$upCycle);
1718 $lastPid = -1;
1719 $lastMatch = -1;
1720 foreach ($products as $i => $p) {
1721 if (!is_array($p)) {
1722 continue;
1723 }
1724 $pid = (string)($p['productid'] ?? $p['pid'] ?? $p['id'] ?? '');
1725 if ($pid !== $wantPid) {
1726 continue;
1727 }
1728 $lastPid = (int)$i;
1729 $cycle = strtolower((string)($p['billingcycle'] ?? ''));
1730 if ($cycle === $wantCycle || $cycle === '') {
1731 $lastMatch = (int)$i; // 周期匹配(或未知)的最后一个即刚添加项
1732 }
1733 }
1734 if ($lastMatch >= 0) {
1735 return $lastMatch;
1736 }
1737 return $lastPid; // 仅 pid 匹配的最后一个
1738 }
1739
1740 /**
1741 * 购物车是否可安全结算:为空或仅含本次商品。
1742 * 用于 cartClear 失败后的兜底确认;购物车数据拉取失败视为不可确认。
1743 *
1744 * @param CubeFinanceClient $client
1745 * @param int $upProductId 本次开通的上游商品 ID
1746 * @return bool true=可继续结算
1747 */
1748 protected static function cartSafeForSettle($client, $upProductId)
1749 {
1750 try {
1751 $res = $client->cartGetShopData();
1752 } catch (CubeFinanceException $e) {
1753 return false; // 无法确认购物车内容,不可继续
1754 }
1755 if (!self::respOk($res)) {
1756 return false;
1757 }
1758 $products = $res['data']['cart_products'] ?? null;
1759 if (!is_array($products)) {
1760 return false; // 结构异常,无法确认
1761 }
1762 foreach ($products as $p) {
1763 if (!is_array($p)) {
1764 continue;
1765 }
1766 $pid = (string)($p['productid'] ?? $p['pid'] ?? $p['id'] ?? '');
1767 if ($pid !== (string)$upProductId) {
1768 return false; // 含本次商品之外的项目,不可继续
1769 }
1770 }
1771 return true;
1772 }
1773
1774 /**
1775 * 从加购响应中取购物车位置 data.i(兼容字符串 data、其他位置键、一层嵌套)。
1776 *
1777 * @param array $res 响应数组
1778 * @return int 位置,找不到返回 -1
1779 */
1780 protected static function findPosition($res)
1781 {
1782 $d = $res['data'] ?? null;
1783 if (is_string($d)) {
1784 if (is_numeric($d)) {
1785 return (int)$d;
1786 }
1787 $decoded = json_decode($d, true);
1788 if (is_array($decoded)) {
1789 $d = $decoded;
1790 }
1791 }
1792 if (is_numeric($d)) {
1793 return (int)$d;
1794 }
1795 if (!is_array($d)) {
1796 return -1;
1797 }
1798 foreach (['i', 'position', 'pos', 'cart_i', 'key', 'id'] as $k) {
1799 if (!array_key_exists($k, $d)) {
1800 continue;
1801 }
1802 $v = $d[$k];
1803 if (is_array($v)) {
1804 $v = reset($v);
1805 }
1806 if (is_numeric($v)) {
1807 return (int)$v;
1808 }
1809 }
1810 // 一层嵌套深搜(如 data.products[].i)
1811 foreach ($d as $v) {
1812 if (is_array($v)) {
1813 $sub = self::findPosition(['data' => $v]);
1814 if ($sub >= 0) {
1815 return $sub;
1816 }
1817 }
1818 }
1819 return -1;
1820 }
1821
1822 /** 上游返回是否成功(200 常规成功;1001 购买成功/支付完成,无需继续支付)。 */
1823 protected static function respOk($res)
1824 {
1825 $st = (int)($res['status'] ?? 0);
1826 return in_array($st, [200, 1001], true);
1827 }
1828
1829 /** 组装上游失败详情(msg + data 截断),避免日志里只有泛化文案。
1830 * data 中 password/pass/pwd/token/secret 等键的值脱敏后再入日志。 */
1831 protected static function respErr($prefix, $res)
1832 {
1833 $msg = (string)($res['msg'] ?? '');
1834 $data = $res['data'] ?? null;
1835 $detail = '';
1836 if (is_array($data) || is_scalar($data)) {
1837 $safeData = is_array($data) ? self::maskSecrets($data) : $data;
1838 $json = json_encode($safeData, JSON_UNESCAPED_UNICODE);
1839 if (is_string($json)) {
1840 $detail = ' data=' . self::truncate($json, 300);
1841 }
1842 }
1843 $out = trim($prefix . ':' . $msg . $detail, ':');
1844 return $out !== '' ? $out : $prefix;
1845 }
1846
1847 /** 递归脱敏:键名含 password/pass/pwd/token/secret 的值替换为 ***。 */
1848 protected static function maskSecrets(array $data)
1849 {
1850 $out = [];
1851 foreach ($data as $k => $v) {
1852 $lk = strtolower((string)$k);
1853 $sensitive = $lk !== '' && (
1854 strpos($lk, 'password') !== false
1855 || strpos($lk, 'pass') !== false
1856 || strpos($lk, 'pwd') !== false
1857 || strpos($lk, 'token') !== false
1858 || strpos($lk, 'secret') !== false
1859 );
1860 if ($sensitive) {
1861 $out[$k] = '***';
1862 } elseif (is_array($v)) {
1863 $out[$k] = self::maskSecrets($v);
1864 } else {
1865 $out[$k] = $v;
1866 }
1867 }
1868 return $out;
1869 }
1870
1871 /** 截断字符串(mb_substr 不可用时回退 substr)。 */
1872 protected static function truncate($str, $len)
1873 {
1874 if (function_exists('mb_substr')) {
1875 return mb_substr($str, 0, $len);
1876 }
1877 return substr($str, 0, $len);
1878 }
1879
1880 /** 生成上游主机名(官方示例:ser + 12 位随机串)。 */
1881 protected static function randHost()
1882 {
1883 $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
1884 return 'ser' . substr(str_shuffle($chars), 0, 12);
1885 }
1886
1887 /** 生成随机密码(12 位字母数字)。 */
1888 protected static function randPassword()
1889 {
1890 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
1891 return substr(str_shuffle($chars), 0, 12);
1892 }
1893
1894 protected static function findId($arr)
1895 {
1896 if (!is_array($arr)) {
1897 return 0;
1898 }
1899 foreach (['id', 'order_id', 'orderid', 'invoiceid', 'invoice_id'] as $k) {
1900 if (isset($arr[$k])) {
1901 $v = $arr[$k];
1902 if (is_array($v)) {
1903 $v = reset($v);
1904 }
1905 return (int)$v;
1906 }
1907 }
1908 return 0;
1909 }
1910
1911 /** 从 data 中找主机 ID(支持嵌套 host 与 hostid 数组)。
1912 * 不含 'id' 兜底键:结算响应 data.id 通常是账单/订单 ID,曾被误判
1913 * 为主机 ID 导致跳过支付(M3 误判)。 */
1914 protected static function findHostId($arr)
1915 {
1916 if (!is_array($arr)) {
1917 return 0;
1918 }
1919 foreach (['host_id', 'hostid', 'hid'] as $k) {
1920 if (isset($arr[$k])) {
1921 $v = $arr[$k];
1922 if (is_array($v)) {
1923 $v = reset($v);
1924 }
1925 if ((int)$v > 0) {
1926 return (int)$v;
1927 }
1928 }
1929 }
1930 if (isset($arr['host']) && is_array($arr['host'])) {
1931 return self::findHostId($arr['host']);
1932 }
1933 return 0;
1934 }
1935
1936 /**
1937 * 插件周期键 → 上游 billingcycle 值。
1938 * 优先取同步时保留的上游原始值(up_cycle),未同步/旧数据回退小写(官方周期如 monthly、day、hour)。
1939 */
1940 protected static function upstreamCycle($supplierId, $upProductId, $cycle)
1941 {
1942 $cycle = (string)$cycle;
1943 if ($cycle !== '') {
1944 $product = zjmf_product_get_by_up((int)$supplierId, (int)$upProductId);
1945 if ($product) {
1946 $cycles = zjmf_product_cycles($product);
1947 $entry = $cycles[$cycle] ?? null;
1948 if (is_array($entry) && (string)($entry['up_cycle'] ?? '') !== '') {
1949 return (string)$entry['up_cycle'];
1950 }
1951 }
1952 }
1953 return strtolower($cycle);
1954 }
1955
1956 /**
1957 * 查询账单详情并轮询主机 ID(主机创建可能异步)。
1958 * 官方:GET /invoices/{id} → data.invoices[].status(支付状态)+
1959 * data.host[].num(账单项目关联的产品 ID,兼容标量/数组)。
1960 *
1961 * @param CubeFinanceClient $client
1962 * @param int $invoiceId
1963 * @param int $maxTries 轮询次数(每次间隔 2 秒)
1964 * @return array|null ['status'=>string, 'host_id'=>int],未取到主机 ID 时轮询至超时
1965 */
1966 protected static function invoiceInfo($client, $invoiceId, $maxTries = 4)
1967 {
1968 for ($i = 0; $i < $maxTries; $i++) {
1969 try {
1970 $res = $client->get('invoices/' . (int)$invoiceId);
1971 if (self::respOk($res)) {
1972 $data = is_array($res['data'] ?? null) ? $res['data'] : [];
1973 $info = ['status' => '', 'host_id' => 0];
1974 $inv = $data['invoices'] ?? null;
1975 if (is_array($inv)) {
1976 $first = (isset($inv[0]) && is_array($inv[0])) ? $inv[0] : $inv;
1977 $info['status'] = strtolower((string)($first['status'] ?? ''));
1978 }
1979 $items = $data['host'] ?? null;
1980 if (is_array($items)) {
1981 foreach ($items as $item) {
1982 if (!is_array($item)) {
1983 continue;
1984 }
1985 $num = $item['num'] ?? null;
1986 if (is_array($num)) {
1987 foreach ($num as $n) {
1988 if ((int)$n > 0) {
1989 $info['host_id'] = (int)$n;
1990 break 2;
1991 }
1992 }
1993 } elseif ((int)$num > 0) {
1994 $info['host_id'] = (int)$num;
1995 break;
1996 }
1997 }
1998 }
1999 if ($info['host_id'] > 0) {
2000 return $info;
2001 }
2002 }
2003 } catch (CubeFinanceException $e) {
2004 // 查询失败忽略,稍后重试
2005 }
2006 if ($i < $maxTries - 1) {
2007 sleep(2);
2008 }
2009 }
2010 return null;
2011 }
2012
2013 /** 账单支付状态是否已支付(兼容英文/中文)。 */
2014 protected static function isPaidStatus($status)
2015 {
2016 $st = strtolower(trim((string)$status));
2017 return in_array($st, ['paid', '已支付', 'completed', 'complete', 'success', 'payment'], true);
2018 }
2019
2020 /** 从主机详情响应提取主机数据(兼容 host_data/host/info/list/data 键与单对象/数组结构)。 */
2021 protected static function pickHostData($data)
2022 {
2023 if (!is_array($data)) {
2024 return [];
2025 }
2026 foreach (['host_data', 'host', 'info', 'list', 'data'] as $k) {
2027 if (isset($data[$k]) && is_array($data[$k])) {
2028 $v = $data[$k];
2029 if (isset($v[0]) && is_array($v[0])) {
2030 return $v[0];
2031 }
2032 return $v;
2033 }
2034 }
2035 return $data;
2036 }
2037
2038 /** 查询主机头信息并安全提取字段(失败给空)。 */
2039 protected static function safeHostHeader($client, $hostId)
2040 {
2041 try {
2042 $res = $client->hostHeader((int)$hostId);
2043 $host = self::pickHostData($res['data'] ?? []);
2044 return [
2045 'username' => (string)($host['username'] ?? ''),
2046 'password' => (string)($host['password'] ?? ''),
2047 'name' => (string)($host['productname'] ?? $host['name'] ?? ''),
2048 // 上游部分版本 nextduedate 为 Unix 时间戳,统一归一化为 Y-m-d
2049 'renew_date' => zjmf_normalize_date(
2050 (string)($host['nextduedate'] ?? $host['renew_date'] ?? $host['renewdate'] ?? '')
2051 ),
2052 ];
2053 } catch (CubeFinanceException $e) {
2054 return ['username' => '', 'password' => '', 'name' => '', 'renew_date' => ''];
2055 }
2056 }
2057
2058 /**
2059 * 上游主机数据 → 本地展示状态(active/suspend/pending/terminated/unknown)。
2060 * 状态映射委托统一实现 zjmf_map_upstream_status(lib/zjmf.php,主表),
2061 * 无状态字段时用 qk 兜底(false 视为不可用)。
2062 */
2063 public static function mapHostStatus($data)
2064 {
2065 if (!is_array($data)) {
2066 return 'unknown';
2067 }
2068 $st = strtolower(trim((string)($data['status'] ?? $data['domainstatus'] ?? '')));
2069 if ($st !== '') {
2070 return zjmf_map_upstream_status($st);
2071 }
2072 // 无状态字段时用 qk 兜底(false 视为不可用)
2073 $qk = $data['qk'] ?? null;
2074 if ($qk !== null && in_array((string)$qk, ['false', '0', ''], true)) {
2075 return 'suspend';
2076 }
2077 return 'unknown';
2078 }
2079}