53 lines
1.8 KiB
Dart
53 lines
1.8 KiB
Dart
import 'dart:convert';
|
||
import 'package:url_launcher/url_launcher.dart';
|
||
|
||
class JDLauncher {
|
||
/// 跳转京东店铺(App 优先)
|
||
static Future<void> openShop(String shopUrlOrShortLink) async {
|
||
final isShortLink = shopUrlOrShortLink.contains("3.cn");
|
||
|
||
if (isShortLink) {
|
||
// 如果是短链接,比如 https://3.cn/xxxxx,直接尝试打开即可
|
||
await _launchJD(shopUrlOrShortLink);
|
||
} else {
|
||
// 如果是普通店铺链接,比如 https://mall.jd.com/index-xxxxxxx.html
|
||
final jdAppUrl = _buildJDAppUrl("m", {"url": shopUrlOrShortLink});
|
||
await _launchJD(jdAppUrl, fallbackUrl: shopUrlOrShortLink);
|
||
}
|
||
}
|
||
|
||
/// 跳转京东商品详情页(传入 SKU)
|
||
static Future<void> openProduct(String skuId) async {
|
||
final webUrl = "https://item.jd.com/$skuId.html";
|
||
final jdAppUrl = _buildJDAppUrl("productDetail", {"skuId": skuId});
|
||
await _launchJD(jdAppUrl, fallbackUrl: webUrl);
|
||
}
|
||
|
||
/// 构建京东 App 的 scheme 跳转 URL
|
||
static String _buildJDAppUrl(String des, Map<String, dynamic> extraParams) {
|
||
final params = {
|
||
"category": "jump",
|
||
"des": des,
|
||
...extraParams,
|
||
};
|
||
final encoded = Uri.encodeComponent(jsonEncode(params));
|
||
return "openapp.jdmobile://virtual?params=$encoded";
|
||
}
|
||
|
||
/// 通用跳转逻辑(优先跳 App,失败跳网页)
|
||
static Future<void> _launchJD(String url, {String? fallbackUrl}) async {
|
||
try {
|
||
final uri = Uri.parse(url);
|
||
if (await canLaunchUrl(uri)) {
|
||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||
} else if (fallbackUrl != null) {
|
||
await launchUrl(Uri.parse(fallbackUrl), mode: LaunchMode.externalApplication);
|
||
}
|
||
} catch (_) {
|
||
if (fallbackUrl != null) {
|
||
await launchUrl(Uri.parse(fallbackUrl), mode: LaunchMode.externalApplication);
|
||
}
|
||
}
|
||
}
|
||
}
|