You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Shopify应用中根据用户位置获取价格及单价?

Flutter Shopify 按用户位置获取商品价格实现方案

一、先完成Shopify后台配置

要实现按位置定价,首先得在Shopify端设置对应规则:

  • 进入Shopify后台 → 产品 → 价格规则,创建新规则。选择「基于地理位置」作为条件,可按国家/地区、省份设置价格调整(固定金额或百分比)。
  • 若原生功能不够,可启用「多地点库存/价格」功能,或用第三方定价类APP补充支持。

二、Flutter端实现步骤

1. 完善用户位置获取(基于你已用的Geolocation)

除了获取经纬度,还需转成Shopify能识别的地区代码(如ISO国家代码),示例代码:

import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';

Future<String?> getUserCountryCode() async {
  // 申请位置权限
  LocationPermission permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) return null;
  }

  // 获取当前位置
  Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
  // 转成地址信息提取国家代码
  List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
  return placemarks.isNotEmpty ? placemarks.first.isoCountryCode : null;
}

注意:需在pubspec.yaml中添加geocoding依赖,同时在iOS的Info.plist和Android的AndroidManifest.xml中配置位置权限描述。

2. 调用Shopify API获取对应位置的价格

Shopify的Storefront API支持通过country参数返回指定地区的商品价格,以下是两种实现方式:

方式一:GraphQL调用(推荐)

import 'package:graphql_flutter/graphql_flutter.dart';

Future<Map<String, dynamic>?> getProductPrice(String productId, String countryCode) async {
  final GraphQLClient client = GraphQLClient(
    link: HttpLink('https://你的店铺域名.myshopify.com/api/2024-07/graphql.json'),
    cache: GraphQLCache(),
  );

  final String query = '''
    query GetProduct(\$id: ID!, \$country: CountryCode!) {
      product(id: \$id) {
        variants(first: 10) {
          edges {
            node {
              priceV2(country: \$country) {
                amount
                currencyCode
              }
              title
            }
          }
        }
      }
    }
  ''';

  final QueryResult result = await client.query(
    QueryOptions(
      document: gql(query),
      variables: {
        'id': productId,
        'country': countryCode.toUpperCase(),
      },
    ),
  );

  if (result.hasException) {
    print(result.exception.toString());
    return null;
  }
  return result.data;
}

方式二:REST API调用

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<dynamic> getProductRestPrice(String productHandle, String countryCode) async {
  final response = await http.get(
    Uri.parse('https://你的店铺域名.myshopify.com/api/2024-07/products/$productHandle.json?country=$countryCode'),
    headers: {
      'X-Shopify-Storefront-Access-Token': '你的Storefront令牌',
    },
  );

  if (response.statusCode == 200) {
    return json.decode(response.body);
  } else {
    print('请求失败:${response.statusCode}');
    return null;
  }
}

3. 解析并展示价格

获取数据后,直接解析展示即可:

void loadProductPrice() async {
  String? countryCode = await getUserCountryCode();
  if (countryCode == null) {
    // 位置获取失败时,加载默认价格
    return;
  }
  var productData = await getProductPrice('gid://shopify/Product/你的商品ID', countryCode);
  if (productData != null) {
    var variants = productData['product']['variants']['edges'];
    for (var variant in variants) {
      var priceInfo = variant['node']['priceV2'];
      print('${variant['node']['title']}: ${priceInfo['amount']} ${priceInfo['currencyCode']}');
      // 将价格渲染到UI组件中
    }
  }
}

三、关键注意事项

  • 权限兜底:若用户拒绝位置权限,提供手动选择地区的入口,避免无法展示价格。
  • 测试验证:切换不同地区(可通过调试工具模拟位置),确认Shopify后台的价格规则是否生效。
  • 令牌安全:Storefront令牌需妥善保管,避免硬编码在客户端,可通过后端代理请求。

内容的提问来源于stack exchange,提问作者Eriny Elkess Antonus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:58:11