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

如何用VB.NET在WooCommerce为指定ProductID添加Small/Red商品规格

在VB.NET中为WooCommerce产品添加Small/Red规格

既然你已经为目标ProductID添加了Size和Color属性,接下来只需通过WooCommerce REST API创建对应属性组合的产品变体即可。以下是具体实现步骤和代码示例:

核心步骤说明

  1. 准备API凭据:从WooCommerce后台获取商店URL、消费者密钥(Consumer Key)和消费者密码(Consumer Secret)。
  2. 构造变体请求数据:指定Size属性值为Small、Color属性值为Red,同时补充价格、库存等必填或可选字段。
  3. 发送POST请求:调用WooCommerce的products/{product_id}/variations接口创建变体。

VB.NET代码实现

Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text
Imports Newtonsoft.Json ' 需要引用Newtonsoft.Json NuGet包

Public Class WooCommerceVariantCreator
    Public Async Function AddSmallRedVariantAsync(productId As Integer, storeUrl As String, consumerKey As String, consumerSecret As String) As Task(Of String)
        ' 构建API端点URL
        Dim apiEndpoint As String = $"{storeUrl}/wp-json/wc/v3/products/{productId}/variations"

        ' 构造变体数据(根据需求调整价格、库存等字段)
        Dim variantData As New With {
            .regular_price = "19.99", ' 常规价格
            .attributes = New List(Of Object) From {
                New With {
                    .id = 0, ' 替换为Size属性的实际ID(可通过GET /products/attributes获取)
                    .name = "Size",
                    .option = "Small"
                },
                New With {
                    .id = 1, ' 替换为Color属性的实际ID
                    .name = "Color",
                    .option = "Red"
                }
            },
            .manage_stock = True,
            .stock_quantity = 50
        }

        ' 序列化JSON数据
        Dim jsonContent As String = Newtonsoft.Json.JsonConvert.SerializeObject(variantData)
        Dim content As New StringContent(jsonContent, Encoding.UTF8, "application/json")

        ' 创建HttpClient并设置认证
        Using client As New HttpClient()
            ' Basic Auth认证:将密钥和密码拼接后Base64编码
            Dim authToken As String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{consumerKey}:{consumerSecret}"))
            client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", authToken)

            ' 发送POST请求
            Dim response As HttpResponseMessage = Await client.PostAsync(apiEndpoint, content)
            response.EnsureSuccessStatusCode() ' 确保请求成功,否则抛出异常

            ' 返回响应内容
            Return Await response.Content.ReadAsStringAsync()
        End Using
    End Function
End Class

关键注意事项

  • 属性ID替换:代码中.id字段需要替换为你实际的Size和Color属性ID,可通过调用GET /wp-json/wc/v3/products/attributes接口获取所有属性的ID信息。
  • API版本:示例使用WooCommerce REST API v3版本,确保你的商店支持该版本(后台可查看API设置)。
  • 必填字段:regular_price是变体的必填字段,若不需要设置价格可设为"0",但需符合WooCommerce的配置规则。
  • 错误处理:实际使用时建议添加异常捕获逻辑,处理网络错误、API返回的错误信息等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:40:33