LqTencentLocationService.cs
17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.TencentLocation;
using NCC.FriendlyException;
using Newtonsoft.Json.Linq;
namespace NCC.Extend
{
/// <summary>
/// 腾讯位置服务(后端代理 WebService:IP 定位、地址解析、地点搜索、逆地址解析)
/// </summary>
[ApiDescriptionSettings(Tag = "Extend", Name = "LqTencentLocation", Order = 210)]
[Route("api/Extend/[controller]")]
[ApiController]
public class LqTencentLocationService : IDynamicApiController, ITransient
{
private const string TencentWsBaseUrl = "https://apis.map.qq.com";
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<LqTencentLocationService> _logger;
/// <summary>
/// 初始化腾讯位置服务
/// </summary>
/// <param name="configuration">配置</param>
/// <param name="httpClientFactory">HttpClient 工厂</param>
/// <param name="logger">日志</param>
public LqTencentLocationService(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
ILogger<LqTencentLocationService> logger)
{
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_logger = logger;
}
/// <summary>
/// 腾讯位置服务 IP 定位
/// </summary>
/// <remarks>
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/location/v1/ip
/// - 用于门店资料页在无经纬度时获取大概中心点与城市
///
/// 示例请求:
/// ```json
/// {}
/// ```
///
/// 参数说明:
/// - 无必填参数,服务端按请求 IP 定位
/// </remarks>
/// <returns>定位坐标与城市</returns>
/// <response code="200">定位成功</response>
/// <response code="400">Key 缺失 / 腾讯接口业务错误</response>
/// <response code="500">服务器内部错误</response>
[HttpGet("IpLocate")]
public async Task<TencentIpLocateOutput> IpLocate()
{
var json = await CallTencentWsAsync("/ws/location/v1/ip", "腾讯 IP 定位");
var lat = json["result"]?["location"]?["lat"]?.Value<decimal?>();
var lng = json["result"]?["location"]?["lng"]?.Value<decimal?>();
if (!lat.HasValue || !lng.HasValue)
{
_logger.LogWarning("腾讯 IP 定位返回无坐标 body={Body}", Truncate(json.ToString(), 1200));
throw NCCException.Oh("腾讯 IP 定位返回坐标为空");
}
var city = json["result"]?["ad_info"]?["city"]?.ToString();
return new TencentIpLocateOutput
{
location = new TencentLocationDto
{
latitude = lat.Value,
longitude = lng.Value
},
city = string.IsNullOrWhiteSpace(city) ? null : city
};
}
/// <summary>
/// 腾讯位置服务地址解析(地址 → 坐标)
/// </summary>
/// <remarks>
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/geocoder/v1/(地址解析)
/// - 适合完整地址检索,失败时前端可再调用 PlaceSearch
///
/// 示例请求:
/// ```json
/// {
/// "address": "成都市武侯区天府大道",
/// "region": "成都"
/// }
/// ```
///
/// 参数说明:
/// - address: 待解析地址(必填)
/// - region: 指定地址所属城市,可选,可提高解析准确度
/// </remarks>
/// <param name="address">待解析地址</param>
/// <param name="region">城市范围,可选</param>
/// <returns>解析后的坐标</returns>
/// <response code="200">解析成功</response>
/// <response code="400">参数错误 / Key 缺失 / 腾讯接口业务错误</response>
/// <response code="500">服务器内部错误</response>
[HttpGet("GeocodeAddress")]
public async Task<TencentGeocodeAddressOutput> GeocodeAddress(
[FromQuery] string address,
[FromQuery] string region = null)
{
if (string.IsNullOrWhiteSpace(address))
throw NCCException.Oh("address 不能为空");
var path = $"/ws/geocoder/v1/?address={Uri.EscapeDataString(address.Trim())}";
if (!string.IsNullOrWhiteSpace(region))
path += $"®ion={Uri.EscapeDataString(region.Trim())}";
var json = await CallTencentWsAsync(path, "腾讯地址解析");
var lat = json["result"]?["location"]?["lat"]?.Value<decimal?>();
var lng = json["result"]?["location"]?["lng"]?.Value<decimal?>();
if (!lat.HasValue || !lng.HasValue)
{
_logger.LogWarning(
"腾讯地址解析返回无坐标 address={Address} body={Body}",
address,
Truncate(json.ToString(), 1200));
throw NCCException.Oh("腾讯地址解析返回坐标为空");
}
return new TencentGeocodeAddressOutput
{
location = new TencentLocationDto
{
latitude = lat.Value,
longitude = lng.Value
}
};
}
/// <summary>
/// 腾讯位置服务地点搜索
/// </summary>
/// <remarks>
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/place/v1/search
/// - boundary 与前端一致:region(cityName,1),page_size=10
/// - 无匹配结果时返回空 list,不抛业务错误
///
/// 示例请求:
/// ```json
/// {
/// "keyword": "绿纤美业",
/// "region": "成都"
/// }
/// ```
///
/// 参数说明:
/// - keyword: 搜索关键词(必填)
/// - region: 城市名称,可选,默认「全国」
/// </remarks>
/// <param name="keyword">搜索关键词</param>
/// <param name="region">城市范围,可选,默认全国</param>
/// <returns>地点列表</returns>
/// <response code="200">搜索成功(含空列表)</response>
/// <response code="400">参数错误 / Key 缺失</response>
/// <response code="500">服务器内部错误</response>
[HttpGet("PlaceSearch")]
public async Task<TencentPlaceSearchOutput> PlaceSearch(
[FromQuery] string keyword,
[FromQuery] string region = null)
{
if (string.IsNullOrWhiteSpace(keyword))
throw NCCException.Oh("keyword 不能为空");
var cityName = string.IsNullOrWhiteSpace(region) ? "全国" : region.Trim();
var boundary = $"region({cityName},1)";
var path = $"/ws/place/v1/search?keyword={Uri.EscapeDataString(keyword.Trim())}"
+ $"&boundary={Uri.EscapeDataString(boundary)}&page_size=10";
var json = await CallTencentWsAsync(path, "腾讯地点搜索", throwOnBusinessError: false);
var status = json["status"]?.Value<int?>() ?? -1;
if (status != 0)
return new TencentPlaceSearchOutput();
var data = json["data"] as JArray;
if (data == null || data.Count == 0)
return new TencentPlaceSearchOutput();
var list = new List<TencentPlaceSearchItemDto>();
foreach (var item in data)
{
var lat = item["location"]?["lat"]?.Value<decimal?>();
var lng = item["location"]?["lng"]?.Value<decimal?>();
if (!lat.HasValue || !lng.HasValue)
continue;
list.Add(new TencentPlaceSearchItemDto
{
title = item["title"]?.ToString(),
address = item["address"]?.ToString(),
location = new TencentLocationDto
{
latitude = lat.Value,
longitude = lng.Value
}
});
}
return new TencentPlaceSearchOutput { list = list };
}
/// <summary>
/// 腾讯位置服务逆地址解析(经纬度 → 文字地址)
/// </summary>
/// <remarks>
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/geocoder/v1/(逆地址解析)
///
/// 示例请求:
/// ```json
/// {
/// "latitude": 30.572269,
/// "longitude": 104.066541
/// }
/// ```
///
/// 参数说明:
/// - latitude: 纬度(-90~90)
/// - longitude: 经度(-180~180)
/// </remarks>
/// <param name="latitude">纬度</param>
/// <param name="longitude">经度</param>
/// <returns>原始坐标与解析后的地址</returns>
/// <response code="200">解析成功</response>
/// <response code="400">参数错误 / Key 缺失 / 腾讯接口业务错误</response>
/// <response code="500">服务器内部错误</response>
[HttpGet("ReverseGeocode")]
public async Task<TencentReverseGeocodeOutput> ReverseGeocode(
[FromQuery] decimal? latitude,
[FromQuery] decimal? longitude)
{
if (!latitude.HasValue || !longitude.HasValue)
throw NCCException.Oh("latitude/longitude 不能为空");
if (latitude.Value < -90 || latitude.Value > 90)
throw NCCException.Oh("latitude 超出范围(-90~90)");
if (longitude.Value < -180 || longitude.Value > 180)
throw NCCException.Oh("longitude 超出范围(-180~180)");
var latStr = latitude.Value.ToString(CultureInfo.InvariantCulture);
var lngStr = longitude.Value.ToString(CultureInfo.InvariantCulture);
var path = $"/ws/geocoder/v1/?location={latStr},{lngStr}&get_poi=0";
var json = await CallTencentWsAsync(path, "腾讯逆地址解析", throwOnBusinessError: true, latStr, lngStr);
var address = json["result"]?["address"]?.ToString();
if (string.IsNullOrWhiteSpace(address))
{
_logger.LogWarning(
"腾讯逆地址解析返回无address lat={Lat} lng={Lng} body={Body}",
latStr,
lngStr,
Truncate(json.ToString(), 1200));
throw NCCException.Oh("腾讯逆地址解析返回地址为空");
}
return new TencentReverseGeocodeOutput
{
location = new TencentLocationDto
{
latitude = latitude.Value,
longitude = longitude.Value
},
address = address
};
}
/// <summary>
/// 读取腾讯位置服务 Key
/// </summary>
private string GetLbsKey()
{
var key = _configuration["NCC_App:TencentLbs:Key"]
?? _configuration["NCC_APP:TencentLbs:Key"];
if (string.IsNullOrWhiteSpace(key))
throw NCCException.Oh("腾讯位置服务 Key 未配置,请设置配置项 NCC_App:TencentLbs:Key(或环境变量映射)");
return key;
}
/// <summary>
/// 读取腾讯 WebService 超时秒数,默认 5 秒
/// </summary>
private int GetTimeoutSeconds()
{
var timeoutSecondsRaw = _configuration["NCC_App:TencentLbs:TimeoutSeconds"]
?? _configuration["NCC_APP:TencentLbs:TimeoutSeconds"];
var timeoutSeconds = 5;
if (!string.IsNullOrWhiteSpace(timeoutSecondsRaw)
&& int.TryParse(timeoutSecondsRaw, out var ts)
&& ts > 0)
{
timeoutSeconds = ts;
}
return timeoutSeconds;
}
/// <summary>
/// 调用腾讯 WebService(自动附加 Key),校验 HTTP 与 status==0
/// </summary>
/// <param name="relativeOrFullUrlWithoutKey">相对路径或不含 Key 的完整 URL</param>
/// <param name="operationName">日志中的操作名称</param>
/// <param name="throwOnBusinessError">status!=0 时是否抛错;PlaceSearch 无结果场景传 false</param>
/// <param name="contextArgs">附加日志上下文</param>
private async Task<JObject> CallTencentWsAsync(
string relativeOrFullUrlWithoutKey,
string operationName,
bool throwOnBusinessError = true,
params string[] contextArgs)
{
var url = BuildTencentUrl(relativeOrFullUrlWithoutKey);
var timeoutSeconds = GetTimeoutSeconds();
var sw = Stopwatch.StartNew();
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
var client = _httpClientFactory.CreateClient();
using var req = new HttpRequestMessage(HttpMethod.Get, url);
using var resp = await client.SendAsync(req, HttpCompletionOption.ResponseContentRead, cts.Token);
var body = await resp.Content.ReadAsStringAsync(cts.Token);
if (!resp.IsSuccessStatusCode)
{
_logger.LogWarning(
"{Operation} HTTP失败 status={Status} context={Context} costMs={CostMs} body={Body}",
operationName,
(int)resp.StatusCode,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds,
Truncate(body, 1200));
throw NCCException.Oh($"{operationName} HTTP 请求失败:{(int)resp.StatusCode}");
}
var json = JObject.Parse(body);
var status = json["status"]?.Value<int?>() ?? -1;
var message = json["message"]?.ToString() ?? "";
if (status != 0)
{
_logger.LogWarning(
"{Operation} 业务失败 status={Status} msg={Msg} context={Context} costMs={CostMs} body={Body}",
operationName,
status,
message,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds,
Truncate(body, 1200));
if (throwOnBusinessError)
throw NCCException.Oh($"{operationName}失败:{(message.Length > 0 ? message : "未知错误")}");
return json;
}
_logger.LogInformation(
"{Operation} 成功 context={Context} costMs={CostMs}",
operationName,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds);
return json;
}
catch (OperationCanceledException ex)
{
_logger.LogWarning(
ex,
"{Operation} 超时 context={Context} costMs={CostMs} timeoutSeconds={TimeoutSeconds}",
operationName,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds,
timeoutSeconds);
throw NCCException.Oh($"{operationName}超时({timeoutSeconds}s)");
}
catch (AppFriendlyException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"{Operation} 异常 context={Context} costMs={CostMs}",
operationName,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds);
throw NCCException.Oh($"{operationName}异常:{ex.Message}");
}
}
/// <summary>
/// 拼接腾讯 WebService 完整 URL 并附加 Key
/// </summary>
private string BuildTencentUrl(string relativeOrFullUrlWithoutKey)
{
var key = GetLbsKey();
var url = relativeOrFullUrlWithoutKey.StartsWith("http", StringComparison.OrdinalIgnoreCase)
? relativeOrFullUrlWithoutKey
: TencentWsBaseUrl + (relativeOrFullUrlWithoutKey.StartsWith("/")
? relativeOrFullUrlWithoutKey
: "/" + relativeOrFullUrlWithoutKey);
var separator = url.Contains("?", StringComparison.Ordinal) ? "&" : "?";
return url + separator + "key=" + Uri.EscapeDataString(key);
}
private static string Truncate(string text, int maxLen)
{
if (string.IsNullOrEmpty(text)) return text;
return text.Length <= maxLen ? text : text.Substring(0, maxLen) + "...";
}
}
}