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

如何在Flutter中发送带OAuth 1.0认证的HTTPS请求(适配WooCommerce API)

解决方案:DIO 结合 OAuth1.0 调用 WooCommerce API

1. 添加依赖

在pubspec.yaml中添加所需依赖:

dependencies:
  dio: ^5.x.x
  oauth1: ^2.x.x

执行flutter pub get(Flutter项目)或dart pub get(纯Dart项目)完成安装。

2. 核心代码实现

首先从WooCommerce后台获取Consumer Key和Consumer Secret,这是OAuth1认证的核心凭证。以下是完整的请求示例(以获取订单列表为例):

import 'package:dio/dio.dart';
import 'package:oauth1/oauth1.dart';

void main() async {
  // 替换为你的WooCommerce信息
  const consumerKey = '你的Consumer Key';
  const consumerSecret = '你的Consumer Secret';
  const storeBaseUrl = 'https://你的店铺域名/wp-json/wc/v3';

  // 初始化OAuth1平台配置
  final platform = Platform(
    '$storeBaseUrl/oauth1/request',
    '$storeBaseUrl/oauth1/authorize',
    '$storeBaseUrl/oauth1/access',
    SignatureMethods.hmacSha1, // WooCommerce固定使用HMAC-SHA1签名
  );

  // 创建OAuth1客户端
  final oauthClient = Client(Credentials(consumerKey, consumerSecret), platform);

  // 构造请求地址并生成OAuth签名头
  final requestUrl = '$storeBaseUrl/orders';
  final oauthHeaders = oauthClient.signRequest(
    Request('GET', Uri.parse(requestUrl)),
    Credentials('', ''), // WooCommerce用Client Credentials模式,此处留空即可
  );

  // 初始化DIO实例并发送请求
  final dio = Dio();
  try {
    final response = await dio.get(
      requestUrl,
      options: Options(headers: oauthHeaders),
    );
    print('请求成功:${response.data}');
  } on DioException catch (e) {
    print('请求失败:${e.response?.data ?? e.message}');
  }
}

3. 关键细节说明

  • 签名方式:WooCommerce OAuth1.0强制使用HMAC-SHA1签名,初始化Platform时必须指定SignatureMethods.hmacSha1。
  • 授权模式:WooCommerce采用Client Credentials模式,无需用户手动授权,直接用Consumer Key/Secret生成签名即可,因此Credentials('', '')无需填充内容。
  • 其他请求类型:POST/PUT/DELETE请求只需修改Request的方法参数(如Request('POST', Uri.parse(requestUrl))),请求体直接通过DIO的data参数传递,签名会自动处理请求参数和体内容。

4. 常见问题排查

  • 返回401 Unauthorized:检查Consumer Key/Secret是否正确、店铺域名是否匹配、签名方法是否为HMAC-SHA1。
  • 权限不足:确保后台创建的Consumer Key拥有对应操作的权限(如读取订单、修改产品等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:42:37