仰望星辰工作室

better-staridc-MNBT

Z zfhsh first commit 2 个月前
1<?php
2/**
3 * domain_shop 插件 - DNSPod(腾讯云 API 3.0)适配器
4 * 文档:https://cloud.tencent.com/document/api/1427
5 *
6 * 旧版 DNSPod API(dnsapi.cn + login_token)已停止维护,此处迁移至腾讯云 API 3.0:
7 * - 接口域名:dnspod.tencentcloudapi.com,Version=2021-03-23
8 * - 鉴权:腾讯云 API 密钥(SecretId + SecretKey),TC3-HMAC-SHA256 签名
9 * - 请求:POST + application/json
10 */
11if (!defined('IN_CRONLITE')) exit;
12
13class DomainShop_DNSPod
14{
15 private $apiId; // 腾讯云 SecretId
16 private $apiSecret; // 腾讯云 SecretKey
17 private $endpoint = 'https://dnspod.tencentcloudapi.com';
18 private $service = 'dnspod';
19 private $version = '2021-03-23';
20 private $lastErr = '';
21
22 public function __construct($apiId, $apiSecret)
23 {
24 $this->apiId = (string)$apiId;
25 $this->apiSecret = (string)$apiSecret;
26 }
27
28 public function lastError()
29 {
30 return $this->lastErr;
31 }
32
33 /**
34 * 取域名列表
35 * @return array [['name'=>..., 'id'=>...], ...]
36 */
37 public function listDomains()
38 {
39 $resp = $this->call('DescribeDomainList', ['Type' => 'ALL', 'Limit' => 1000]);
40 if ($resp === false) return [];
41 $out = [];
42 foreach (($resp['DomainList'] ?? []) as $d) {
43 $out[] = ['id' => (string)($d['DomainId'] ?? ''), 'name' => $d['Name'] ?? ''];
44 }
45 return $out;
46 }
47
48 /**
49 * 取某域名下记录列表(字段映射为小写风格,与旧适配器输出保持一致)
50 */
51 public function listRecords($domain)
52 {
53 $resp = $this->call('DescribeRecordList', [
54 'Domain' => $domain,
55 'Offset' => 0,
56 'Limit' => 1000,
57 'ErrorOnEmpty' => 'no',
58 ]);
59 if ($resp === false) return [];
60 $out = [];
61 foreach (($resp['RecordList'] ?? []) as $r) {
62 $out[] = [
63 'id' => (string)($r['RecordId'] ?? ''),
64 'name' => $r['Name'] ?? '',
65 'type' => $r['Type'] ?? '',
66 'value' => $r['Value'] ?? '',
67 'line' => $r['Line'] ?? '',
68 'ttl' => $r['TTL'] ?? 0,
69 'mx' => $r['MX'] ?? 0,
70 'status' => $r['Status'] ?? '',
71 ];
72 }
73 return $out;
74 }
75
76 /**
77 * 创建记录
78 * @return string|false 远程记录 ID,失败返回 false
79 */
80 public function createRecord($domain, $name, $type, $value, $ttl = 600, $mx = 0)
81 {
82 $params = [
83 'Domain' => $domain,
84 'SubDomain' => $name,
85 'RecordType' => strtoupper($type),
86 'RecordLine' => '默认',
87 'Value' => $value,
88 'TTL' => (int)$ttl,
89 ];
90 if (strtoupper($type) === 'MX') $params['MX'] = (int)$mx;
91
92 $resp = $this->call('CreateRecord', $params);
93 if ($resp === false) return false;
94 return (string)($resp['RecordId'] ?? '');
95 }
96
97 /**
98 * 更新记录
99 */
100 public function updateRecord($domain, $recordId, $name, $type, $value, $ttl = 600, $mx = 0)
101 {
102 $params = [
103 'Domain' => $domain,
104 'RecordId' => (int)$recordId,
105 'SubDomain' => $name,
106 'RecordType' => strtoupper($type),
107 'RecordLine' => '默认',
108 'Value' => $value,
109 'TTL' => (int)$ttl,
110 ];
111 if (strtoupper($type) === 'MX') $params['MX'] = (int)$mx;
112
113 $resp = $this->call('ModifyRecord', $params);
114 return $resp !== false;
115 }
116
117 /**
118 * 删除记录
119 */
120 public function deleteRecord($domain, $recordId)
121 {
122 $resp = $this->call('DeleteRecord', ['Domain' => $domain, 'RecordId' => (int)$recordId]);
123 return $resp !== false;
124 }
125
126 /**
127 * 调用腾讯云 DNSPod API 3.0
128 * @return array|false 解析后的 Response 数组,失败返回 false(lastErr 记录原因)
129 */
130 private function call($action, array $params)
131 {
132 $timestamp = time();
133 $payload = json_encode($params, JSON_UNESCAPED_UNICODE);
134 $authorization = $this->sign($action, $payload, $timestamp);
135
136 $headers = [
137 'Content-Type: application/json; charset=utf-8',
138 'X-TC-Action: ' . $action,
139 'X-TC-Timestamp: ' . $timestamp,
140 'X-TC-Version: ' . $this->version,
141 'Authorization: ' . $authorization,
142 ];
143
144 // 用插件引擎的 HTTP 出站函数(有内网/协议安全策略),失败回退到 cURL
145 if (function_exists('mnbt_http_post')) {
146 $res = mnbt_http_post($this->endpoint, $payload, [
147 'timeout' => 15,
148 'headers' => $headers,
149 ]);
150 if (!empty($res['ok'])) {
151 return $this->parseResponse($res['body'] ?? '');
152 }
153 $this->lastErr = $res['error'] ?? 'mnbt_http_post 失败';
154 }
155
156 if (!function_exists('curl_init')) {
157 $this->lastErr = 'PHP 未启用 cURL 扩展';
158 return false;
159 }
160 $ch = curl_init($this->endpoint);
161 curl_setopt_array($ch, [
162 CURLOPT_POST => true,
163 CURLOPT_POSTFIELDS => $payload,
164 CURLOPT_RETURNTRANSFER => true,
165 CURLOPT_TIMEOUT => 15,
166 CURLOPT_HTTPHEADER => $headers,
167 ]);
168 $body = curl_exec($ch);
169 $err = curl_error($ch);
170 curl_close($ch);
171 if ($body === false) {
172 $this->lastErr = 'cURL 错误:' . $err;
173 return false;
174 }
175 return $this->parseResponse($body);
176 }
177
178 /**
179 * 解析 API 3.0 响应(统一包在 Response 中;存在 Error 视为失败)
180 */
181 private function parseResponse($body)
182 {
183 $arr = json_decode($body, true);
184 if (!is_array($arr) || !isset($arr['Response'])) {
185 $this->lastErr = '响应解析失败:' . mb_substr((string)$body, 0, 200);
186 return false;
187 }
188 $resp = $arr['Response'];
189 if (isset($resp['Error'])) {
190 $this->lastErr = ($resp['Error']['Message'] ?? '') ?: ($resp['Error']['Code'] ?? 'API 错误');
191 return false;
192 }
193 return $resp;
194 }
195
196 /**
197 * TC3-HMAC-SHA256 签名(腾讯云 API 3.0 签名方法 v3)
198 */
199 private function sign($action, $payload, $timestamp)
200 {
201 $algorithm = 'TC3-HMAC-SHA256';
202 $host = 'dnspod.tencentcloudapi.com';
203 $date = gmdate('Y-m-d', $timestamp);
204
205 // 1. 拼接规范请求串
206 $contentType = 'application/json; charset=utf-8';
207 $canonicalHeaders = "content-type:$contentType\nhost:$host\nx-tc-action:" . strtolower($action) . "\n";
208 $signedHeaders = 'content-type;host;x-tc-action';
209 $hashedRequestPayload = hash('sha256', $payload);
210 $canonicalRequest = "POST\n/\n\n$canonicalHeaders\n$signedHeaders\n$hashedRequestPayload";
211
212 // 2. 拼接待签名字符串
213 $credentialScope = "$date/{$this->service}/tc3_request";
214 $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
215 $stringToSign = "$algorithm\n$timestamp\n$credentialScope\n$hashedCanonicalRequest";
216
217 // 3. 计算派生签名密钥与签名
218 $secretDate = hash_hmac('sha256', $date, 'TC3' . $this->apiSecret, true);
219 $secretService = hash_hmac('sha256', $this->service, $secretDate, true);
220 $secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true);
221 $signature = hash_hmac('sha256', $stringToSign, $secretSigning);
222
223 // 4. 拼接 Authorization
224 return "$algorithm Credential={$this->apiId}/$credentialScope, SignedHeaders=$signedHeaders, Signature=$signature";
225 }
226}