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

如何在Checkout UI Extensions中获取选中的配送方式

使用deliveryGroups API获取选中的配送方式

要在你的Checkout UI扩展中获取用户选中的配送方式,你可以直接从useExtensionApi中解构出deliveryGroups对象,通过监听它的变化来实时获取当前选中的配送选项。以下是修改后的完整代码:

import {
  useExtensionApi,
  render,
  TextField,
  useApplyAttributeChange,
} from '@shopify/checkout-ui-extensions-react';
import { useState, useEffect } from 'react'; // 补充缺失的React钩子导入

render("Checkout::ShippingMethods::RenderAfter", () => <App />);

function App() {
  const { extensionPoint, deliveryGroups } = useExtensionApi(); // 解构出deliveryGroups
  const [shippingAccountInfo, setShippingAccountInfo] = useState('');
  const [selectedShippingMethod, setSelectedShippingMethod] = useState(null);

  const handleShippingChange = (val) => {
    setShippingAccountInfo(val)
  }

  const applyAttributeChange = useApplyAttributeChange();

  // 监听配送方式变化,获取选中的配送选项
  useEffect(() => {
    // 单地址结账场景下取第一个配送组即可
    const activeDeliveryGroup = deliveryGroups[0];
    if (activeDeliveryGroup?.selectedDeliveryOption) {
      setSelectedShippingMethod(activeDeliveryGroup.selectedDeliveryOption);
    }
  }, [deliveryGroups]);

  useEffect(() => {
    if (shippingAccountInfo && selectedShippingMethod) {
      async function updateShippingAttribute() {
        // 可将配送方式信息与用户账号信息结合存入属性
        const attributeValue = JSON.stringify({
          accountInfo: shippingAccountInfo,
          shippingMethod: {
            id: selectedShippingMethod.id,
            title: selectedShippingMethod.title,
            handle: selectedShippingMethod.handle
          }
        });
        await applyAttributeChange({
          type: 'updateAttribute',
          key: 'shipping_info',
          value: attributeValue,
        });
      }

      updateShippingAttribute()
    }
  }, [shippingAccountInfo, applyAttributeChange, selectedShippingMethod]);


  return (
    <>
      <TextField
        label="配送账户信息:(输入承运商及账户编号)"
        name="shipping_account_info"
        value={shippingAccountInfo}
        onChange={(str) => handleShippingChange(str)}
      />
      {/* 可选:展示当前选中的配送方式 */}
      {selectedShippingMethod && (
        <p>当前选中配送方式: {selectedShippingMethod.title}</p>
      )}
    </>
  );
}

关键说明

  • deliveryGroups是一个数组,对应结账流程中的每个配送组(多地址结账会存在多个),单地址场景下取第一个元素即可
  • selectedDeliveryOption包含选中配送方式的核心信息:id(唯一标识)、title(显示名称)、handle(配送方式标识)、price等
  • 通过useEffect监听deliveryGroups的变化,能实时捕获用户切换配送方式的操作
  • 可根据业务需求,将配送方式信息与用户输入的账号信息结合,统一存入结账属性中

内容的提问来源于stack exchange,提问作者Alex Zelinsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:12:30