import 'dart:convert'; import 'package:url_launcher/url_launcher.dart'; class JDLauncher { /// 跳转京东店铺(App 优先) static Future 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 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 extraParams) { final params = { "category": "jump", "des": des, ...extraParams, }; final encoded = Uri.encodeComponent(jsonEncode(params)); return "openapp.jdmobile://virtual?params=$encoded"; } /// 通用跳转逻辑(优先跳 App,失败跳网页) static Future _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); } } } }