Flutter美国邮政服务集成插件usps_sdk的使用

Flutter美国邮政服务集成插件usps_sdk的使用

United States Postal Service unofficial Software Development Kit

由Puerto Rico的Radamés J. Valentín Reyes制作。


Account Registration/Creation

  1. 前往https://www.usps.com/business/web-tools-apis/并点击“Register now”按钮以获取API Key(用户ID),该Key将通过电子邮件发送给您。
  2. 若要获取额外访问权限(如跟踪功能),请在https://gateway.usps.com/eAdmin/view/knowledge?securityId=MID创建账户。
  3. 向以下邮箱发送邮件请求额外权限(例如跟踪API):
    uspscustomersupport@usps.gov
    
    邮件内容应包括以下信息:
    I. Begin using USPS Web Tools  
    Shippers using a third-party shipping software or shopping cart provider: Refer to your software provider for instructions to begin using USPS Web Tools. If your software prompts you for URLs to access the USPS APIs, please use the production URL below.  
    
    Developers integrating Web Tools into a custom application:  
    The following URL is the production URL you will use to access the Web Tools Servers:  
    - https://secure.shippingapis.com/ShippingAPI.dll   
    
    Step-by-Step Instructions for All USPS Web Tools (important information when getting started):  
    - https://www.usps.com/business/web-tools-apis/general-api-developer-guide.pdf   
    
    API User’s Guides (API specific technical/integration information):  
    - https://www.usps.com/business/web-tools-apis/documentation-updates.htm   
    
    USPS Web Tools website: (contains all these resources and more):  
    - https://www.usps.com/business/web-tools-apis/welcome.htm
    
    II. Request Additional API Permissions  
    Additional API access and permissions are added separately. To obtain these permissions, contact our Internet Customer Care Center ([https://Emailus.usps.com/](https://emailus.usps.com/)) and include "Web Tools API Access" in the subject line. An agent will be happy to assist you.  
    
    1. To obtain Package Tracking API (API=TrackV2) access, users will need to contact the USPS Web Tools Program Office to request access and supply additional information for customer verification.  
        - Note: This applies to both TrackV2 API simplified track requests (i.e., “TrackRequest”) and TrackV2 API detailed track requests (i.e., “TrackFieldRequest”).  
    2. Users should follow these steps to submit a request for Tracking APIs access:  
        - Navigate to: https://usps.force.com/emailus/s/web-tools-inquiry. Provide user name (Web Tools User ID), select “Tracking APIs”, select “Track API” and submit the request with the following information below in the “Additional Information” text box:  
            - Web Tools UserID:  
            - Mailer ID (MID):  
            - Company Name:  
            - Requester First and Last Name:  
            - Requester Email:  
            - Requester Phone number:  
            - Mailing Address:  
            - Mailing City:  
            - Mailing State:  
            - Mailing Zip Code:  
            - PROD Registration Date:  
            - API access requested: Package Tracking (API=TrackV2)  
            - Anticipated volume:  
            - Any additional information from the customer:  
    
    Shipping label API access requires eVS setup/enrollment.  
    In general, eVS:  
    - Requires 50 pieces or 50 pounds per mailing  
    - Requires a permit imprint  
    - Requires payment via ACH debit daily (no other forms of payment)  
    - Handles origin entered mail (no destination entry or presort)  
    - Requires enrollment and new Mailer IDs (MIDs) and permits  
    - Will do domestic/international/APO/FPO/DPO/US Territories  
    For registration please visit: https://www.usps.com/postalone/evs.htm. Contact [eVS@usps.gov](mailto:eVS@usps.gov) for support. If that will not work for you, then you can follow up with [sales@usps.gov](mailto:sales@usps.gov) (or your local Postmaster or USPS Sales Manager) for additional solutions outside of the Web Tools APIs.  
    
    III. Troubleshoot/Additional Questions  
    1. Reference our FAQ document for common questions and concerns: https://www.usps.com/business/web-tools-apis/webtools-faqs.pdf   
    2. Contact your third-party software provider.  
    3. If still experiencing problems, our Internet Customer Care Center ([https://Emailus.usps.com/](https://emailus.usps.com/)) will investigate only if provided with the following:  
        - Copy of a sample XML request resulting in the issue or error, pasted into the body of the email  
        - Complete description of exact issue you are experiencing  
        - Name of API  
        - Name of third-party software provider
    

Import library/package:

import 'package:usps_sdk/usps_sdk.dart';

Getting Started

USPSSdk uspsSdk = USPSSdk(userID: userID);

SDK Functions

Address Information

Verify

地址验证API可以纠正街道地址中的错误,包括缩写和缺失信息,并提供邮政编码和邮政编码+4。通过消除地址错误,您可以提高整体包裹投递服务质量。

USPSAddress response = await uspsSdk.validate(
  address: USPSAddress(
    firmName: "", // 公司名称
    address1: "SUITE K", // 地址行1
    address2: "29851 Aventura", // 地址行2
    city: "", // 城市
    state: "CA", // 州
    zip5: "92688", // 五位邮政编码
    zip4: "", // 四位邮政编码
  ),
);
print(response.state); // 打印州
ZIP Code Lookup API

ZIP Code Lookup API返回给定地址、城市和州的邮政编码和邮政编码+4(使用USPS州缩写)。

USPSAddress response = await uspsSdk.zipCodeLookupAPI(
  address1: "SUITE K",
  address2: "29851 Aventura",
  state: "CA",
  zip5: "92688",
);
CityStateLookup API

City/State Lookup API返回给定邮政编码的城市和州。

USPSAddress response = await uspsSdk.cityStateLookup(
  zip5: 92688,
);
print(response.city); // 打印城市
print(response.state); // 打印州

Track and Confirm

Track and Confirm

跟踪和确认API用于跟踪包裹状态。

try {
  String response = await uspsSdk.trackAndConfirm(
    trackID: "9305589674000215488420",
  );
  print(response);
} catch (error) {
  if (error is USPSError) {
    print("--------------------------------------------------");
    print("Error code: ${error.errorCode}");
    print("Error description ${error.description}");
    print("Error source: ${error.source}");
    print("--------------------------------------------------");
  }
}

Rate Calculator

Domestic Rates

国内费率API允许客户根据物品的重量和尺寸计算国内包裹和信封的费用。

DomesticRates response = await uspsSdk.domesticRates(
  uspsServiceType: USPSServiceType.priority, // 优先服务类型
  zipOrigination: 32003, // 起始邮政编码
  zipDestination: 92688, // 目标邮政编码
  uspsContainer: USPSContainer.flatRateEnvelope, // 容器类型
  pounds: 2, // 磅数
  ounces: 0, // 盎司数
);
print(response.rate); // 打印费率
for (USPSSpecialService uspsSpecialService in response.availableServices) {
  print("Available"); // 是否可用
  print(uspsSpecialService.available);
  print("Price"); // 价格
  print(uspsSpecialService.price);
  print("Service ID"); // 服务ID
  print(uspsSpecialService.serviceID);
  print("Service Name"); // 服务名称
  print(uspsSpecialService.serviceName);
  print("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_");
}
International Rates

国际费率API允许客户根据物品的重量和尺寸计算国际包裹和信封的费用。

InternationalRates response = await uspsSdk.internationalRates(
  uspsServiceType: USPSServiceType.priority, // 优先服务类型
  zipOrigination: 32003, // 起始邮政编码
  pounds: 2, // 磅数
  ounces: 0, // 盎司数
  width: 6, // 宽度
  height: 6, // 高度
  length: 6, // 长度
  country: "Australia", // 目标国家
);

EVS Label(Shipping Label)

电子可变数据标签API用于生成电子可变数据标签。


Package Pickup

包裹取件API用于安排包裹取件。


Error catching

try {
  String response = await uspsSdk.trackAndConfirm(
    trackID: "9305589674000215488420",
  );
  print(response);
} catch (error) {
  if (error is USPSError) {
    print("--------------------------------------------------");
    print("Error code: ${error.errorCode}");
    print("Error description ${error.description}");
    print("Error source: ${error.source}");
    print("--------------------------------------------------");
  }
}

更多关于Flutter美国邮政服务集成插件usps_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter美国邮政服务集成插件usps_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


要在Flutter应用中集成美国邮政服务(USPS)的SDK,你可以使用usps_sdk插件。这个插件允许你与USPS API进行交互,实现诸如地址验证、邮政编码查询、运费计算等功能。

以下是如何在Flutter项目中使用usps_sdk的基本步骤:

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加usps_sdk插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  usps_sdk: ^1.0.0  # 请使用最新版本

然后运行flutter pub get来获取依赖。

2. 获取USPS API密钥

在使用USPS API之前,你需要注册一个USPS开发者账号并获取API密钥。你可以通过访问USPS Web Tools API来注册并获取密钥。

3. 初始化USPS SDK

在你的Flutter应用中初始化usps_sdk插件。

import 'package:usps_sdk/usps_sdk.dart';

void main() {
  // 初始化USPS SDK
  UspsSdk.initialize(apiKey: 'YOUR_USPS_API_KEY');
  runApp(MyApp());
}

4. 使用USPS API功能

usps_sdk插件提供了多种功能,下面是一些常见的使用示例。

地址验证

你可以使用USPS API来验证地址。

Future<void> validateAddress() async {
  try {
    final response = await UspsSdk.validateAddress(
      address: UspsAddress(
        address1: '123 Main St',
        city: 'Anytown',
        state: 'CA',
        zip5: '90210',
      ),
    );

    if (response.isValid) {
      print('Address is valid: ${response.address}');
    } else {
      print('Address is invalid');
    }
  } catch (e) {
    print('Error validating address: $e');
  }
}

邮政编码查询

你可以查询某个地址的邮政编码。

Future<void> getZipCode() async {
  try {
    final response = await UspsSdk.getZipCode(
      address: UspsAddress(
        address1: '123 Main St',
        city: 'Anytown',
        state: 'CA',
      ),
    );

    print('Zip Code: ${response.zip5}');
  } catch (e) {
    print('Error getting zip code: $e');
  }
}

运费计算

你可以计算某个包裹的运费。

Future<void> calculateShippingRate() async {
  try {
    final response = await UspsSdk.calculateShippingRate(
      fromZip: '90210',
      toZip: '10001',
      weightInPounds: 2.0,
    );

    print('Shipping Rate: \$${response.rate}');
  } catch (e) {
    print('Error calculating shipping rate: $e');
  }
}

5. 处理错误

在使用USPS API时,可能会遇到各种错误,如网络错误、API限制等。你可以通过try-catch块来捕获并处理这些错误。

try {
  // 调用USPS API
} catch (e) {
  print('Error: $e');
}
回到顶部