SureTax for General Sales and Use Tax

Comprehensive tax compliance for retail, e-commerce, wholesale, and service-based transactions across 13,000+ U.S. jurisdictions

SureTax Calculations SureTax Returns General Merchandise Content SureTax ECM Compliance Reports

Introduction

General sales and use tax compliance presents significant challenges for businesses operating across multiple jurisdictions. With over 13,000 state and local tax jurisdictions in the United States alone, each with unique rates, rules, and filing requirements, managing accurate tax determination and return filing at scale is a complex undertaking. SureTax for General Sales and Use Tax is Wolters Kluwer's comprehensive tax compliance solution designed to address these challenges, delivering accurate, automated tax determination across retail, e-commerce, wholesale, and service-based transactions.

SureTax for General Sales and Use Tax simplifies compliance for businesses selling tangible personal property, digital goods, and taxable services by automating the calculation of transaction-based taxes and managing exemptions, product taxability, and nexus requirements. It is delivered as a complete, bundled solution that includes SureTax Calculations, SureTax Returns, General Merchandise Content, SureTax ECM, and comprehensive reporting tools — everything you need in a single package. It supports both realtime and batch processing, integrates with leading ERP and e-commerce platforms, and is backed by continuously updated tax content maintained by Wolters Kluwer's team of tax research experts.

Capabilities

SureTax for General Sales and Use Tax provides a comprehensive set of capabilities tailored to multi-jurisdiction sales tax compliance:

CapabilityDescription
Multi-Jurisdiction SupportHandles tax calculations across all state, county, city, and special district jurisdictions in the United States, ensuring accurate rate determination for every transaction.
Product TaxabilityApplies jurisdiction-specific taxability rules based on product categories, ensuring correct treatment of groceries, clothing, digital goods, services, and other product types with varying tax treatment.
Exemptions ManagementManages resale certificates, government exemptions, nonprofit exemptions, manufacturing exemptions, and industry-specific exemption scenarios.
Origin & Destination SourcingDetermines correct sourcing methodology (origin vs. destination) based on jurisdiction rules, product type, and customer location.
Economic NexusSupports nexus tracking and threshold monitoring to ensure compliance with economic nexus requirements following the Wayfair decision.
Use Tax CalculationAutomatically calculates use tax for out-of-state purchases where sales tax was not collected.
Tax HolidaysApplies jurisdiction-specific tax holiday rules for qualifying periods and product categories.
Shipping & HandlingCorrectly taxes shipping and handling charges based on jurisdiction-specific rules and taxability of the underlying goods.
Marketplace Facilitator RulesSupports compliance with marketplace facilitator laws where applicable, distinguishing between marketplace and direct seller obligations.
Realtime Tax CalculationProvides sub-second tax determination for point-of-sale, e-commerce checkouts, and self-service transactions.
Audit & ReportingGenerates comprehensive audit trails and compliance reports to support internal reviews, regulatory audits, and return preparation.
IntegrationsConnects with ERP systems, e-commerce platforms, and custom applications through APIs, SDKs, and pre-built connectors.
Drop Shipment HandlingManages complex drop shipment scenarios where the seller, customer, and shipper are in different jurisdictions.
Returns & RefundsSupports tax adjustments for returns, refunds, and credits with proper jurisdiction-level tracking.
Discounts & PromotionsCorrectly taxes discounted transactions, promotional pricing, and coupon redemptions based on jurisdiction rules.
Bundled TransactionsHandles mixed bundles where taxable and non-taxable items are sold together, applying jurisdiction-specific bundling rules.
Local Tax RatesApplies county, city, and special district rates in addition to state-level rates, ensuring complete jurisdiction coverage.
Customer-Level Tax SettingsManages customer-specific tax profiles, exemption certificates, and jurisdiction overrides.
API SupportProvides RESTful APIs for integration with any system capable of making HTTP requests.
Tax ForecastingEnables forward-looking tax estimates for pricing, quoting, and financial planning.
Invoice BreakdownProvides granular tax breakdowns by authority, tax type, and jurisdiction for transparent invoicing and customer communication.
Electronic FilingSupports electronic filing of sales and use tax returns and remittance across applicable jurisdictions.
Custom Rules EngineAllows configuration of custom rules and overrides to accommodate unique business scenarios, contractual obligations, or industry-specific requirements.
Rate Change ManagementAutomatically applies updated tax rates as they are released by jurisdictions, with no manual configuration required.
Digital Goods & ServicesApplies correct tax treatment for digital products, SaaS, and cloud-based services subject to evolving tax rules.
Threshold TrackingMonitors transaction thresholds for economic nexus, marketplace facilitator obligations, and other compliance triggers.
Sales Tax PermitsTracks sales tax permit statuses, renewal dates, and jurisdiction registration details.
Consolidated ReturnsSupports filing of consolidated returns across multiple legal entities and locations.
Accrual vs. Cash BasisAccommodates both accrual and cash-basis accounting methods for tax reporting.

What's Included

SureTax for General Sales and Use Tax is a bundled solution — all of the applications, content, and tools you need are included out of the box.

ComponentDescription
General Merchandise ContentContinuously updated sales and use tax rates, rules, jurisdiction data, and product taxability matrices maintained by Wolters Kluwer's tax research team. This is the tax intelligence that powers all calculations.
SureTax CalculationsThe core tax calculation engine. Processes transactions in realtime or batch mode and returns accurate tax amounts, rates, and jurisdiction details for each line item.
SureTax ReturnsAutomates the preparation, review, and filing of sales and use tax returns across all applicable jurisdictions.
SureTax ECMExemption Certificate Management — stores, validates, and tracks exemption certificates to ensure proper exemption handling and audit readiness.
Compliance ReportsPre-built reporting suite providing audit trails, liability summaries, nexus reports, and jurisdiction-level breakdowns tailored to sales and use tax compliance.

Configuring Your Solution

Since all components are bundled, getting started focuses on configuration rather than procurement:

  1. Company Profile — Set up your company information, tax registration details, nexus jurisdictions, and default settings in the SureTax portal.
  2. Tax Content Configuration — Configure the general merchandise content for your specific product catalog, jurisdictions, and customer types. The content is pre-loaded — you select and activate the rules relevant to your business.
  3. SureTax Calculations — Configure calculation settings such as default sourcing rules, rounding behavior, and any company-specific overrides or custom rules.
  4. SureTax Returns — Set up your return filing jurisdictions, filing frequencies, and review workflows.
  5. SureTax ECM — Configure exemption certificate types, validation rules, and expiration tracking for your customer base.
  6. Compliance Reports — Configure your reporting preferences, schedule recurring reports, and set up distribution lists.
💡 Tip
Your Wolters Kluwer implementation team will guide you through the initial configuration. Once configured, ongoing adjustments can be made directly in the SureTax portal.

Off-the-Shelf Integrations

For organizations using a supported ERP or e-commerce platform, Wolters Kluwer provides pre-built connectors that simplify integration. These connectors handle the communication between your system and SureTax, reducing development effort and accelerating time to value.

ERP / E-Commerce PlatformDescription
AcumaticaCloud ERP connector for Acumatica-based environments.
BigCommerceE-commerce connector for BigCommerce storefronts.
Dynamics 365 Business CentralConnector for Microsoft Dynamics 365 Business Central.
Dynamics 365 Finance & Operations / CommerceConnector for Microsoft Dynamics 365 Finance & Operations and Commerce modules.
Dynamics GPConnector for Microsoft Dynamics GP (Great Plains).
Dynamics AXConnector for Microsoft Dynamics AX.
MagentoE-commerce connector for Adobe Commerce (Magento).
NAVConnector for Microsoft Dynamics NAV.
NetSuiteConnector for Oracle NetSuite.
Salesforce Commerce CloudConnector for Salesforce Commerce Cloud (formerly Demandware).
SAP S/4HANA CloudConnector for SAP S/4HANA Cloud environments.
SAP S/4HANA On-PremiseConnector for on-premise SAP S/4HANA deployments.
WooCommerceE-commerce connector for WooCommerce (WordPress).
💡 Tip
If your ERP or e-commerce platform is listed above, the off-the-shelf connector is the fastest path to integration. Contact your Wolters Kluwer representative for connector availability and setup guidance.

Integration Workflows at a Glance

SureTax for General Sales and Use Tax exposes a complete set of API-driven workflows that mirror the end-to-end tax compliance lifecycle — from realtime tax calculation and entity setup through batch processing, return preparation, review, filing, and reporting. Each workflow is a discrete, composable building block: you can adopt them individually, chain them together in sequence, or orchestrate them programmatically to fit your existing operational processes.

These workflows are designed for retailers, e-commerce operators, and compliance teams who need to embed tax compliance directly into their billing, ERP, or client-facing platforms — without requiring users to leave your application or learn a separate portal. Every workflow operates through standard RESTful APIs with OAuth 2.0 authentication, JSON payloads, and consistent response patterns, making them straightforward to integrate from any language or platform.

AI Agent and Automation Ready

Because every workflow is a stateless, API-first operation with clearly defined inputs and outputs, they are inherently compatible with AI agent frameworks, robotic process automation (RPA), and intelligent orchestration platforms. An AI agent can authenticate, discover entities, calculate taxes, upload transactions, generate returns, review change logs, and extract compliance reports — all through the same API contracts documented below. Whether you are building a conversational compliance assistant, an autonomous filing pipeline, or an AI-augmented analyst workbench, these workflows provide the structured, deterministic API surface your agents need.

Workflow Summary

#WorkflowWhat It DoesSection
1Realtime Tax CalculationCalculate taxes in realtime for point-of-sale, e-commerce, and self-service portal transactions. Submit individual transactions via the Realtime API or SDK and receive sub-second responses with itemized tax amounts, rates, and jurisdiction details.Integrate with SureTax Realtime
2Account / Entity CreationDiscover and provision the Legal Filing Entities (LFEs) that scope all downstream operations — batch uploads, returns, and reporting — to a specific legal organization or client.Account/Legal Entity Creation
3Account / Entity ConfigurationEstablish each LFE’s compliance profile: tax authority relationships, filing jurisdictions, frequencies, license numbers, and contact details. This is the foundation that tells SureTax where and how each entity files.Account/Legal Entity Configuration
4Batch Transaction ProcessingUpload high-volume transaction files (CDRs, billing extracts, aggregated summaries) for asynchronous tax calculation. Supports multiple import templates tailored to telecom — forward calculation, gross-up, and external tax summary formats.Integrate with SureTax Batch
5Tax Return GenerationTrigger the asynchronous generation of tax return documents from processed transaction data. The Returns API discovers filing obligations, generates form instances, and tracks generation progress.Tax Return Generation Workflow
6PDF Return DownloadRetrieve completed tax returns as downloadable PDF documents via pre-signed, time-limited URLs — suitable for archiving, distribution, or offline review.Download Your PDF Tax Return
7Inline Review & AdjustmentEmbed the SureTax form viewer or editor directly in your application using an iframe. Analysts can review returns in read-only mode or make line-item adjustments in edit mode — with a full audit trail of every change.Reviewing and Adjusting Tax Returns Inline
8Electronic FilingSubmit approved returns to taxing authorities electronically. Track submission status from “Submitted to Government” through acceptance or rejection, and handle corrections when needed.E-Filing Tax Returns
9Compliance Report ExtractionPull post-filing compliance reports — aggregate summaries, invoice-level detail, jurisdiction breakdowns — for internal analysis, audit defense, and regulatory reporting.Extracting Reports for Analysis

Typical End-to-End Flow

Realtime Calc Entity Setup Configuration Batch Upload Return Gen Download / Review E-File Extract Reports
📝 Note
Realtime calculation (workflow 1) and batch processing (workflow 4) serve different integration patterns. Realtime is for individual, on-demand transactions during a customer interaction. Batch is for high-volume, periodic processing of accumulated transactions (e.g., monthly billing cycles). Most organizations use one or both depending on their billing architecture.
💡 Tip
You do not need to implement every workflow at once. Many organizations start with Realtime Calculation (workflow 1) or Batch Upload (workflow 4) and Return Generation (workflow 5), then layer on inline review, e-filing, and reporting as their integration matures.

The sections below walk through each workflow in detail — including API endpoints, request/response examples, and complete working code in Bash, JavaScript, Python, and C#.

Integrate with SureTax Realtime

SureTax Realtime is designed for scenarios that require immediate tax determination — such as point-of-sale transactions, e-commerce checkouts, and self-service customer portals. Realtime integration delivers sub-second tax responses, making it suitable for any user-facing or transactional system where tax must be calculated before the transaction is completed.

How It Works

  1. Your application sends a tax calculation request to the SureTax Realtime API with transaction details (product details, customer location, charge amounts, etc.).
  2. SureTax processes the request against current tax content (rates, rules, jurisdiction data, product taxability).
  3. A response is returned with the calculated tax amounts, applicable rates, tax type breakdowns, and jurisdiction details.

Integration Options

RESTful API

Make direct HTTP requests from any application capable of sending and receiving JSON.

SDK

Streamlined integration in supported languages. Handles auth, serialization, and error handling.

💡 Best Practice
Use the SDK when available for your platform. It simplifies error handling, retry logic, and version management compared to raw API calls.

Realtime API Reference

The Realtime API uses inline authentication — your Client Number and Validation Key are included directly in each JSON request body. There is no separate OAuth token step.

DetailValue
Endpoint/Services/V07/SureTax.asmx/PostRequest
MethodPOST
Content-Typeapplication/x-www-form-urlencoded
AuthenticationClientNumber + ValidationKey (per-request)

Environments

EnvironmentBase URL
CERT (Testing)https://testapi.taxrating.net
Productionhttps://api.taxrating.net
💡 Recommendation
Always develop and test against the CERT environment first.

Transaction Lifecycle

The Realtime API supports a transaction lifecycle using the ReturnFileCode field:

ReturnFileCodeModeDescription
QQuoteCalculate taxes for estimation only. No data is saved. Ideal for development and testing.
TIn-ProgressCalculate and save. Transaction can be updated or cancelled.
0FinalizedCalculate and lock for compliance reporting. Transaction cannot be modified.
💡 Tip
Use ReturnFileCode: "Q" during development — no data is saved, and you can iterate freely without affecting compliance data.

Rate Limits and Request Size Limits

All Realtime API calls are subject to rate limiting and request size restrictions enforced at the network edge by a Web Application Firewall (WAF). Design your integration with these limits in mind from the start.

LimitThreshold
Requests per minute8,000/min
Maximum request size6 MB

Rate limiting uses a sliding 60-second window. The system tracks requests received within the most recent 60 seconds. Once 8,000 requests have been accepted in that window, additional requests are rejected. When this happens, the client must wait for the 60-second window to elapse before new requests are accepted.

⚠️ Important — 403 Responses
When rate limits or request size limits are exceeded, the API returns a 403 Forbidden — not 429 Too Many Requests or 413 Payload Too Large. This is because these limits are enforced by a WAF layer upstream of the API itself. A 403 does not always mean an authentication or authorization failure — it may be a rate limiting or size blocking response.

Handling a 403 Response

ScenarioIndicatorsAction
Security 403Invalid or expired ClientNumber/ValidationKeyVerify credentials
Rate Limiting 403Credentials are valid; high request volumeWait 60 seconds, then retry
Size Blocking 403Credentials are valid; large request payloadSplit payload into smaller batches under 6 MB

Recommendations

Integrate with SureTax Batch

SureTax Batch is designed for high-volume, file-based tax processing. It is ideal for scenarios where transactions are accumulated over a period (e.g., a monthly sales cycle) and processed together, rather than individually in realtime. The Batch Upload API uses OAuth 2.0 authentication and provides three operations that form a complete upload-process-download workflow.

Key Features

FeatureDescription
High VolumeProcess thousands to millions of transactions in a single batch job.
AccuracyApplies the same tax content and rules as SureTax Realtime, ensuring consistent results.
ScalabilityAutomatically scales to handle large files without manual infrastructure management.
Error HandlingProvides detailed error reporting at the line-item level, enabling targeted corrections.
SecurityAll data is transmitted and stored securely using industry-standard encryption.

Batch Upload API Endpoints

StepOperationEndpointMethodDescription
1Get TokenOAuth Token URLPOSTObtain an OAuth 2.0 Bearer token using client credentials
2Upload/SureTax/api/v1/Batch/UploadPOSTUpload a CSV file for async processing; returns a Job ID
3Status/SureTax/api/v1/Batch/Status?jobId={id}GETPoll job status (In Progress, Completed, Failed). When a job fails, the response includes an array of error objects — each containing the field, value, and message — so you can diagnose every issue in a single call without re-polling.
4Download/SureTax/api/v1/Download?jobId={id}GETDownload results as a ZIP file once completed
5Upload History/SureTax/api/v1/Batch/UploadHistory?lfeId={id}&fromDate={date}&toDate={date}GETRetrieve a log of all batch uploads for a given LFE within a date range. Each entry includes the Job ID, upload timestamp, status (Completed, Failed), and record counts — useful for auditing and tracking prior uploads.

Workflow

1
Get Token
OAuth 2.0
→
2
Upload CSV
POST → Job ID
→
3
Poll Status
~60 s intervals
→
4
Download
ZIP results

General Sales and Use Tax Batch Import Templates

SureTax provides several batch import templates designed for sales and use tax processing. The template you choose depends on your data format, processing needs, and whether you are submitting individual transactions or pre-aggregated summaries. Review the table below to select the right template for your use case.

Template Batch API Config. Name Data Level Use Case Description
Communication Tax Summary Grossup ExternalTaxSummaryGrossup Pre-aggregated summaries Aggregated communications tax data. Use this template when your source system provides pre-aggregated tax summaries rather than individual transactions. Each row represents a rolled-up tax summary for a unique combination of Service Group, Tax Type, Tax Category, Authority Level, and jurisdiction. Ideal for loading compliance data from external systems. Flat CSV; 23 fields including aggregated revenue totals, taxable base, rates, and computed tax amounts.
Communications Batch Import Template — Transaction line items Primary telecom batch processing. Use this template when you have individual call detail records (CDRs) or line-item transactions that need tax calculated. Uses a three-record-type layout (Header, Detail, Trailer) with full telecom situs fields including origination, termination, and bill-to numbers. Supports wireline, wireless, VoIP, and other telecom services. H/D/Z record format; each Detail record is a single taxable event.
Forward Calculation Template ForwardCalculation Transaction line items General-purpose forward calculation. Use this template when you have the revenue amount and need SureTax to calculate the taxes owed. Each row represents a single transaction. This is the most common method and works for both telecom and general merchandise transactions. Flat CSV; one row per line item with transaction date, customer info, service address, transaction type code, revenue, and regulatory codes.
Gross-Up Template GrossUp Transaction line items Tax-inclusive pricing. Use this template when you have the total charge (inclusive of tax) and need SureTax to back-calculate the tax and pre-tax revenue. Common for tax-inclusive pricing models. SureTax spreads the taxes across applicable jurisdictions for compliance reporting. Flat CSV; similar to Forward Calculation but uses gross (tax-inclusive) amounts instead of net revenue.
Aggregated Summary Transactions Import Template — Pre-aggregated summaries General aggregated summaries. Use this template when you have pre-aggregated transaction summaries rolled up by filing period, tax type, jurisdiction, and service group. Works for both telecom and general merchandise. Commonly used for compliance reporting and reconciliation workflows. Flat CSV; summarized revenue, exemption, and tax totals by jurisdiction and tax type.

Choosing the Right Template

Understanding the Batch API Config. Name

The Batch API Config. Name is a required value you must pass in the requestData JSON payload when uploading a batch file via the Batch Upload API. It tells SureTax which file layout and processing rules to apply to your CSV. When constructing your upload request, include it as the configurationName field:

JSON — requestData payload
{
  "legalEntityCode": "A001670001",
  "fileLayoutVersion": "1.0",
  "configurationName": "Aggregated Tax Summary",
  "dataYearMonth": "202601",
  "complianceYearMonth": "202601"
}
📝 Note
When using ExternalTaxSummaryGrossup, the complianceYearMonth field is required. For ForwardCalculation and GrossUp, it is optional and defaults to dataYearMonth if omitted.

Each configuration name maps to a specific template and processing behavior:

Batch API Config. Name Processing Behavior
ForwardCalculation SureTax reads net revenue amounts from the CSV and calculates all applicable taxes forward.
GrossUp SureTax reads tax-inclusive totals and back-calculates the pre-tax revenue and tax breakdown per jurisdiction.
ExternalTaxSummaryGrossup SureTax imports pre-aggregated tax summaries from an external source for compliance reporting and reconciliation — no tax calculation is performed.
⚠️ Note
The configurationName value is case-sensitive and must exactly match one of the values listed above. Using an incorrect or missing configuration name will cause the upload to be rejected.
💡 Tip
Detailed field definitions, example CSVs, and downloadable CSV templates are available on each template’s reference page. Click the template name in the table above to view the full specification.
⚠️ Important
Ensure your batch file adheres to the expected CSV format and includes all required fields for the template you select. Malformed files will be rejected with error details indicating the issue.

Complete Batch Upload Workflow — External Tax Summary

The following examples demonstrate the full end-to-end batch workflow for uploading an External Tax Summary file: authenticate with OAuth, upload a CSV containing pre-aggregated tax summary data, poll for completion at 60-second intervals, and download the results.

The External Tax Summary import type (ExternalTaxSummaryGrossup) is used when your source system provides pre-aggregated tax summaries rather than individual transactions — no tax calculation is performed by SureTax. This is ideal for loading compliance data from external tax engines for reporting and reconciliation.

⚠️ Key Differences from ForwardCalculation/GrossUp
  • X-Import-Type header must be set to ExternalTaxSummaryGrossup
  • configurationName field is required in the request data (set to "Aggregated Tax Summary")
  • complianceYearMonth field is required in the request data (YYYYMM format)
  • The X-Request-Id header value you supply is the Job ID — the server does not return a separate job ID in the response body. Generate a UUID before uploading and reuse it for status polling and download.
Bash — External Tax Summary Upload
#!/usr/bin/env bash
set -euo pipefail

# ── Configuration ──────────────────────────────────────────────────────────
TOKEN_URL="https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE="https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE="https://testsuretaxapi.taxrating.net"
CLIENT_ID="YOUR_CLIENT_ID"
CLIENT_SECRET="YOUR_CLIENT_SECRET"
LEGAL_ENTITY="A001670001"
DATA_YEAR_MONTH="202601"
COMPLIANCE_YEAR_MONTH="202601"
CSV_FILE="external_tax_summary.csv"
POLL_INTERVAL=60
MAX_ATTEMPTS=30

# ── Step 1: Get OAuth Token ───────────────────────────────────────────────
echo "[1/4] Acquiring OAuth token..."
TOKEN=$(curl -s -X POST "$TOKEN_URL" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=$CLIENT_ID" \
  -d "client_secret=$CLIENT_SECRET" \
  -d "scope=$SCOPE" \
  -d "grant_type=client_credentials" \
  | jq -r '.access_token')
echo "      Token acquired."

# ── Step 2: Upload CSV ────────────────────────────────────────────────────
JOB_ID=$(uuidgen)
echo "[2/4] Uploading $CSV_FILE (Job ID: $JOB_ID)..."

HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
  -X POST "$API_BASE/SureTax/api/v1/Batch/Upload" \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-Import-Type: ExternalTaxSummaryGrossup" \
  -H "X-request-id: $JOB_ID" \
  -H "X-source-system: ERP-System" \
  -F "fileContent=@$CSV_FILE" \
  -F "requestData={\"legalEntityCode\":\"$LEGAL_ENTITY\",\"fileLayoutVersion\":\"1.0\",\"dataYearMonth\":\"$DATA_YEAR_MONTH\",\"configurationName\":\"Aggregated Tax Summary\",\"complianceYearMonth\":\"$COMPLIANCE_YEAR_MONTH\"}")

echo "      Upload response: HTTP $HTTP_STATUS"
if [ "$HTTP_STATUS" != "202" ]; then
  echo "      ERROR: Expected 202 Accepted, got $HTTP_STATUS"
  exit 1
fi

# ── Step 3: Poll for Completion ───────────────────────────────────────────
echo "[3/4] Polling for job completion ($POLL_INTERVAL s interval)..."
for ATTEMPT in $(seq 1 $MAX_ATTEMPTS); do
  STATUS_RESPONSE=$(curl -s -X GET \
    "$API_BASE/SureTax/api/v1/Batch/Status?jobId=$JOB_ID" \
    -H "Authorization: Bearer $TOKEN")

  UPLOAD_STATUS=$(echo "$STATUS_RESPONSE" | jq -r '.uploadStatus')
  echo "      Attempt $ATTEMPT/$MAX_ATTEMPTS: $UPLOAD_STATUS"

  if [ "$UPLOAD_STATUS" = "Completed" ]; then
    break
  elif [ "$UPLOAD_STATUS" = "Failed" ]; then
    echo "      Job failed. Error details:"
    echo "$STATUS_RESPONSE" | jq '.itemsWithMessages'
    exit 1
  fi

  sleep $POLL_INTERVAL
done

if [ "$UPLOAD_STATUS" != "Completed" ]; then
  echo "      Job did not complete within the timeout."
  exit 1
fi

# ── Step 4: Download Results ──────────────────────────────────────────────
echo "[4/4] Downloading results..."
curl -s -X GET "$API_BASE/SureTax/api/v1/Download?jobId=$JOB_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-request-id: $(uuidgen)" \
  -o "results_${JOB_ID}.zip"

echo "      Results saved to results_${JOB_ID}.zip"
JavaScript (Node.js) — External Tax Summary Upload
const https = require('https');
const fs = require('fs');
const path = require('path');
const { randomUUID } = require('crypto');
const querystring = require('querystring');

// ── Configuration ──────────────────────────────────────────────────────────
const TOKEN_URL           = 'https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/';
const SCOPE               = 'https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default';
const API_BASE            = 'https://testsuretaxapi.taxrating.net';
const CLIENT_ID           = 'YOUR_CLIENT_ID';
const CLIENT_SECRET       = 'YOUR_CLIENT_SECRET';
const LEGAL_ENTITY        = 'A001670001';
const DATA_YEAR_MONTH     = '202601';
const COMPLIANCE_YEAR_MONTH = '202601';
const CSV_FILE            = 'external_tax_summary.csv';
const POLL_INTERVAL_MS    = 60000;  // 60 seconds
const MAX_ATTEMPTS        = 30;

// ── Helpers ──────────────────────────────────────────────────────────────
function httpRequest(url, options, body) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const opts = { hostname: u.hostname, path: u.pathname + u.search, ...options };
    const req = https.request(opts, res => {
      const chunks = [];
      res.on('data', c => chunks.push(c));
      res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks) }));
    });
    req.on('error', reject);
    if (body) req.write(body);
    req.end();
  });
}

function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

// ── Main ─────────────────────────────────────────────────────────────────
(async () => {
  // Step 1 — Get OAuth Token
  console.log('[1/4] Acquiring OAuth token...');
  const tokenBody = querystring.stringify({
    client_id: CLIENT_ID, client_secret: CLIENT_SECRET,
    scope: SCOPE, grant_type: 'client_credentials'
  });
  const tokenResp = await httpRequest(TOKEN_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(tokenBody) }
  }, tokenBody);
  const token = JSON.parse(tokenResp.body.toString()).access_token;
  console.log('      Token acquired.');

  // Step 2 — Upload CSV
  const jobId = randomUUID();
  console.log(`[2/4] Uploading ${CSV_FILE} (Job ID: ${jobId})...`);

  const boundary = '----SureTaxBoundary' + Date.now();
  const fileData = fs.readFileSync(CSV_FILE);
  const metadata = JSON.stringify({
    legalEntityCode: LEGAL_ENTITY,
    fileLayoutVersion: '1.0',
    dataYearMonth: DATA_YEAR_MONTH,
    configurationName: 'Aggregated Tax Summary',
    complianceYearMonth: COMPLIANCE_YEAR_MONTH
  });

  const bodyParts = [
    `--${boundary}\r\nContent-Disposition: form-data; name="fileContent"; filename="${path.basename(CSV_FILE)}"\r\nContent-Type: text/csv\r\n\r\n`,
    fileData,
    `\r\n--${boundary}\r\nContent-Disposition: form-data; name="requestData"\r\n\r\n${metadata}\r\n--${boundary}--\r\n`
  ];
  const uploadBody = Buffer.concat(bodyParts.map(p => typeof p === 'string' ? Buffer.from(p) : p));

  const uploadResp = await httpRequest(`${API_BASE}/SureTax/api/v1/Batch/Upload`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'X-Import-Type': 'ExternalTaxSummaryGrossup',
      'X-request-id': jobId,
      'X-source-system': 'ERP-System',
      'Content-Type': `multipart/form-data; boundary=${boundary}`,
      'Content-Length': uploadBody.length
    }
  }, uploadBody);
  console.log(`      Upload response: HTTP ${uploadResp.status}`);

  // Step 3 — Poll for Completion
  console.log('[3/4] Polling for job completion (60 s interval)...');
  let uploadStatus = '';
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
    const statusResp = await httpRequest(
      `${API_BASE}/SureTax/api/v1/Batch/Status?jobId=${jobId}`,
      { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } }
    );
    const result = JSON.parse(statusResp.body.toString());
    uploadStatus = result.uploadStatus;
    console.log(`      Attempt ${attempt}/${MAX_ATTEMPTS}: ${uploadStatus}`);

    if (uploadStatus === 'Completed') break;
    if (uploadStatus === 'Failed') {
      console.log('      Job failed. Error details:', JSON.stringify(result.itemsWithMessages, null, 2));
      process.exit(1);
    }
    await sleep(POLL_INTERVAL_MS);
  }

  if (uploadStatus !== 'Completed') {
    console.log('      Job did not complete within the timeout.');
    process.exit(1);
  }

  // Step 4 — Download Results
  console.log('[4/4] Downloading results...');
  const dlResp = await httpRequest(
    `${API_BASE}/SureTax/api/v1/Download?jobId=${jobId}`,
    { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'X-request-id': randomUUID() } }
  );
  const outputFile = `results_${jobId}.zip`;
  fs.writeFileSync(outputFile, dlResp.body);
  console.log(`      Results saved to ${outputFile}`);
})();
Python — External Tax Summary Upload
import requests
import uuid
import json
import time
import sys

# ── Configuration ──────────────────────────────────────────────────────────
TOKEN_URL             = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE                 = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE              = "https://testsuretaxapi.taxrating.net"
CLIENT_ID             = "YOUR_CLIENT_ID"
CLIENT_SECRET         = "YOUR_CLIENT_SECRET"
LEGAL_ENTITY          = "A001670001"
DATA_YEAR_MONTH       = "202601"
COMPLIANCE_YEAR_MONTH = "202601"
CSV_FILE              = "external_tax_summary.csv"
POLL_INTERVAL         = 60   # seconds
MAX_ATTEMPTS          = 30


def main():
    # Step 1 — Get OAuth Token
    print("[1/4] Acquiring OAuth token...")
    token_resp = requests.post(TOKEN_URL, data={
        "client_id":     CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope":         SCOPE,
        "grant_type":    "client_credentials",
    })
    token_resp.raise_for_status()
    token = token_resp.json()["access_token"]
    auth_headers = {"Authorization": f"Bearer {token}"}
    print("      Token acquired.")

    # Step 2 — Upload CSV
    job_id = str(uuid.uuid4())
    print(f"[2/4] Uploading {CSV_FILE} (Job ID: {job_id})...")

    request_data = {
        "legalEntityCode":    LEGAL_ENTITY,
        "fileLayoutVersion":  "1.0",
        "dataYearMonth":      DATA_YEAR_MONTH,
        "configurationName":  "Aggregated Tax Summary",
        "complianceYearMonth": COMPLIANCE_YEAR_MONTH,
    }

    upload_resp = requests.post(
        f"{API_BASE}/SureTax/api/v1/Batch/Upload",
        headers={
            **auth_headers,
            "X-Import-Type":  "ExternalTaxSummaryGrossup",
            "X-request-id":   job_id,
            "X-source-system": "ERP-System",
        },
        files={
            "fileContent": (CSV_FILE, open(CSV_FILE, "rb"), "text/csv"),
        },
        data={
            "requestData": json.dumps(request_data),
        },
    )
    print(f"      Upload response: HTTP {upload_resp.status_code}")
    if upload_resp.status_code != 202:
        print(f"      ERROR: Expected 202, got {upload_resp.status_code}")
        print(f"      Response: {upload_resp.text}")
        sys.exit(1)

    # Step 3 — Poll for Completion
    print(f"[3/4] Polling for job completion ({POLL_INTERVAL} s interval)...")
    upload_status = ""
    for attempt in range(1, MAX_ATTEMPTS + 1):
        status_resp = requests.get(
            f"{API_BASE}/SureTax/api/v1/Batch/Status",
            params={"jobId": job_id},
            headers=auth_headers,
        )
        status_resp.raise_for_status()
        result = status_resp.json()
        upload_status = result["uploadStatus"]
        print(f"      Attempt {attempt}/{MAX_ATTEMPTS}: {upload_status}")

        if upload_status == "Completed":
            break
        if upload_status == "Failed":
            print("      Job failed. Error details:")
            for item in result.get("itemsWithMessages", []):
                print(f"        Line {item['itemNumber']}: {item['message']} ({item['itemStatus']})")
            sys.exit(1)

        time.sleep(POLL_INTERVAL)
    else:
        print("      Job did not complete within the timeout.")
        sys.exit(1)

    # Step 4 — Download Results
    print("[4/4] Downloading results...")
    dl_resp = requests.get(
        f"{API_BASE}/SureTax/api/v1/Download",
        params={"jobId": job_id},
        headers={**auth_headers, "X-request-id": str(uuid.uuid4())},
    )
    dl_resp.raise_for_status()

    output_file = f"results_{job_id}.zip"
    with open(output_file, "wb") as f:
        f.write(dl_resp.content)
    print(f"      Results saved to {output_file}")


if __name__ == "__main__":
    main()
C# — SureTaxBatchClient.cs
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

public class SureTaxBatchClient
{
    // -- Configuration --------------------------------------------------
    private const string TokenUrl             = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/";
    private const string OAuthScope           = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default";
    private const string ApiBaseUrl           = "https://testsuretaxapi.taxrating.net";
    private const string ClientId             = "YOUR_CLIENT_ID";
    private const string ClientSecret         = "YOUR_CLIENT_SECRET";
    private const string LegalEntity          = "A001670001";   // Your LFE code
    private const string DataYearMonth        = "202601";
    private const string ComplianceYearMonth  = "202601";
    private const int    PollInterval         = 60;             // seconds between status checks
    private const int    MaxAttempts          = 30;             // max polls (~30 min)

    private static readonly HttpClient Http = new HttpClient();

    public static async Task Main(string[] args)
    {
        // Step 1 — Authenticate
        Console.WriteLine("[1/4] Acquiring OAuth token...");
        var token = await GetAccessTokenAsync();
        Http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);
        Console.WriteLine("      Token acquired.");

        // Step 2 — Upload CSV file
        var jobId = Guid.NewGuid().ToString();
        Console.WriteLine($"[2/4] Uploading batch file (Job ID: {jobId})...");
        await UploadBatchFileAsync("external_tax_summary.csv", jobId);
        Console.WriteLine($"      Upload accepted.");

        // Step 3 — Poll for completion
        Console.WriteLine("[3/4] Polling for job completion (60 s interval)...");
        var completed = await PollUntilCompleteAsync(jobId);
        if (!completed)
        {
            Console.WriteLine("      Job did not complete within the timeout.");
            return;
        }
        Console.WriteLine("      Job completed.");

        // Step 4 — Download results
        Console.WriteLine("[4/4] Downloading results...");
        await DownloadResultsAsync(jobId, $"results_{jobId}.zip");
        Console.WriteLine($"      Results saved to results_{jobId}.zip");
    }

    // -- Step 1: Get Access Token ---------------------------------------
    private static async Task<string> GetAccessTokenAsync()
    {
        var body = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id",     ClientId),
            new KeyValuePair<string, string>("client_secret",  ClientSecret),
            new KeyValuePair<string, string>("scope",          OAuthScope),
            new KeyValuePair<string, string>("grant_type",     "client_credentials")
        });

        var response = await Http.PostAsync(TokenUrl, body);
        response.EnsureSuccessStatusCode();

        var json  = await response.Content.ReadAsStringAsync();
        var doc   = JsonDocument.Parse(json);
        return doc.RootElement.GetProperty("access_token").GetString()!;
    }

    // -- Step 2: Upload CSV ---------------------------------------------
    private static async Task UploadBatchFileAsync(string csvPath, string jobId)
    {
        var form = new MultipartFormDataContent();

        var fileBytes   = await File.ReadAllBytesAsync(csvPath);
        var fileContent = new ByteArrayContent(fileBytes);
        fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
        form.Add(fileContent, "fileContent", Path.GetFileName(csvPath));

        var metadata = JsonSerializer.Serialize(new
        {
            legalEntityCode    = LegalEntity,
            fileLayoutVersion  = "1.0",
            dataYearMonth      = DataYearMonth,
            configurationName  = "Aggregated Tax Summary",
            complianceYearMonth = ComplianceYearMonth
        });
        form.Add(new StringContent(metadata), "requestData");

        var request = new HttpRequestMessage(HttpMethod.Post,
            $"{ApiBaseUrl}/SureTax/api/v1/Batch/Upload")
        {
            Content = form
        };
        request.Headers.Add("X-Import-Type", "ExternalTaxSummaryGrossup");
        request.Headers.Add("X-request-id",  jobId);
        request.Headers.Add("X-source-system", "ERP-System");

        var response = await Http.SendAsync(request);
        response.EnsureSuccessStatusCode();  // expects 202 Accepted
    }

    // -- Step 3: Poll Status --------------------------------------------
    private static async Task<bool> PollUntilCompleteAsync(string jobId)
    {
        for (int attempt = 1; attempt <= MaxAttempts; attempt++)
        {
            var response = await Http.GetAsync(
                $"{ApiBaseUrl}/SureTax/api/v1/Batch/Status?jobId={jobId}");
            response.EnsureSuccessStatusCode();

            var json   = await response.Content.ReadAsStringAsync();
            var doc    = JsonDocument.Parse(json);
            var status = doc.RootElement.GetProperty("uploadStatus").GetString();

            Console.WriteLine($"      Attempt {attempt}/{MaxAttempts}: {status}");

            if (status == "Completed") return true;
            if (status == "Failed")
            {
                Console.WriteLine("      Job failed. Check error details.");
                if (doc.RootElement.TryGetProperty("itemsWithMessages", out var items))
                {
                    foreach (var item in items.EnumerateArray())
                    {
                        Console.WriteLine($"        Line {item.GetProperty("itemNumber").GetString()}: " +
                            $"{item.GetProperty("message").GetString()} " +
                            $"({item.GetProperty("itemStatus").GetString()})");
                    }
                }
                return false;
            }

            await Task.Delay(TimeSpan.FromSeconds(PollInterval));
        }
        return false;
    }

    // -- Step 4: Download Results ---------------------------------------
    private static async Task DownloadResultsAsync(string jobId, string outputPath)
    {
        var request = new HttpRequestMessage(HttpMethod.Get,
            $"{ApiBaseUrl}/SureTax/api/v1/Download?jobId={jobId}");
        request.Headers.Add("X-request-id", Guid.NewGuid().ToString());

        var response = await Http.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var bytes = await response.Content.ReadAsByteArrayAsync();
        await File.WriteAllBytesAsync(outputPath, bytes);
    }
}

🔑 Key Points

  • Job ID = X-Request-Id — The client generates a UUID before uploading and passes it as the X-request-id header. This same UUID is used as the jobId for status polling and result download. The server does not return a separate job ID.
  • X-Import-Type: ExternalTaxSummaryGrossup — Tells SureTax to import pre-aggregated tax summary data for compliance reporting. No tax calculation is performed.
  • configurationName and complianceYearMonth are required fields in the request data when using ExternalTaxSummaryGrossup. The configurationName must be "Aggregated Tax Summary" and complianceYearMonth specifies the compliance reporting period in YYYYMM format.
  • Token lifetime is 1 hour (3600 seconds). For long-running jobs, implement token refresh logic before the token expires.
  • Poll interval is set to 60 seconds, which is reasonable for batch jobs. Adjust based on your file sizes.
  • legalEntityCode must be a valid LFE from your parent account (see “Understanding Legal Filing Entities” above).
  • To use ForwardCalculation or GrossUp instead, change X-Import-Type to the desired value, set configurationName accordingly, and omit complianceYearMonth (it defaults to dataYearMonth).

Troubleshooting Common Errors

Error Response Structure

When a batch upload fails or encounters validation issues, the Status endpoint returns all errors at once — not one at a time. The response body contains an array of error objects, each identifying the problematic field, the value received, and a descriptive message:

JSON
{
  "errors": [
    {
      "field": "TransactionTypeCode",
      "value": "XYZ",
      "message": "Invalid transaction type code 'XYZ'. Expected a valid numeric code."
    },
    {
      "field": "ZipCode",
      "value": "",
      "message": "ZipCode is required and cannot be empty."
    }
  ]
}
💡 Tip
Because the API surfaces every validation error in a single response, you can fix all issues in one pass and re-upload — rather than discovering errors one at a time through repeated submissions.

Incremental Upload and Correction Behavior

Batch uploads for a given LFE and compliance period are additive — new uploads append data rather than overwriting what was previously uploaded. This has important implications for your workflow:

📋 Example
You upload a batch file covering all states for a client. Nebraska form 10 has an error. You fix the Nebraska transactions, upload only those corrected rows, then regenerate only the Nebraska form. All other state forms remain valid and unchanged.

Account/Legal Entity Creation

Before using the Batch Upload or Returns APIs, you must understand Legal Filing Entities (LFEs). An LFE represents a distinct legal organization within your parent account — typically mapping to a client or subsidiary that files tax returns independently. All batch uploads and returns operations are scoped to a specific LFE.

A single set of OAuth credentials is associated with a parent account. That parent account may contain multiple LFEs, each representing a different client or legal entity. When uploading batch files, you specify which LFE the transactions belong to. When generating returns, you scope the operation to a specific External Reporting Entity (which corresponds to an LFE).

Discovering Your LFEs

Use the Configuration API GET /SureTax/api/v1/User endpoint to retrieve the list of LFEs associated with your parent account credentials:

StepAPIEndpointPurpose
1Config APIGET /SureTax/api/v1/User?email={email}Retrieves the user’s LFEs for the parent account
HTTP Request
GET https://testsuretaxapi.taxrating.net/SureTax/api/v1/User?email=your.email@company.com
Authorization: Bearer {access_token}

Example Response

JSON
{
  "data": [
    { "id": "A001670001" },
    { "id": "A001670002" },
    { "id": "A001670003" },
    { "id": "A001670004" }
  ]
}

Each id value is an LFE code. Use these codes as the legalEntityCode when uploading batch files and as the externalReportingEntity when working with the Returns API. All LFEs under a parent account share the same OAuth credentials.


Discovering Returns Reporting Entities

For the Returns API specifically, use the GET External Reporting Entities endpoint to discover entities configured for returns:

HTTP Request
GET https://testsuretaxapi.taxrating.net/SureTax/api/v1/Forms/ExternalReportingEntities
Authorization: Bearer {access_token}

Example Response

JSON
{
  "data": [
    {
      "id": "A001670001",
      "name": [{ "text": "Acme Commerce Inc.", "language": "EN" }]
    },
    {
      "id": "A001670002",
      "name": [{ "text": "Acme Retail LLC", "language": "EN" }]
    }
  ]
}

Complete LFE Discovery Workflow

The following examples demonstrate the full LFE discovery workflow in a single script: authenticate with OAuth, use the user’s email to retrieve the LFEs for the parent account, then retrieve detailed information for each LFE.

#!/usr/bin/env bash
set -euo pipefail

# ── Configuration ──────────────────────────────────────────────────────
TOKEN_URL="https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE="https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE="https://testsuretaxapi.taxrating.net/SureTax/api/v1"
CLIENT_ID="YOUR_CLIENT_ID"
CLIENT_SECRET="YOUR_CLIENT_SECRET"
USER_EMAIL="your.email@company.com"

# ── Step 1: Get OAuth Token ───────────────────────────────────────────
echo "[1/3] Acquiring OAuth token..."
TOKEN=$(curl -s -X POST "$TOKEN_URL" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=$CLIENT_ID" \
  -d "client_secret=$CLIENT_SECRET" \
  -d "scope=$SCOPE" \
  -d "grant_type=client_credentials" \
  | jq -r '.access_token')

echo "      Token acquired."

# ── Step 2: Get User LFEs ────────────────────────────────────────────
echo "[2/3] Retrieving LFEs for $USER_EMAIL..."
USER_RESPONSE=$(curl -s -X GET "$API_BASE/User?email=$USER_EMAIL" \
  -H "Authorization: Bearer $TOKEN")

echo "$USER_RESPONSE" | jq '.data[] | .id' -r | while read -r LFE_ID; do
  echo "      Found LFE: $LFE_ID"
done

# ── Step 3: Get Details for Each LFE ─────────────────────────────────
echo "[3/3] Retrieving details for each LFE..."
echo "$USER_RESPONSE" | jq '.data[] | .id' -r | while read -r LFE_ID; do
  echo ""
  echo "      ── LFE: $LFE_ID ──"
  ENTITY=$(curl -s -X GET "$API_BASE/Account/LegalEntities/$LFE_ID" \
    -H "Authorization: Bearer $TOKEN")

  echo "$ENTITY" | jq '{
    entityName,
    fein,
    address: (.entityAddress | "\(.address1), \(.city), \(.state) \(.zipcode)-\(.plus4)"),
    contact: (.contactPersons[0] | "\(.personName) (\(.personType)) – \(.emailAddress)"),
    phone:   (.contactNumbers[0] | "\(.contactNumberType): \(.contactPhonenumber)"),
    website,
    notificationEmail: .notificationBusinessEmail
  }'
done
const https = require('https');
const querystring = require('querystring');

// ── Configuration ──────────────────────────────────────────────────────
const TOKEN_URL     = 'https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/';
const SCOPE         = 'https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default';
const API_BASE      = 'https://testsuretaxapi.taxrating.net/SureTax/api/v1';
const CLIENT_ID     = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const USER_EMAIL    = 'your.email@company.com';

// ── Helpers ────────────────────────────────────────────────────────────
function post(url, body, headers = {}) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const data = typeof body === 'string' ? body : querystring.stringify(body);
    const opts = {
      hostname: u.hostname, path: u.pathname, method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
                 'Content-Length': Buffer.byteLength(data), ...headers }
    };
    const req = https.request(opts, res => {
      let chunks = '';
      res.on('data', c => chunks += c);
      res.on('end', () => resolve(JSON.parse(chunks)));
    });
    req.on('error', reject);
    req.write(data);
    req.end();
  });
}

function get(url, token) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const opts = {
      hostname: u.hostname, path: u.pathname + u.search, method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    };
    const req = https.request(opts, res => {
      let chunks = '';
      res.on('data', c => chunks += c);
      res.on('end', () => resolve(JSON.parse(chunks)));
    });
    req.on('error', reject);
    req.end();
  });
}

// ── Main ───────────────────────────────────────────────────────────────
(async () => {
  // Step 1 — Get OAuth Token
  console.log('[1/3] Acquiring OAuth token...');
  const tokenResp = await post(TOKEN_URL, {
    client_id:     CLIENT_ID,
    client_secret: CLIENT_SECRET,
    scope:         SCOPE,
    grant_type:    'client_credentials'
  });
  const token = tokenResp.access_token;
  console.log('      Token acquired.');

  // Step 2 — Get User LFEs
  console.log(`[2/3] Retrieving LFEs for ${USER_EMAIL}...`);
  const userResp = await get(
    `${API_BASE}/User?email=${encodeURIComponent(USER_EMAIL)}`, token);
  const lfeIds = userResp.data.map(e => e.id);
  console.log(`      Found ${lfeIds.length} LFE(s): ${lfeIds.join(', ')}`);

  // Step 3 — Get Details for Each LFE
  console.log('[3/3] Retrieving details for each LFE...');
  for (const lfeId of lfeIds) {
    const entity = await get(
      `${API_BASE}/Account/LegalEntities/${lfeId}`, token);
    console.log(`\n      ── LFE: ${lfeId} ──`);
    console.log(`      Name:    ${entity.entityName}`);
    console.log(`      FEIN:    ${entity.fein}`);
    const addr = entity.entityAddress;
    console.log(`      Address: ${addr.address1}, ${addr.city}, ${addr.state} ${addr.zipcode}-${addr.plus4}`);
    if (entity.contactPersons?.length) {
      const cp = entity.contactPersons[0];
      console.log(`      Contact: ${cp.personName} (${cp.personType}) – ${cp.emailAddress}`);
    }
    if (entity.contactNumbers?.length) {
      const cn = entity.contactNumbers[0];
      console.log(`      Phone:   ${cn.contactNumberType}: ${cn.contactPhonenumber}`);
    }
    console.log(`      Website: ${entity.website}`);
    console.log(`      Notify:  ${entity.notificationBusinessEmail}`);
  }
})();
import requests

# ── Configuration ──────────────────────────────────────────────────────
TOKEN_URL     = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE         = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE      = "https://testsuretaxapi.taxrating.net/SureTax/api/v1"
CLIENT_ID     = "YOUR_CLIENT_ID"
CLIENT_SECRET = "YOUR_CLIENT_SECRET"
USER_EMAIL    = "your.email@company.com"


def main():
    # Step 1 — Get OAuth Token
    print("[1/3] Acquiring OAuth token...")
    token_resp = requests.post(TOKEN_URL, data={
        "client_id":     CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope":         SCOPE,
        "grant_type":    "client_credentials",
    })
    token_resp.raise_for_status()
    token = token_resp.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    print("      Token acquired.")

    # Step 2 — Get User LFEs
    print(f"[2/3] Retrieving LFEs for {USER_EMAIL}...")
    user_resp = requests.get(
        f"{API_BASE}/User", params={"email": USER_EMAIL}, headers=headers
    )
    user_resp.raise_for_status()
    lfe_ids = [e["id"] for e in user_resp.json()["data"]]
    print(f"      Found {len(lfe_ids)} LFE(s): {', '.join(lfe_ids)}")

    # Step 3 — Get Details for Each LFE
    print("[3/3] Retrieving details for each LFE...")
    for lfe_id in lfe_ids:
        entity_resp = requests.get(
            f"{API_BASE}/Account/LegalEntities/{lfe_id}", headers=headers
        )
        entity_resp.raise_for_status()
        entity = entity_resp.json()

        addr = entity["entityAddress"]
        address_str = (
            f"{addr['address1']}, {addr['city']}, "
            f"{addr['state']} {addr['zipcode']}-{addr['plus4']}"
        )

        print(f"\n      ── LFE: {lfe_id} ──")
        print(f"      Name:    {entity['entityName']}")
        print(f"      FEIN:    {entity['fein']}")
        print(f"      Address: {address_str}")
        if entity.get("contactPersons"):
            cp = entity["contactPersons"][0]
            print(f"      Contact: {cp['personName']} ({cp['personType']}) – {cp['emailAddress']}")
        if entity.get("contactNumbers"):
            cn = entity["contactNumbers"][0]
            print(f"      Phone:   {cn['contactNumberType']}: {cn['contactPhonenumber']}")
        print(f"      Website: {entity['website']}")
        print(f"      Notify:  {entity['notificationBusinessEmail']}")


if __name__ == "__main__":
    main()
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

public class LfeDiscoveryClient
{
    // -- Configuration --------------------------------------------------
    private const string TokenUrl     = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/";
    private const string OAuthScope   = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default";
    private const string ApiBaseUrl   = "https://testsuretaxapi.taxrating.net/SureTax/api/v1";
    private const string ClientId     = "YOUR_CLIENT_ID";
    private const string ClientSecret = "YOUR_CLIENT_SECRET";
    private const string UserEmail    = "your.email@company.com";

    private static readonly HttpClient Http = new HttpClient();

    public static async Task Main(string[] args)
    {
        // Step 1 — Get OAuth Token
        Console.WriteLine("[1/3] Acquiring OAuth token...");
        var tokenBody = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id",     ClientId),
            new KeyValuePair<string, string>("client_secret", ClientSecret),
            new KeyValuePair<string, string>("scope",         OAuthScope),
            new KeyValuePair<string, string>("grant_type",    "client_credentials")
        });
        var tokenResp = await Http.PostAsync(TokenUrl, tokenBody);
        tokenResp.EnsureSuccessStatusCode();
        var tokenDoc = JsonDocument.Parse(await tokenResp.Content.ReadAsStringAsync());
        var token = tokenDoc.RootElement.GetProperty("access_token").GetString()!;
        Http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);
        Console.WriteLine("      Token acquired.");

        // Step 2 — Get User LFEs
        Console.WriteLine($"[2/3] Retrieving LFEs for {UserEmail}...");
        var userResp = await Http.GetAsync(
            $"{ApiBaseUrl}/User?email={Uri.EscapeDataString(UserEmail)}");
        userResp.EnsureSuccessStatusCode();
        var userDoc = JsonDocument.Parse(await userResp.Content.ReadAsStringAsync());
        var lfeArray = userDoc.RootElement.GetProperty("data");

        var lfeIds = new System.Collections.Generic.List<string>();
        foreach (var item in lfeArray.EnumerateArray())
            lfeIds.Add(item.GetProperty("id").GetString()!);
        Console.WriteLine($"      Found {lfeIds.Count} LFE(s): {string.Join(", ", lfeIds)}");

        // Step 3 — Get Details for Each LFE
        Console.WriteLine("[3/3] Retrieving details for each LFE...");
        foreach (var lfeId in lfeIds)
        {
            var entityResp = await Http.GetAsync(
                $"{ApiBaseUrl}/Account/LegalEntities/{lfeId}");
            entityResp.EnsureSuccessStatusCode();
            var entity = JsonDocument.Parse(
                await entityResp.Content.ReadAsStringAsync()).RootElement;

            var addr = entity.GetProperty("entityAddress");
            var address = $"{addr.GetProperty("address1").GetString()}, " +
                          $"{addr.GetProperty("city").GetString()}, " +
                          $"{addr.GetProperty("state").GetString()} " +
                          $"{addr.GetProperty("zipcode").GetString()}-" +
                          $"{addr.GetProperty("plus4").GetString()}";

            Console.WriteLine($"\n      ── LFE: {lfeId} ──");
            Console.WriteLine($"      Name:    {entity.GetProperty("entityName").GetString()}");
            Console.WriteLine($"      FEIN:    {entity.GetProperty("fein").GetString()}");
            Console.WriteLine($"      Address: {address}");

            if (entity.TryGetProperty("contactPersons", out var persons) &&
                persons.GetArrayLength() > 0)
            {
                var cp = persons[0];
                Console.WriteLine($"      Contact: {cp.GetProperty("personName").GetString()} " +
                    $"({cp.GetProperty("personType").GetString()}) – " +
                    $"{cp.GetProperty("emailAddress").GetString()}");
            }

            if (entity.TryGetProperty("contactNumbers", out var numbers) &&
                numbers.GetArrayLength() > 0)
            {
                var cn = numbers[0];
                Console.WriteLine($"      Phone:   {cn.GetProperty("contactNumberType").GetString()}: " +
                    $"{cn.GetProperty("contactPhonenumber").GetString()}");
            }

            Console.WriteLine($"      Website: {entity.GetProperty("website").GetString()}");
            Console.WriteLine($"      Notify:  {entity.GetProperty("notificationBusinessEmail").GetString()}");
        }
    }
}
[1/3] Acquiring OAuth token...
      Token acquired.
[2/3] Retrieving LFEs for your.email@company.com...
      Found 4 LFE(s): A001670001, A001670002, A001670003, A001670004
[3/3] Retrieving details for each LFE...

      ── LFE: A001670001 ──
      Name:    Acme Commerce Inc.
      FEIN:    1234567890
      Address: 1567 Street Ct, Frisco, TX 11111-1234
      Contact: John Smith (PRIMARY) – john.smith@acme.com
      Phone:   Office: 1238123234
      Website: www.acmecommerce.com
      Notify:  tax@acmecommerce.com

      ── LFE: A001670002 ──
      Name:    Acme Retail LLC
      FEIN:    0987654321
      Address: 2400 Commerce Dr, Dallas, TX 75201-5678
      Contact: Jane Doe (PRIMARY) – jane.doe@acme.com
      Phone:   Office: 9725551234
      Website: www.acmeretail.com
      Notify:  tax@acmeretail.com
      ...

Key Points

  • Step 1 uses OAuth 2.0 client credentials flow — the same token works for both Config API endpoints.
  • Step 2 calls GET /SureTax/api/v1/User?email={email} to discover all LFE codes under the parent account.
  • Step 3 iterates each LFE code and calls GET /SureTax/api/v1/Account/LegalEntities/{entitycode} to retrieve the full entity profile including name, FEIN, address, contacts, and notification settings.
  • The token has a 1-hour lifetime. For scripts that process many LFEs, no refresh is typically needed.
  • All LFEs under a parent account share the same OAuth credentials — you authenticate once and access all entities.

Account/Legal Entity Configuration

Once your Legal Filing Entities (LFEs) are created and discoverable, the next step is configuring the foundational settings that govern how each entity calculates, reports, and files taxes. This configuration step establishes the compliance profile for each LFE before any transactions are processed or returns are generated.

What Gets Configured

Configuration AreaDescription
Tax Authority Relationships Define the relationships between each LFE and the tax authorities it is obligated to file with. Each relationship specifies the authority level (state, county, city), the applicable tax form, filing frequency (monthly, quarterly, annually), filing method, license numbers, and contact information.

How to Configure

Tax authority relationships can be set up through:

  1. SureTax Portal — Use the SureTax web portal to manually configure tax authority relationships, filing jurisdictions, and other settings through the administrative interface.
  2. Import Templates — Use the Tax Authority Relationships Import Template to bulk-import your filing relationships from a CSV file. This is the recommended approach for organizations with a large number of jurisdictions.
  3. Configuration API — Use the Config API programmatically to create and update entity configurations as part of an automated onboarding or sync workflow.
⚠️ Important
Tax authority relationships must be configured before generating returns. Without these relationships, the Returns API will not have the filing obligations needed to produce return documents.

Where This Fits in the Workflow

Account/Entity Creation → Account/Entity Configuration → Batch Upload → Returns Generation → Report Extraction

Configuration is a one-time setup step per LFE (with periodic updates as your filing obligations change). Once configured, the LFE is ready to receive transactions via Batch Upload and generate returns via the Returns API.

Tax Return Generation Workflow

SureTax Returns automates the preparation, review, and filing of sales and use tax returns. The Returns API provides a programmatic interface for the full returns lifecycle — from discovering filing obligations to generating return documents, downloading them for review, and submitting them for e-filing. Like the Batch Upload API, it uses OAuth 2.0 authentication and all operations are scoped to an External Reporting Entity (LFE).

Returns API Endpoints

StepOperationEndpointMethodDescription
1Get TokenOAuth Token URLPOSTObtain an OAuth 2.0 Bearer token
2List Entities/SureTax/api/v1/Forms/ExternalReportingEntitiesGETDiscover available reporting entities (LFEs)
3Get Due Forms/SureTax/api/v1/Forms/DueFormsGETRetrieve filing obligations for an entity and period
4Generate Forms/SureTax/api/v1/Forms/DueFormInstancesPOSTTrigger async generation of return documents. Accepts an array of form IDs — you can generate multiple forms in a single call.
5Check Status/SureTax/api/v1/Forms/GenerationRequestStatusGETPoll until generation completes. The response lists each form’s individual instance ID and status, so you can track them independently.
5aCheck Errors/SureTax/api/v1/Forms/GenerationLogs?jobId={id}GETWhen a form’s generation status is GWE (Generated With Errors), call this endpoint to retrieve the specific error details. Returns 204 No Content if the form generated without errors.
6Get Instance/SureTax/api/v1/Forms/FormInstancesGETRetrieve metadata for a generated return
7Download/SureTax/api/v1/Forms/FormInstanceDownloadURLGETGet a secure download URL for the return document (per form instance — see note below)
8Regenerate/SureTax/api/v1/Forms/FormInstances/regeneratePOSTRegenerate a specific form instance after data corrections or edits. Required to reflect changes in the downloadable PDF.
9Reset/SureTax/api/v1/Forms/FormInstances/resetPOSTRevert a form instance to its original generated state, undoing all manual edits made through the embedded editor.
10Update Status/SureTax/api/v1/Forms/FormInstancesPATCHUpdate the lifecycle status of a form (e.g., mark as Filed, Accepted by Tax Authority). Once a form is marked as filed/accepted, it no longer appears in the DueForms list.
11Delete/SureTax/api/v1/Forms/FormInstancesDELETEPermanently delete a generated form instance you no longer need.

Workflow

1
Get Token
OAuth 2.0
→
2
List LFEs
GET Entities
→
3
Due Forms
Filing obligations
→
4
Generate
POST → Job ID
→
5
Poll Status
~60 s intervals
6
Get Instance
Form metadata
→
7
Download
Pre-signed URL

Status Reference

Generation Request Status

CodeMeaning
1In Process — generation is still running
2Completed — generation has finished

Form Instance Status

CodeMeaning
GENGenerated successfully
GWWGenerated with warnings (review recommended)
GWEGenerated with errors — call GenerationLogs to retrieve the specific errors. Fix the underlying data, re-upload corrections if needed, and regenerate the form.
STGSubmitted to government
SOKContent accepted by government after e-filing
SDEContent declined by government
💡 Tip — Multi-form generation
When you POST to DueFormInstances with multiple form IDs, the generation status response lists every form along with its own unique form instance ID. You can track, download, edit, and e-file each form independently — even if some are still generating while others have completed.
⚠️ Important — Consolidated jurisdiction forms
Some states consolidate multiple jurisdictions into a single return form. For example, Louisiana consolidates all parish filings into a single “parish” form — you generate it once and it includes all applicable parishes. Ensure all parish transaction data has been uploaded before generating the form, since it produces a single combined return rather than individual forms per parish.
⚠️ Important — DueForms list management
The DueForms endpoint only returns forms that have not yet been marked as filed or accepted. Once you update a form instance’s status to filed/accepted via the PATCH endpoint, it drops off the DueForms list. Use this to track which forms are still outstanding for a given filing period.

Complete Returns Workflow in C#

The following C# example demonstrates the full returns workflow: authenticate, discover entities, retrieve due forms, generate return documents, poll for completion, and download the generated return.

C# — SureTaxReturnsClient.cs
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class SureTaxReturnsClient
{
    // Configuration
    private const string TokenUrl     = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/";
    private const string OAuthScope   = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default";
    private const string ApiBaseUrl   = "https://testsuretaxapi.taxrating.net";
    private const string ClientId     = "YOUR_CLIENT_ID";
    private const string ClientSecret = "YOUR_CLIENT_SECRET";
    private const int    PollInterval = 60;    // seconds
    private const int    MaxAttempts  = 30;

    private static readonly HttpClient Http = new HttpClient();

    public static async Task Main(string[] args)
    {
        // Step 1 — Authenticate
        Console.WriteLine("[1/7] Acquiring OAuth token...");
        var token = await GetAccessTokenAsync();
        Http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

        // Step 2 — List External Reporting Entities (LFEs)
        Console.WriteLine("[2/7] Retrieving reporting entities...");
        var entities = await GetReportingEntitiesAsync();
        foreach (var e in entities)
            Console.WriteLine($"      Entity: {e.Id} — {e.Name}");

        var entityId = entities[0].Id;
        Console.WriteLine($"      Using entity: {entityId}");

        // Step 3 — Get Due Forms
        Console.WriteLine("[3/7] Retrieving due forms...");
        var dueForms = await GetDueFormsAsync(entityId, "2026-01-01", "2026-01-31");
        Console.WriteLine($"      Found {dueForms.Length} due form(s).");

        if (dueForms.Length == 0)
        {
            Console.WriteLine("      No due forms found for this period.");
            return;
        }

        // Step 4 — Generate Form Instances
        Console.WriteLine("[4/7] Generating form instances...");
        var requestId = Guid.NewGuid().ToString("N")[..32];
        await GenerateFormInstancesAsync(entityId, dueForms, requestId);

        // Step 5 — Poll Generation Status
        Console.WriteLine("[5/7] Polling generation status (60 s interval)...");
        var genResult = await PollGenerationStatusAsync(requestId);
        if (genResult == null)
        {
            Console.WriteLine("      Generation did not complete.");
            return;
        }
        Console.WriteLine($"      Generation completed. {genResult.FormInstanceIds.Length} form(s) generated.");

        // Step 6 — Get Form Instance details
        Console.WriteLine("[6/7] Retrieving form instance details...");
        var instanceId = genResult.FormInstanceIds[0];
        var instance = await GetFormInstanceAsync(instanceId);
        Console.WriteLine($"      Form: {instance.Name}  Status: {instance.Status}  Size: {instance.FileSize}");

        // Step 7 — Download the return
        Console.WriteLine("[7/7] Downloading return document...");
        var downloadUrl = await GetDownloadUrlAsync(instanceId);
        await DownloadFileAsync(downloadUrl, $"return_{instanceId}.pdf");
        Console.WriteLine($"      Saved to return_{instanceId}.pdf");
    }

    // Authentication
    private static async Task<string> GetAccessTokenAsync()
    {
        var body = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id",     ClientId),
            new KeyValuePair<string, string>("client_secret",  ClientSecret),
            new KeyValuePair<string, string>("scope",          OAuthScope),
            new KeyValuePair<string, string>("grant_type",     "client_credentials")
        });

        var resp = await Http.PostAsync(TokenUrl, body);
        resp.EnsureSuccessStatusCode();
        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        return doc.RootElement.GetProperty("access_token").GetString()!;
    }

    // Step 2: List Reporting Entities
    private static async Task<ReportingEntity[]> GetReportingEntitiesAsync()
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/ExternalReportingEntities");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        var data = doc.RootElement.GetProperty("data");
        var list = new System.Collections.Generic.List<ReportingEntity>();

        foreach (var item in data.EnumerateArray())
        {
            var name = "";
            if (item.TryGetProperty("name", out var names))
                foreach (var n in names.EnumerateArray())
                    if (n.GetProperty("language").GetString() == "EN")
                    { name = n.GetProperty("text").GetString()!; break; }

            list.Add(new ReportingEntity { Id = item.GetProperty("id").GetString()!, Name = name });
        }
        return list.ToArray();
    }

    // Step 3: Get Due Forms
    private static async Task<DueForm[]> GetDueFormsAsync(
        string entityId, string fromDate, string toDate)
    {
        var url = $"{ApiBaseUrl}/SureTax/api/v1/Forms/DueForms" +
            $"?ExternalReportingEntity={entityId}" +
            $"&StartDateForReportingPeriod={fromDate}" +
            $"&EndDateForReportingPeriod={toDate}";

        var resp = await Http.GetAsync(url);
        resp.EnsureSuccessStatusCode();

        var doc  = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        var data = doc.RootElement.GetProperty("data");
        var list = new System.Collections.Generic.List<DueForm>();

        foreach (var item in data.EnumerateArray())
        {
            list.Add(new DueForm
            {
                FormId                  = item.GetProperty("formId").GetString()!,
                ReportingPeriodFromDate = item.GetProperty("reportingPeriodFromDate").GetString()!,
                ReportingPeriodToDate   = item.GetProperty("reportingPeriodToDate").GetString()!,
                ReportingPeriodicity    = item.GetProperty("reportingPeriodicity").GetString()!,
                ReportingPeriodNum      = item.GetProperty("reportingPeriodNum").GetString()!,
                LocationId              = item.TryGetProperty("locationId", out var loc) ? loc.GetString() : null
            });
        }
        return list.ToArray();
    }

    // Step 4: Generate Form Instances
    private static async Task GenerateFormInstancesAsync(
        string entityId, DueForm[] dueForms, string requestId)
    {
        var forms = new System.Collections.Generic.List<object>();
        foreach (var df in dueForms)
        {
            forms.Add(new
            {
                formId                  = df.FormId,
                locationId              = df.LocationId,
                reportingPeriodFromDate = df.ReportingPeriodFromDate,
                reportingPeriodToDate   = df.ReportingPeriodToDate,
                reportingPeriodicity    = df.ReportingPeriodicity,
                reportingPeriodNum      = df.ReportingPeriodNum,
                reportingPhase          = "STAND"
            });
        }

        var payload = JsonSerializer.Serialize(new
        {
            externalReportingEntity = entityId,
            forms = forms
        });

        var request = new HttpRequestMessage(HttpMethod.Post,
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/DueFormInstances")
        {
            Content = new StringContent(payload, Encoding.UTF8, "application/json")
        };
        request.Headers.Add("x-request-id", requestId);

        var resp = await Http.SendAsync(request);
        resp.EnsureSuccessStatusCode();  // expects 207 Multi-Status
    }

    // Step 5: Poll Generation Status
    private static async Task<GenerationResult?> PollGenerationStatusAsync(
        string requestId)
    {
        for (int attempt = 1; attempt <= MaxAttempts; attempt++)
        {
            var resp = await Http.GetAsync(
                $"{ApiBaseUrl}/SureTax/api/v1/Forms/GenerationRequestStatus?Id={requestId}");
            resp.EnsureSuccessStatusCode();

            var doc    = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
            var data   = doc.RootElement.GetProperty("data");
            var status = data.GetProperty("requestStatus").GetString();

            Console.WriteLine($"      Attempt {attempt}/{MaxAttempts}: Status = {(status == "1" ? "In Process" : "Completed")}");

            if (status == "2") // Completed
            {
                var ids = new System.Collections.Generic.List<string>();
                foreach (var fi in data.GetProperty("formInstances").EnumerateArray())
                    ids.Add(fi.GetProperty("id").GetString()!);
                return new GenerationResult { FormInstanceIds = ids.ToArray() };
            }

            await Task.Delay(TimeSpan.FromSeconds(PollInterval));
        }
        return null;
    }

    // Step 6: Get Form Instance
    private static async Task<FormInstance> GetFormInstanceAsync(string instanceId)
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstances?Id={instanceId}");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        var fi  = doc.RootElement.GetProperty("data").GetProperty("formInstances")[0];

        return new FormInstance
        {
            Id       = fi.GetProperty("id").GetString()!,
            Name     = fi.GetProperty("name").GetString()!,
            Status   = fi.GetProperty("status").GetString()!,
            FileSize = fi.TryGetProperty("fileSize", out var fs) ? fs.GetString() : "unknown"
        };
    }

    // Step 7: Download Return Document
    private static async Task<string> GetDownloadUrlAsync(string instanceId)
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstanceDownloadURL?Id={instanceId}");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        return doc.RootElement.GetProperty("data").GetProperty("formInstances")[0]
            .GetProperty("downloadUrl").GetString()!;
    }

    private static async Task DownloadFileAsync(string url, string outputPath)
    {
        var resp  = await Http.GetAsync(url);
        resp.EnsureSuccessStatusCode();
        var bytes = await resp.Content.ReadAsByteArrayAsync();
        await File.WriteAllBytesAsync(outputPath, bytes);
    }

    // Data Models
    private record ReportingEntity
    { public string Id { get; init; } = ""; public string Name { get; init; } = ""; }

    private record DueForm
    {
        public string FormId { get; init; } = "";
        public string ReportingPeriodFromDate { get; init; } = "";
        public string ReportingPeriodToDate { get; init; } = "";
        public string ReportingPeriodicity { get; init; } = "";
        public string ReportingPeriodNum { get; init; } = "";
        public string? LocationId { get; init; }
    }

    private record GenerationResult
    { public string[] FormInstanceIds { get; init; } = Array.Empty<string>(); }

    private record FormInstance
    {
        public string Id { get; init; } = "";
        public string Name { get; init; } = "";
        public string Status { get; init; } = "";
        public string? FileSize { get; init; }
    }
}

🔑 Key Points

  • External Reporting Entity corresponds to an LFE. Use the GET ExternalReportingEntities call to discover available entities.
  • x-request-id on the generation POST becomes the Job ID for polling via GET GenerationRequestStatus.
  • Generation status 2 means completed — the response includes the generated form instance IDs.
  • Download URLs are pre-signed Azure Blob Storage URLs with built-in expiration. No additional authentication is needed to download.
  • Reporting Phase STAND is used for standard (original) filings. Use CORR for corrections.

Download Your PDF Tax Return

Once a return has been generated, you can retrieve the completed tax form as a downloadable PDF. This is a two-step process: first, obtain the secure download URL for the form instance, then use that URL to pull the PDF across the wire.

⚠️ Important — Per-form download
The Download URL endpoint operates on a single form instance at a time. There is no batch download endpoint that returns all forms for a job in one call. If you generated multiple forms, you must call FormInstanceDownloadURL for each form instance ID individually. For organizations processing many forms per period, consider looping through the form instance IDs returned in the generation status response and downloading each one programmatically.

Download Workflow

StepOperationEndpointMethodDescription
1 Get Form Instance /SureTax/api/v1/Forms/FormInstances?Id={instanceId} GET Retrieve metadata for a generated return, including its status and file size.
2 Get Download URL /SureTax/api/v1/Forms/FormInstanceDownloadURL?Id={instanceId} GET Returns a pre-signed Azure Blob Storage URL pointing to the generated PDF.
3 Download the PDF The URL from Step 2 GET Fetch the PDF directly using a standard HTTP GET request. No authentication header is required — the pre-signed URL contains embedded authorization with a built-in expiration.

How It Works

  1. After form generation completes (generation status 2), you receive one or more form instance IDs in the generation status response.
  2. Call GET /SureTax/api/v1/Forms/FormInstances?Id={instanceId} with your Bearer token to retrieve instance metadata — including the form name, status (GEN, GWW, etc.), and file size.
  3. Call GET /SureTax/api/v1/Forms/FormInstanceDownloadURL?Id={instanceId} with your Bearer token. The response includes a downloadUrl field containing a pre-signed Azure Blob Storage URL.
  4. Issue a simple GET request to that download URL — no Authorization header is needed. The pre-signed URL is self-authenticating and will expire after a set period.
  5. Save the response body as a PDF file.

Example — Get Download URL

HTTP Request
GET https://testsuretaxapi.taxrating.net/SureTax/api/v1/Forms/FormInstanceDownloadURL?Id=12345
Authorization: Bearer {access_token}

Example Response

JSON
{
  "data": {
    "formInstances": [
      {
        "id": "12345",
        "downloadUrl": "https://suretaxstorage.blob.core.windows.net/returns/12345.pdf?sv=2023-01-03&se=2026-03-30T20%3A00%3A00Z&sig=..."
      }
    ]
  }
}

Example — Download the PDF

HTTP Request
GET https://suretaxstorage.blob.core.windows.net/returns/12345.pdf?sv=2023-01-03&se=2026-03-30T20%3A00%3A00Z&sig=...

No Authorization header is needed. Save the response body to a .pdf file.

⚠️ Important
Download URLs are temporary and will expire. Always retrieve a fresh URL via FormInstanceDownloadURL before downloading. Do not cache or store the URL for later use.

Reviewing and Adjusting Tax Returns Inline

For organizations that want to give tax analysts, compliance reviewers, or approvers direct access to tax returns without leaving your application, the Returns API provides a secure, iframe-compatible viewer and editor. Using the Get FormInstanceURL endpoint, your application can generate a time-limited, pre-authenticated URL that renders the full SureTax tax return form inside an <iframe> — in either read-only (View) or interactive editing (Edit) mode.

This integration pattern is ideal when you want to keep users within your platform while still providing full access to the SureTax form interface for reviewing, adjusting, or approving tax returns before e-filing.

When to Use Inline Review and Adjustment

Inline Review Workflow

StepOperationEndpointMethodDescription
1Verify Form Instance/SureTax/api/v1/Forms/FormInstances?Id={instanceId}GETConfirm the form instance exists and check its current status before generating a viewer URL.
2Generate Viewer URL/SureTax/api/v1/Forms/FormInstanceURL?Id={instanceId}&Action={View|Edit}GETRetrieve a secure, time-limited URL with embedded authentication. Pass Action=View for read-only access or Action=Edit for interactive editing.
3Embed in iframe(Client-side)—Render the returned URL in an <iframe> within your application. The SureTax form interface loads inline — no additional login required.
4Retrieve Change Log (optional)/SureTax/api/v1/Forms/FormInstanceChangeLog?Id={instanceId}GETAfter editing, retrieve a complete audit trail of every modification — including the element, old/new values, the user, and timestamp.

How It Works

  1. Before generating a viewer URL, call GET FormInstances with the instance ID to verify the form exists and check its status. This ensures you are not attempting to open a form instance that has been deleted or is in an unexpected state.
  2. Call GET FormInstanceURL with the instance ID and the desired Action parameter (View or Edit). The API returns a secure, pre-authenticated URL that is valid for a limited time.
  3. Set the returned URL as the src attribute of an <iframe> in your application. The SureTax form interface renders inline — users can view or edit the return depending on the action you requested.
  4. (Optional) After an editing session, call GET FormInstanceChangeLog to retrieve a granular audit trail. Each entry records the specific form element and attribute that changed, the old and new values, the user who made the change, and a UTC timestamp.

Access Modes

ActionBehaviorUse Case
ViewOpens the form in read-only mode — no changes can be made.Compliance review, auditor access, client portal display
EditOpens the form in interactive editing mode — users can modify line items directly.Tax analyst adjustments, manual corrections, pre-filing reviews
💡 Tip
Use Action=View for any scenario where changes should not be permitted — reviewer dashboards, audit displays, and client-facing portals. Reserve Action=Edit for authorized tax analysts who need to make manual adjustments. Your application controls which action is passed, so you can enforce role-based access at the URL level.
⚠️ Important
Generated URLs are time-limited and include embedded session tokens. Treat them as sensitive credentials — do not cache, log, or share them. If a URL expires, simply call the endpoint again to generate a fresh one.

Example — Generate a Viewer URL

HTTP Request
GET https://testsuretaxapi.taxrating.net/SureTax/api/v1/Forms/FormInstanceURL?Id=12345&Action=View
Authorization: Bearer {access_token}

Example Response

JSON
{
  "data": {
    "url": "https://sandboxsuretaxapp.taxrating.net?sessionId=9888acf0-1795-4876-8292-a3d6bc5dd4dc&action=View"
  }
}

Example — Embed in an iframe

HTML
<!-- Minimal iframe integration -->
<iframe
  id="suretax-viewer"
  src="https://sandboxsuretaxapp.taxrating.net?sessionId=9888acf0-1795-4876-8292-a3d6bc5dd4dc&action=View"
  width="100%"
  height="800"
  frameborder="0"
  title="SureTax Tax Return Viewer"
  sandbox="allow-scripts allow-same-origin allow-forms allow-popups">
</iframe>

Example — Retrieve Change Log After Editing

HTTP Request
GET https://testsuretaxapi.taxrating.net/SureTax/api/v1/Forms/FormInstanceChangeLog?Id=12345
Authorization: Bearer {access_token}

Example Change Log Response

JSON
{
  "data": {
    "changeLog": [
      {
        "elementId": "12345",
        "elementName": "Line 1 - Gross Sales",
        "attributeId": "attr-001",
        "attributeName": "Amount",
        "oldValue": "150000.00",
        "newValue": "152500.00",
        "changedBy": "jsmith",
        "changedOn": "2025-03-15T14:30:00Z"
      },
      {
        "elementId": "12346",
        "elementName": "Line 3 - Exempt Sales",
        "attributeId": "attr-002",
        "attributeName": "Amount",
        "oldValue": "5000.00",
        "newValue": "7500.00",
        "changedBy": "jsmith",
        "changedOn": "2025-03-15T14:31:00Z"
      }
    ]
  }
}

Integration Patterns

The embedded viewer fits naturally into several common integration architectures:

Edit, Regenerate, and Download Pattern

A critical workflow detail: edits made through the embedded editor are not reflected in the downloadable PDF until you regenerate the form instance. If you download the form before regenerating, you will receive the previous version. The recommended pattern is:

  1. Open the form in Action=Edit mode (embedded iframe)
  2. User makes adjustments and saves within the editor
  3. When the user closes the editor, always call POST FormInstances/regenerate for that form instance — this is safe even if no changes were made
  4. Poll GET GenerationRequestStatus until regeneration completes
  5. Download the updated PDF via FormInstanceDownloadURL
💡 Tip
Use the FormInstanceChangeLog endpoint to determine whether the user actually made changes during the edit session. If the change log is empty (no new entries since the session started), no edits were made. However, calling regenerate regardless is harmless and simplifies your workflow logic.

Resetting and Deleting Form Instances


Complete Inline Review and Adjustment Workflow

The following examples demonstrate the full inline review and adjustment workflow in each supported language: authenticate, verify the form instance, generate a viewer or editor URL, and optionally retrieve the change log after modifications.

Bash — Inline Review & Adjustment Workflow
#!/usr/bin/env bash
set -euo pipefail

# ── Configuration ──────────────────────────────────────────────────────
TOKEN_URL="https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE="https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE="https://testsuretaxapi.taxrating.net/SureTax/api/v1"
CLIENT_ID="YOUR_CLIENT_ID"
CLIENT_SECRET="YOUR_CLIENT_SECRET"
FORM_INSTANCE_ID="12345"
ACTION="Edit"   # "View" for read-only, "Edit" for interactive editing

# ── Step 1: Get OAuth Token ───────────────────────────────────────────
echo "[1/4] Acquiring OAuth token..."
TOKEN=$(curl -s -X POST "$TOKEN_URL" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=$CLIENT_ID" \
  -d "client_secret=$CLIENT_SECRET" \
  -d "scope=$SCOPE" \
  -d "grant_type=client_credentials" \
  | jq -r '.access_token')
echo "      Token acquired."

# ── Step 2: Verify form instance exists ───────────────────────────────
echo "[2/4] Verifying form instance..."
INSTANCE_RESP=$(curl -s -X GET "$API_BASE/Forms/FormInstances?Id=$FORM_INSTANCE_ID" \
  -H "Authorization: Bearer $TOKEN")
STATUS=$(echo "$INSTANCE_RESP" | jq -r '.data.formInstances[0].status')
echo "      Instance $FORM_INSTANCE_ID: Status = $STATUS"

if [[ "$STATUS" == "null" || -z "$STATUS" ]]; then
  echo "      ✗ Form instance not found."
  exit 1
fi
echo "      ✓ Form instance verified."

# ── Step 3: Generate viewer/editor URL ────────────────────────────────
echo "[3/4] Generating $ACTION URL..."
URL_RESP=$(curl -s -X GET \
  "$API_BASE/Forms/FormInstanceURL?Id=$FORM_INSTANCE_ID&Action=$ACTION" \
  -H "Authorization: Bearer $TOKEN")
VIEWER_URL=$(echo "$URL_RESP" | jq -r '.data.url')

if [[ "$VIEWER_URL" == "null" || -z "$VIEWER_URL" ]]; then
  echo "      ✗ Failed to generate URL."
  exit 1
fi
echo "      ✓ URL generated: $VIEWER_URL"
echo ""
echo "      Embed this URL in an <iframe> in your application:"
echo "      <iframe src=\"$VIEWER_URL\" width=\"100%\" height=\"800\"></iframe>"

# ── Step 4 (Optional): Retrieve change log after editing ─────────────
echo ""
echo "[4/4] Retrieving change log for instance $FORM_INSTANCE_ID..."
CHANGELOG=$(curl -s -X GET \
  "$API_BASE/Forms/FormInstanceChangeLog?Id=$FORM_INSTANCE_ID" \
  -H "Authorization: Bearer $TOKEN")
ENTRY_COUNT=$(echo "$CHANGELOG" | jq '.data.changeLog | length')
echo "      $ENTRY_COUNT change(s) recorded."

if [[ "$ENTRY_COUNT" -gt 0 ]]; then
  echo "$CHANGELOG" | jq -r '.data.changeLog[] |
    "      [\(.changedOn)] \(.changedBy): \(.elementName) / \(.attributeName) — \(.oldValue) → \(.newValue)"'
fi

echo ""
echo "Inline review workflow complete."
JavaScript — Inline Review & Adjustment Workflow
const https = require('https');
const querystring = require('querystring');

// ── Configuration ──────────────────────────────────────────────────────
const TOKEN_URL        = 'https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/';
const SCOPE            = 'https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default';
const API_BASE         = 'https://testsuretaxapi.taxrating.net/SureTax/api/v1';
const CLIENT_ID        = 'YOUR_CLIENT_ID';
const CLIENT_SECRET    = 'YOUR_CLIENT_SECRET';
const FORM_INSTANCE_ID = '12345';
const ACTION           = 'Edit';   // 'View' or 'Edit'

// ── Helpers ────────────────────────────────────────────────────────────
function post(url, body, headers = {}) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const data = typeof body === 'string' ? body : querystring.stringify(body);
    const contentType = typeof body === 'string'
      ? 'application/json' : 'application/x-www-form-urlencoded';
    const opts = {
      hostname: u.hostname, path: u.pathname, method: 'POST',
      headers: { 'Content-Type': contentType,
                 'Content-Length': Buffer.byteLength(data), ...headers }
    };
    const req = https.request(opts, res => {
      let chunks = '';
      res.on('data', c => chunks += c);
      res.on('end', () => resolve(JSON.parse(chunks)));
    });
    req.on('error', reject);
    req.write(data);
    req.end();
  });
}

function get(url, token) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const opts = {
      hostname: u.hostname, path: u.pathname + u.search, method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    };
    const req = https.request(opts, res => {
      let chunks = '';
      res.on('data', c => chunks += c);
      res.on('end', () => resolve(JSON.parse(chunks)));
    });
    req.on('error', reject);
    req.end();
  });
}

// ── Main ───────────────────────────────────────────────────────────────
(async () => {
  // Step 1 — Authenticate
  console.log('[1/4] Acquiring OAuth token...');
  const tokenResp = await post(TOKEN_URL, {
    client_id: CLIENT_ID, client_secret: CLIENT_SECRET,
    scope: SCOPE, grant_type: 'client_credentials'
  });
  const token = tokenResp.access_token;
  console.log('      Token acquired.');

  // Step 2 — Verify form instance exists
  console.log('[2/4] Verifying form instance...');
  const instanceResp = await get(
    `${API_BASE}/Forms/FormInstances?Id=${FORM_INSTANCE_ID}`, token);
  const instance = instanceResp.data.formInstances[0];

  if (!instance) {
    console.error(`      ✗ Form instance ${FORM_INSTANCE_ID} not found.`);
    process.exit(1);
  }
  console.log(`      Instance ${FORM_INSTANCE_ID}: Status = ${instance.status}`);
  console.log('      ✓ Form instance verified.');

  // Step 3 — Generate viewer/editor URL
  console.log(`[3/4] Generating ${ACTION} URL...`);
  const urlResp = await get(
    `${API_BASE}/Forms/FormInstanceURL?Id=${FORM_INSTANCE_ID}&Action=${ACTION}`,
    token);
  const viewerUrl = urlResp.data.url;

  if (!viewerUrl) {
    console.error('      ✗ Failed to generate URL.');
    process.exit(1);
  }
  console.log(`      ✓ URL generated: ${viewerUrl}`);
  console.log('');
  console.log('      Embed in your application:');
  console.log(`      <iframe src="${viewerUrl}" width="100%" height="800"></iframe>`);

  // Step 4 (Optional) — Retrieve change log after editing
  console.log('');
  console.log(`[4/4] Retrieving change log for instance ${FORM_INSTANCE_ID}...`);
  const logResp = await get(
    `${API_BASE}/Forms/FormInstanceChangeLog?Id=${FORM_INSTANCE_ID}`, token);
  const entries = logResp.data.changeLog || [];
  console.log(`      ${entries.length} change(s) recorded.`);

  for (const entry of entries) {
    console.log(`      [${entry.changedOn}] ${entry.changedBy}: ` +
      `${entry.elementName} / ${entry.attributeName} — ` +
      `${entry.oldValue} → ${entry.newValue}`);
  }

  console.log('');
  console.log('Inline review workflow complete.');
})();
Python — Inline Review & Adjustment Workflow
import requests
import json

# ── Configuration ──────────────────────────────────────────────────────
TOKEN_URL        = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE            = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE         = "https://testsuretaxapi.taxrating.net/SureTax/api/v1"
CLIENT_ID        = "YOUR_CLIENT_ID"
CLIENT_SECRET    = "YOUR_CLIENT_SECRET"
FORM_INSTANCE_ID = "12345"
ACTION           = "Edit"   # "View" for read-only, "Edit" for interactive editing

# ── Step 1: Get OAuth Token ───────────────────────────────────────────
print("[1/4] Acquiring OAuth token...")
token_resp = requests.post(TOKEN_URL, data={
    "client_id":     CLIENT_ID,
    "client_secret": CLIENT_SECRET,
    "scope":         SCOPE,
    "grant_type":    "client_credentials"
})
token_resp.raise_for_status()
token = token_resp.json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
print("      Token acquired.")

# ── Step 2: Verify form instance exists ───────────────────────────────
print("[2/4] Verifying form instance...")
instance_resp = requests.get(
    f"{API_BASE}/Forms/FormInstances",
    params={"Id": FORM_INSTANCE_ID},
    headers=headers
)
instance_resp.raise_for_status()
instances = instance_resp.json()["data"]["formInstances"]

if not instances:
    print(f"      ✗ Form instance {FORM_INSTANCE_ID} not found.")
    exit(1)

status = instances[0]["status"]
print(f"      Instance {FORM_INSTANCE_ID}: Status = {status}")
print("      ✓ Form instance verified.")

# ── Step 3: Generate viewer/editor URL ────────────────────────────────
print(f"[3/4] Generating {ACTION} URL...")
url_resp = requests.get(
    f"{API_BASE}/Forms/FormInstanceURL",
    params={"Id": FORM_INSTANCE_ID, "Action": ACTION},
    headers=headers
)
url_resp.raise_for_status()
viewer_url = url_resp.json()["data"]["url"]

if not viewer_url:
    print("      ✗ Failed to generate URL.")
    exit(1)

print(f"      ✓ URL generated: {viewer_url}")
print()
print("      Embed in your application:")
print(f'      <iframe src="{viewer_url}" width="100%" height="800"></iframe>')

# ── Step 4 (Optional): Retrieve change log after editing ─────────────
print()
print(f"[4/4] Retrieving change log for instance {FORM_INSTANCE_ID}...")
log_resp = requests.get(
    f"{API_BASE}/Forms/FormInstanceChangeLog",
    params={"Id": FORM_INSTANCE_ID},
    headers=headers
)
log_resp.raise_for_status()
entries = log_resp.json()["data"]["changeLog"]
print(f"      {len(entries)} change(s) recorded.")

for entry in entries:
    print(f"      [{entry['changedOn']}] {entry['changedBy']}: "
          f"{entry['elementName']} / {entry['attributeName']} — "
          f"{entry['oldValue']} → {entry['newValue']}")

print()
print("Inline review workflow complete.")
C# — Inline Review & Adjustment Workflow
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

public class SureTaxInlineReviewClient
{
    // -- Configuration --------------------------------------------------
    private const string TokenUrl       = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/";
    private const string OAuthScope     = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default";
    private const string ApiBaseUrl     = "https://testsuretaxapi.taxrating.net";
    private const string ClientId       = "YOUR_CLIENT_ID";
    private const string ClientSecret   = "YOUR_CLIENT_SECRET";
    private const string FormInstanceId = "12345";
    private const string Action         = "Edit";  // "View" or "Edit"

    private static readonly HttpClient Http = new HttpClient();

    public static async Task Main(string[] args)
    {
        // Step 1 — Authenticate
        Console.WriteLine("[1/4] Acquiring OAuth token...");
        var token = await GetAccessTokenAsync();
        Http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

        // Step 2 — Verify form instance exists
        Console.WriteLine("[2/4] Verifying form instance...");
        var instance = await GetFormInstanceAsync(FormInstanceId);

        if (instance == null)
        {
            Console.WriteLine($"      ✗ Form instance {FormInstanceId} not found.");
            return;
        }
        Console.WriteLine($"      Instance {FormInstanceId}: Status = {instance.Status}");
        Console.WriteLine("      ✓ Form instance verified.");

        // Step 3 — Generate viewer/editor URL
        Console.WriteLine($"[3/4] Generating {Action} URL...");
        var viewerUrl = await GetFormInstanceUrlAsync(FormInstanceId, Action);

        if (string.IsNullOrEmpty(viewerUrl))
        {
            Console.WriteLine("      ✗ Failed to generate URL.");
            return;
        }
        Console.WriteLine($"      ✓ URL generated: {viewerUrl}");
        Console.WriteLine();
        Console.WriteLine("      Embed in your application:");
        Console.WriteLine($"      <iframe src=\"{viewerUrl}\" width=\"100%\" " +
            "height=\"800\"></iframe>");

        // Step 4 (Optional) — Retrieve change log after editing
        Console.WriteLine();
        Console.WriteLine($"[4/4] Retrieving change log for instance {FormInstanceId}...");
        var entries = await GetChangeLogAsync(FormInstanceId);
        Console.WriteLine($"      {entries.Count} change(s) recorded.");

        foreach (var entry in entries)
        {
            Console.WriteLine($"      [{entry.ChangedOn}] {entry.ChangedBy}: " +
                $"{entry.ElementName} / {entry.AttributeName} — " +
                $"{entry.OldValue} → {entry.NewValue}");
        }

        Console.WriteLine();
        Console.WriteLine("Inline review workflow complete.");
    }

    // -- Authentication -------------------------------------------------
    private static async Task<string> GetAccessTokenAsync()
    {
        var body = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id",     ClientId),
            new KeyValuePair<string, string>("client_secret",  ClientSecret),
            new KeyValuePair<string, string>("scope",          OAuthScope),
            new KeyValuePair<string, string>("grant_type",     "client_credentials")
        });

        var resp = await Http.PostAsync(TokenUrl, body);
        resp.EnsureSuccessStatusCode();
        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        return doc.RootElement.GetProperty("access_token").GetString()!;
    }

    // -- Step 2: Get Form Instance --------------------------------------
    private static async Task<FormInstance?> GetFormInstanceAsync(string instanceId)
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstances?Id={instanceId}");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        var arr = doc.RootElement.GetProperty("data")
                     .GetProperty("formInstances");

        if (arr.GetArrayLength() == 0) return null;

        var fi = arr[0];
        return new FormInstance
        {
            Id     = fi.GetProperty("id").GetString()!,
            Status = fi.GetProperty("status").GetString()!,
            Name   = fi.TryGetProperty("name", out var n) ? n.GetString()! : ""
        };
    }

    // -- Step 3: Get Form Instance URL ----------------------------------
    private static async Task<string> GetFormInstanceUrlAsync(
        string instanceId, string action)
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstanceURL" +
            $"?Id={instanceId}&Action={action}");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        return doc.RootElement.GetProperty("data")
                   .GetProperty("url").GetString() ?? "";
    }

    // -- Step 4: Get Change Log -----------------------------------------
    private static async Task<List<ChangeLogEntry>> GetChangeLogAsync(
        string instanceId)
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstanceChangeLog" +
            $"?Id={instanceId}");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        var log = doc.RootElement.GetProperty("data")
                     .GetProperty("changeLog");

        var entries = new List<ChangeLogEntry>();
        foreach (var item in log.EnumerateArray())
        {
            entries.Add(new ChangeLogEntry
            {
                ElementName   = item.GetProperty("elementName").GetString()!,
                AttributeName = item.GetProperty("attributeName").GetString()!,
                OldValue      = item.GetProperty("oldValue").GetString()!,
                NewValue      = item.GetProperty("newValue").GetString()!,
                ChangedBy     = item.GetProperty("changedBy").GetString()!,
                ChangedOn     = item.GetProperty("changedOn").GetString()!
            });
        }
        return entries;
    }

    // -- Data Models ----------------------------------------------------
    private record FormInstance
    {
        public string Id     { get; init; } = "";
        public string Status { get; init; } = "";
        public string Name   { get; init; } = "";
    }

    private record ChangeLogEntry
    {
        public string ElementName   { get; init; } = "";
        public string AttributeName { get; init; } = "";
        public string OldValue      { get; init; } = "";
        public string NewValue      { get; init; } = "";
        public string ChangedBy     { get; init; } = "";
        public string ChangedOn     { get; init; } = "";
    }
}

🔑 Key Points

  • Verify first — Always confirm the form instance exists and check its status before generating a URL. This prevents errors from invalid or deleted instance IDs.
  • Action controls access — Your application decides whether to pass View or Edit. Use this to enforce role-based access: reviewers get View, tax analysts get Edit.
  • URLs are temporary — Generated URLs expire after a limited time. Do not cache or persist them. If a user needs to return to the form later, generate a fresh URL.
  • URLs contain embedded authentication — No additional login is required inside the iframe. Treat generated URLs as sensitive credentials.
  • Change Log for auditability — The Change Log endpoint provides a complete, tamper-evident record of every modification. Use it to satisfy regulatory audit requirements and internal compliance reviews.
  • Sandbox attribute — When embedding in an iframe, use the sandbox attribute (allow-scripts allow-same-origin allow-forms allow-popups) to apply the principle of least privilege while ensuring the SureTax interface functions correctly.

E-Filing Tax Returns

If your organization wants to integrate electronic filing directly into your compliance workflows, the Returns API supports programmatic e-filing of generated tax returns. Rather than manually submitting returns through the SureTax Portal, you can automate the entire submit → track → confirm cycle using the same API you already use for returns generation and download.

When to Use E-Filing Integration

E-Filing Workflow

StepOperationEndpointMethodDescription
1Review Generated Return/SureTax/api/v1/Forms/FormInstances?Id={instanceId}GETConfirm the form instance status is GEN or GWW before submitting.
2Submit for E-Filing/SureTax/api/v1/Forms/FormInstances/efilePOSTSubmit one or more generated form instances to the taxing authority for electronic filing.
3Poll Submission Status/SureTax/api/v1/Forms/FormInstances?Id={instanceId}GETMonitor the form instance status as it transitions through the e-filing lifecycle.

How It Works

  1. After generating and optionally downloading a return (see previous workflows), verify the form instance status is GEN or GWW by calling GET FormInstances.
  2. Submit the form instance for e-filing by calling POST FormInstances/efile with the instance ID(s) in the request body. The API queues the return for transmission to the appropriate taxing authority.
  3. Poll GET FormInstances periodically to track the submission status as it moves through the e-filing lifecycle.

E-Filing Status Lifecycle

GEN Generated STG Submitted SOK Accepted ✓ Happy Path SDE Declined ✗ Review & Resubmit
StatusMeaningNext Action
GENGenerated successfully — ready for e-filingSubmit via POST FormInstances/efile
GWWGenerated with warnings — review recommendedReview warnings, then submit if acceptable
STGSubmitted to government — in transitContinue polling; no action required
SOKAccepted by government — filing completeNo further action; archive confirmation
SDEDeclined by government — submission rejectedReview rejection reason, correct, and resubmit

Example — Submit for E-Filing

HTTP Request
POST https://testsuretaxapi.taxrating.net/SureTax/api/v1/Forms/FormInstances/efile
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "formInstanceIds": ["12345", "12346"]
}

Example — Poll Submission Status

HTTP Request
GET https://testsuretaxapi.taxrating.net/SureTax/api/v1/Forms/FormInstances?Id=12345
Authorization: Bearer {access_token}

Example Response (Accepted)

JSON
{
  "data": {
    "formInstances": [
      {
        "id": "12345",
        "status": "SOK",
        "statusDescription": "Content accepted by government",
        "formName": "Texas State Sales Tax Return",
        "filingPeriod": "2026-02",
        "submittedDate": "2026-03-15T14:30:00Z",
        "acceptedDate": "2026-03-15T16:45:00Z"
      }
    ]
  }
}
💡 Tip
Build automated retry logic for SDE (declined) statuses. Common decline reasons include data validation errors or duplicate submissions. Retrieve the decline details from the form instance response, correct the issue, regenerate if necessary, and resubmit.
⚠️ Important
E-filing is irreversible once the status reaches SOK. Always review generated returns (download and inspect the PDF) before submitting for e-filing, especially for forms with a GWW (generated with warnings) status.

Complete E-Filing Workflow

The following examples demonstrate the full e-filing workflow in each supported language: authenticate, retrieve a generated form instance, verify its status, submit for e-filing, and poll until the taxing authority accepts or declines the submission.

Bash — E-Filing Workflow
#!/usr/bin/env bash
set -euo pipefail

# ── Configuration ──────────────────────────────────────────────────────
TOKEN_URL="https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE="https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE="https://testsuretaxapi.taxrating.net/SureTax/api/v1"
CLIENT_ID="YOUR_CLIENT_ID"
CLIENT_SECRET="YOUR_CLIENT_SECRET"
FORM_INSTANCE_IDS=("12345" "12346")
POLL_INTERVAL=30
MAX_ATTEMPTS=60

# ── Step 1: Get OAuth Token ───────────────────────────────────────────
echo "[1/4] Acquiring OAuth token..."
TOKEN=$(curl -s -X POST "$TOKEN_URL" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=$CLIENT_ID" \
  -d "client_secret=$CLIENT_SECRET" \
  -d "scope=$SCOPE" \
  -d "grant_type=client_credentials" \
  | jq -r '.access_token')
echo "      Token acquired."

# ── Step 2: Verify form instances are ready for e-filing ──────────────
echo "[2/4] Verifying form instance status..."
for ID in "${FORM_INSTANCE_IDS[@]}"; do
  STATUS=$(curl -s -X GET "$API_BASE/Forms/FormInstances?Id=$ID" \
    -H "Authorization: Bearer $TOKEN" \
    | jq -r '.data.formInstances[0].status')
  echo "      Instance $ID: Status = $STATUS"

  if [[ "$STATUS" != "GEN" && "$STATUS" != "GWW" ]]; then
    echo "      ✗ Instance $ID is not in a fileable state (expected GEN or GWW)."
    exit 1
  fi
  [[ "$STATUS" == "GWW" ]] && echo "      ⚠ Instance $ID has warnings — review before filing."
done
echo "      ✓ All instances ready for e-filing."

# ── Step 3: Submit for e-filing ───────────────────────────────────────
echo "[3/4] Submitting for e-filing..."
IDS_JSON=$(printf '%s\n' "${FORM_INSTANCE_IDS[@]}" | jq -R . | jq -s '.')
curl -s -X POST "$API_BASE/Forms/FormInstances/efile" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"formInstanceIds\": $IDS_JSON}" > /dev/null
echo "      ✓ Submission queued."

# ── Step 4: Poll until terminal status ────────────────────────────────
echo "[4/4] Polling submission status (${POLL_INTERVAL}s interval)..."
for ID in "${FORM_INSTANCE_IDS[@]}"; do
  for (( ATTEMPT=1; ATTEMPT<=MAX_ATTEMPTS; ATTEMPT++ )); do
    STATUS=$(curl -s -X GET "$API_BASE/Forms/FormInstances?Id=$ID" \
      -H "Authorization: Bearer $TOKEN" \
      | jq -r '.data.formInstances[0].status')
    echo "      Attempt $ATTEMPT/$MAX_ATTEMPTS [$ID]: Status = $STATUS"

    [[ "$STATUS" == "SOK" ]] && echo "      ✓ Instance $ID: Accepted by government." && break
    [[ "$STATUS" == "SDE" ]] && echo "      ✗ Instance $ID: Declined. Review and resubmit." && break
    sleep "$POLL_INTERVAL"
  done
done
echo "E-filing workflow complete."
JavaScript (Node.js) — E-Filing Workflow
const https = require('https');
const querystring = require('querystring');

// ── Configuration ──────────────────────────────────────────────────────
const TOKEN_URL     = 'https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/';
const SCOPE         = 'https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default';
const API_BASE      = 'https://testsuretaxapi.taxrating.net/SureTax/api/v1';
const CLIENT_ID     = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const FORM_IDS      = ['12345', '12346'];
const POLL_INTERVAL = 30000;  // ms
const MAX_ATTEMPTS  = 60;

// ── Helpers ────────────────────────────────────────────────────────────
function post(url, body, headers = {}) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const data = typeof body === 'string' ? body : querystring.stringify(body);
    const contentType = typeof body === 'string'
      ? 'application/json' : 'application/x-www-form-urlencoded';
    const opts = {
      hostname: u.hostname, path: u.pathname, method: 'POST',
      headers: { 'Content-Type': contentType,
                 'Content-Length': Buffer.byteLength(data), ...headers }
    };
    const req = https.request(opts, res => {
      let chunks = '';
      res.on('data', c => chunks += c);
      res.on('end', () => resolve(JSON.parse(chunks)));
    });
    req.on('error', reject);
    req.write(data);
    req.end();
  });
}

function get(url, token) {
  return new Promise((resolve, reject) => {
    const u = new URL(url);
    const opts = {
      hostname: u.hostname, path: u.pathname + u.search, method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    };
    const req = https.request(opts, res => {
      let chunks = '';
      res.on('data', c => chunks += c);
      res.on('end', () => resolve(JSON.parse(chunks)));
    });
    req.on('error', reject);
    req.end();
  });
}

const sleep = ms => new Promise(r => setTimeout(r, ms));

// ── Main ───────────────────────────────────────────────────────────────
(async () => {
  // Step 1 — Authenticate
  console.log('[1/4] Acquiring OAuth token...');
  const tokenResp = await post(TOKEN_URL, {
    client_id: CLIENT_ID, client_secret: CLIENT_SECRET,
    scope: SCOPE, grant_type: 'client_credentials'
  });
  const token = tokenResp.access_token;
  console.log('      Token acquired.');

  // Step 2 — Verify form instances
  console.log('[2/4] Verifying form instance status...');
  for (const id of FORM_IDS) {
    const resp = await get(`${API_BASE}/Forms/FormInstances?Id=${id}`, token);
    const status = resp.data.formInstances[0].status;
    console.log(`      Instance ${id}: Status = ${status}`);

    if (status !== 'GEN' && status !== 'GWW') {
      console.error(`      ✗ Instance ${id} not fileable (expected GEN or GWW).`);
      process.exit(1);
    }
    if (status === 'GWW') console.log(`      ⚠ Instance ${id} has warnings.`);
  }
  console.log('      ✓ All instances ready for e-filing.');

  // Step 3 — Submit for e-filing
  console.log('[3/4] Submitting for e-filing...');
  await post(`${API_BASE}/Forms/FormInstances/efile`,
    JSON.stringify({ formInstanceIds: FORM_IDS }),
    { 'Authorization': `Bearer ${token}` });
  console.log('      ✓ Submission queued.');

  // Step 4 — Poll until terminal status
  console.log('[4/4] Polling submission status (30 s interval)...');
  for (const id of FORM_IDS) {
    for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
      const resp = await get(`${API_BASE}/Forms/FormInstances?Id=${id}`, token);
      const status = resp.data.formInstances[0].status;
      console.log(`      Attempt ${attempt}/${MAX_ATTEMPTS} [${id}]: Status = ${status}`);

      if (status === 'SOK') { console.log(`      ✓ Instance ${id}: Accepted.`); break; }
      if (status === 'SDE') { console.log(`      ✗ Instance ${id}: Declined.`); break; }
      await sleep(POLL_INTERVAL);
    }
  }
  console.log('E-filing workflow complete.');
})();
Python — E-Filing Workflow
import requests
import time
import json

# ── Configuration ──────────────────────────────────────────────────────
TOKEN_URL     = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE         = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE      = "https://testsuretaxapi.taxrating.net/SureTax/api/v1"
CLIENT_ID     = "YOUR_CLIENT_ID"
CLIENT_SECRET = "YOUR_CLIENT_SECRET"
FORM_IDS      = ["12345", "12346"]
POLL_INTERVAL = 30   # seconds
MAX_ATTEMPTS  = 60

# ── Step 1: Get OAuth Token ───────────────────────────────────────────
print("[1/4] Acquiring OAuth token...")
token_resp = requests.post(TOKEN_URL, data={
    "client_id":     CLIENT_ID,
    "client_secret": CLIENT_SECRET,
    "scope":         SCOPE,
    "grant_type":    "client_credentials"
})
token_resp.raise_for_status()
token = token_resp.json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
print("      Token acquired.")

# ── Step 2: Verify form instances are ready for e-filing ──────────────
print("[2/4] Verifying form instance status...")
for fid in FORM_IDS:
    resp = requests.get(f"{API_BASE}/Forms/FormInstances", params={"Id": fid}, headers=headers)
    resp.raise_for_status()
    status = resp.json()["data"]["formInstances"][0]["status"]
    print(f"      Instance {fid}: Status = {status}")

    if status not in ("GEN", "GWW"):
        print(f"      ✗ Instance {fid} is not in a fileable state (expected GEN or GWW).")
        exit(1)
    if status == "GWW":
        print(f"      ⚠ Instance {fid} has warnings — review before filing.")

print("      ✓ All instances ready for e-filing.")

# ── Step 3: Submit for e-filing ───────────────────────────────────────
print("[3/4] Submitting for e-filing...")
efile_resp = requests.post(
    f"{API_BASE}/Forms/FormInstances/efile",
    json={"formInstanceIds": FORM_IDS},
    headers=headers
)
efile_resp.raise_for_status()
print("      ✓ Submission queued.")

# ── Step 4: Poll until terminal status ────────────────────────────────
print(f"[4/4] Polling submission status ({POLL_INTERVAL}s interval)...")
for fid in FORM_IDS:
    for attempt in range(1, MAX_ATTEMPTS + 1):
        resp = requests.get(f"{API_BASE}/Forms/FormInstances", params={"Id": fid}, headers=headers)
        resp.raise_for_status()
        status = resp.json()["data"]["formInstances"][0]["status"]
        print(f"      Attempt {attempt}/{MAX_ATTEMPTS} [{fid}]: Status = {status}")

        if status == "SOK":
            print(f"      ✓ Instance {fid}: Accepted by government.")
            break
        elif status == "SDE":
            print(f"      ✗ Instance {fid}: Declined. Review and resubmit.")
            break
        time.sleep(POLL_INTERVAL)
    else:
        print(f"      Timeout: Instance {fid} did not reach terminal status.")

print("E-filing workflow complete.")
C# — SureTaxEFilingClient.cs
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class SureTaxEFilingClient
{
    // -- Configuration --------------------------------------------------
    private const string TokenUrl     = "https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/";
    private const string OAuthScope   = "https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default";
    private const string ApiBaseUrl   = "https://testsuretaxapi.taxrating.net";
    private const string ClientId     = "YOUR_CLIENT_ID";
    private const string ClientSecret = "YOUR_CLIENT_SECRET";
    private const int    PollInterval = 30;    // seconds
    private const int    MaxAttempts  = 60;

    private static readonly HttpClient Http = new HttpClient();

    public static async Task Main(string[] args)
    {
        // The form instance IDs from a previous returns generation workflow
        var formInstanceIds = new[] { "12345", "12346" };

        // Step 1 — Authenticate
        Console.WriteLine("[1/4] Acquiring OAuth token...");
        var token = await GetAccessTokenAsync();
        Http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

        // Step 2 — Verify form instances are ready for e-filing
        Console.WriteLine("[2/4] Verifying form instance status...");
        foreach (var id in formInstanceIds)
        {
            var instance = await GetFormInstanceAsync(id);
            Console.WriteLine($"      Instance {id}: Status = {instance.Status}");

            if (instance.Status != "GEN" && instance.Status != "GWW")
            {
                Console.WriteLine($"      ✗ Instance {id} is not in a fileable state. " +
                    $"Expected GEN or GWW, got {instance.Status}.");
                return;
            }

            if (instance.Status == "GWW")
                Console.WriteLine($"      ⚠ Instance {id} has warnings — review before filing.");
        }
        Console.WriteLine("      ✓ All instances ready for e-filing.");

        // Step 3 — Submit for e-filing
        Console.WriteLine("[3/4] Submitting for e-filing...");
        await SubmitForEFilingAsync(formInstanceIds);
        Console.WriteLine("      ✓ Submission queued.");

        // Step 4 — Poll until all submissions reach a terminal status
        Console.WriteLine("[4/4] Polling submission status (30 s interval)...");
        foreach (var id in formInstanceIds)
        {
            var finalStatus = await PollEFilingStatusAsync(id);
            if (finalStatus == "SOK")
                Console.WriteLine($"      ✓ Instance {id}: Accepted by government.");
            else if (finalStatus == "SDE")
                Console.WriteLine($"      ✗ Instance {id}: Declined by government. " +
                    "Review and resubmit.");
            else
                Console.WriteLine($"      ? Instance {id}: Final status = {finalStatus}");
        }

        Console.WriteLine("E-filing workflow complete.");
    }

    // -- Authentication -------------------------------------------------
    private static async Task<string> GetAccessTokenAsync()
    {
        var body = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id",     ClientId),
            new KeyValuePair<string, string>("client_secret",  ClientSecret),
            new KeyValuePair<string, string>("scope",          OAuthScope),
            new KeyValuePair<string, string>("grant_type",     "client_credentials")
        });

        var resp = await Http.PostAsync(TokenUrl, body);
        resp.EnsureSuccessStatusCode();
        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        return doc.RootElement.GetProperty("access_token").GetString()!;
    }

    // -- Step 2: Get Form Instance --------------------------------------
    private static async Task<FormInstance> GetFormInstanceAsync(string instanceId)
    {
        var resp = await Http.GetAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstances?Id={instanceId}");
        resp.EnsureSuccessStatusCode();

        var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
        var fi  = doc.RootElement.GetProperty("data")
                     .GetProperty("formInstances")[0];

        return new FormInstance
        {
            Id     = fi.GetProperty("id").GetString()!,
            Status = fi.GetProperty("status").GetString()!,
            Name   = fi.TryGetProperty("name", out var n) ? n.GetString()! : ""
        };
    }

    // -- Step 3: Submit for E-Filing ------------------------------------
    private static async Task SubmitForEFilingAsync(string[] instanceIds)
    {
        var payload = JsonSerializer.Serialize(new
        {
            formInstanceIds = instanceIds
        });

        var resp = await Http.PostAsync(
            $"{ApiBaseUrl}/SureTax/api/v1/Forms/FormInstances/efile",
            new StringContent(payload, Encoding.UTF8, "application/json"));
        resp.EnsureSuccessStatusCode();
    }

    // -- Step 4: Poll E-Filing Status -----------------------------------
    private static async Task<string> PollEFilingStatusAsync(string instanceId)
    {
        for (int attempt = 1; attempt <= MaxAttempts; attempt++)
        {
            var instance = await GetFormInstanceAsync(instanceId);

            Console.WriteLine($"      Attempt {attempt}/{MaxAttempts} " +
                $"[{instanceId}]: Status = {instance.Status}");

            // Terminal statuses — stop polling
            if (instance.Status == "SOK" || instance.Status == "SDE")
                return instance.Status;

            // STG means still in transit — keep polling
            await Task.Delay(TimeSpan.FromSeconds(PollInterval));
        }

        Console.WriteLine($"      Timeout: Instance {instanceId} did not reach " +
            "a terminal status within the polling window.");
        return "TIMEOUT";
    }

    // -- Data Models ----------------------------------------------------
    private record FormInstance
    {
        public string Id     { get; init; } = "";
        public string Status { get; init; } = "";
        public string Name   { get; init; } = "";
    }
}

🔑 Key Points

  • Verify before submitting — Always check that form instances are in GEN or GWW status before calling the e-file endpoint. Attempting to e-file an instance in any other status will result in an error.
  • GWW instances can be e-filed but should be reviewed first. Warnings may indicate missing data or unusual tax amounts that could trigger government rejection.
  • Terminal statuses are SOK (accepted) and SDE (declined). Once a submission reaches SOK, it cannot be reversed or resubmitted.
  • SDE recovery — When a submission is declined, retrieve the full form instance details to inspect the rejection reason. Common causes include validation errors, duplicate filings, or expired filing periods. Correct the issue, regenerate the return, and resubmit.
  • Poll interval — Government processing times vary by jurisdiction. A 30-second interval is recommended for e-filing status checks. Some jurisdictions may take hours to respond.

Extracting Reports for Analysis

After returns are generated and filed, the next step in the compliance workflow is extracting report data for internal analysis, reconciliation, and audit preparation. SureTax provides a Reports API that gives you programmatic access to a comprehensive library of pre-built compliance and tax analysis reports.

Report Extract Workflow

StepActionDescription
1 List Available Reports Call POST /api/Reports?api-version=1.0 to retrieve the report catalog available to the authenticated client.
2 Run a Report Call POST /api/Reports/{reportId}/run?api-version=1.0 with output format and parameters. The API returns 202 Accepted with a requestId.
3 Poll Status Call GET /api/Reports/{requestId}/status?api-version=1.0 until status is Completed, CompletedWithNoData, or Failed.
4 Download Output When status is Completed, call GET /api/Reports/{requestId}/download?api-version=1.0 to stream CSV/XLSX output.

Reports API Endpoints Used in This Workflow

StepOperationEndpointMethodPurpose
1Get Available Reports/api/Reports?api-version=1.0POSTReturns report IDs and names available to the client.
2Run Report/api/Reports/{reportId}/run?api-version=1.0POSTQueues asynchronous execution and returns requestId.
3Get Report Status/api/Reports/{requestId}/status?api-version=1.0GETReturns execution status and download link when complete.
4Download Report/api/Reports/{requestId}/download?api-version=1.0GETStreams the generated report file.
📝 Required Headers
All Reports API requests require Authorization: Bearer {token}, X-Client-Number, and X-Validation-Key.

Available Reports

The Reports API provides access to a wide range of reports, including:

ReportPurpose
Aggregate ReportRevenue and tax data aggregated by state, county, and city for streamlined analysis.
Compliance ReportCore compliance data with service group, tax type, and tax category breakdowns by jurisdiction.
Compliance Invoice ReportDetailed compliance data at the invoice level with tax type and sales type breakdowns.
Tax Summary ReportOverview of tax-related information segmented by geographic regions and business units.
Regulatory ReportSpecialized regulatory compliance data for telecommunications and utilities industries.
Funding Request ReportReconciliation and audit-trail report showing where tax liability was allocated for a given filing period.
Tax Compliance ReportReadable, structured report with tax authorities as rows and tax types as columns for easy compliance visibility.
📝 Full Report Reference
For a complete list of available reports and their field definitions, see the Report Extracts reference.

Complete Reports API Download Workflow

The following examples demonstrate the end-to-end pattern in each supported language: authenticate, list reports, run a report, poll status, and download the output.

Bash — Reports API Workflow
#!/usr/bin/env bash
set -euo pipefail

TOKEN_URL="https://cpesgsuretaxcert.b2clogin.com/cpesgsuretaxcert.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token/"
SCOPE="https://cpesgsuretaxcert.onmicrosoft.com/dc817fc6-62b3-4277-a467-e119201232c0/.default"
API_BASE="https://testapi.suretax.com/suretax-reporting/api"
CLIENT_ID="YOUR_CLIENT_ID"
CLIENT_SECRET="YOUR_CLIENT_SECRET"
CLIENT_NUMBER="YOUR_CLIENT_NUMBER"
VALIDATION_KEY="YOUR_VALIDATION_KEY"

TOKEN=$(curl -s -X POST "$TOKEN_URL" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "client_id=$CLIENT_ID" \
    -d "client_secret=$CLIENT_SECRET" \
    -d "scope=$SCOPE" \
    -d "grant_type=client_credentials" | jq -r '.access_token')

REPORT_ID=$(curl -s -X POST "$API_BASE/Reports?api-version=1.0" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Client-Number: $CLIENT_NUMBER" \
    -H "X-Validation-Key: $VALIDATION_KEY" | jq -r '.[0].reportId')

REQUEST_ID=$(curl -s -X POST "$API_BASE/Reports/$REPORT_ID/run?api-version=1.0" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Client-Number: $CLIENT_NUMBER" \
    -H "X-Validation-Key: $VALIDATION_KEY" \
    -H "Content-Type: application/json" \
    -d '{"reportOutputFormat":"csv","parameters":{"ComplianceYear":"2026","ComplianceMonth":"Q2"}}' \
    | jq -r '.requestId')

while true; do
    STATUS=$(curl -s -X GET "$API_BASE/Reports/$REQUEST_ID/status?api-version=1.0" \
        -H "Authorization: Bearer $TOKEN" \
        -H "X-Client-Number: $CLIENT_NUMBER" \
        -H "X-Validation-Key: $VALIDATION_KEY" | jq -r '.status')
    [[ "$STATUS" == "Completed" || "$STATUS" == "CompletedWithNoData" || "$STATUS" == "Failed" ]] && break
    sleep 5
done

curl -s -X GET "$API_BASE/Reports/$REQUEST_ID/download?api-version=1.0" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Client-Number: $CLIENT_NUMBER" \
    -H "X-Validation-Key: $VALIDATION_KEY" \
    --output "report-$REQUEST_ID.csv"
JavaScript (Node.js) — Reports API Workflow
const API_BASE = 'https://testapi.suretax.com/suretax-reporting/api';

function apiHeaders(token) {
    return {
        Authorization: `Bearer ${token}`,
        'X-Client-Number': 'YOUR_CLIENT_NUMBER',
        'X-Validation-Key': 'YOUR_VALIDATION_KEY'
    };
}

async function runAndDownload(token) {
    const available = await fetch(`${API_BASE}/Reports?api-version=1.0`, {
        method: 'POST', headers: apiHeaders(token)
    }).then(r => r.json());

    const reportId = available[0].reportId;

    const run = await fetch(`${API_BASE}/Reports/${reportId}/run?api-version=1.0`, {
        method: 'POST',
        headers: { ...apiHeaders(token), 'Content-Type': 'application/json' },
        body: JSON.stringify({
            reportOutputFormat: 'csv',
            parameters: { ComplianceYear: '2026', ComplianceMonth: 'Q2' }
        })
    }).then(r => r.json());

    const requestId = run.requestId;
    let status = 'Queued';

    while (!['Completed', 'CompletedWithNoData', 'Failed'].includes(status)) {
        const statusBody = await fetch(`${API_BASE}/Reports/${requestId}/status?api-version=1.0`, {
            headers: apiHeaders(token)
        }).then(r => r.json());
        status = statusBody.status;
        if (!['Completed', 'CompletedWithNoData', 'Failed'].includes(status)) {
            await new Promise(resolve => setTimeout(resolve, 5000));
        }
    }

    const response = await fetch(`${API_BASE}/Reports/${requestId}/download?api-version=1.0`, {
        headers: apiHeaders(token)
    });
    const bytes = Buffer.from(await response.arrayBuffer());
    const fs = await import('node:fs/promises');
    await fs.writeFile(`report-${requestId}.csv`, bytes);
}
Python — Reports API Workflow
import requests
import time

API_BASE = "https://testapi.suretax.com/suretax-reporting/api"
headers = {
        "Authorization": "Bearer YOUR_TOKEN",
        "X-Client-Number": "YOUR_CLIENT_NUMBER",
        "X-Validation-Key": "YOUR_VALIDATION_KEY",
}

available = requests.post(f"{API_BASE}/Reports", params={"api-version": "1.0"}, headers=headers)
available.raise_for_status()
report_id = available.json()[0]["reportId"]

run = requests.post(
        f"{API_BASE}/Reports/{report_id}/run",
        params={"api-version": "1.0"},
        headers={**headers, "Content-Type": "application/json"},
        json={"reportOutputFormat": "csv", "parameters": {"ComplianceYear": "2026", "ComplianceMonth": "Q2"}},
)
run.raise_for_status()
request_id = run.json()["requestId"]

while True:
        status_resp = requests.get(f"{API_BASE}/Reports/{request_id}/status", params={"api-version": "1.0"}, headers=headers)
        status_resp.raise_for_status()
        status = status_resp.json()["status"]
        if status in {"Completed", "CompletedWithNoData", "Failed"}:
                break
        time.sleep(5)

download = requests.get(
        f"{API_BASE}/Reports/{request_id}/download",
        params={"api-version": "1.0"},
        headers=headers,
        stream=True,
)
download.raise_for_status()

with open(f"report-{request_id}.csv", "wb") as f:
        for chunk in download.iter_content(8192):
                f.write(chunk)
C# — Reports API Workflow
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", "YOUR_TOKEN");
http.DefaultRequestHeaders.Add("X-Client-Number", "YOUR_CLIENT_NUMBER");
http.DefaultRequestHeaders.Add("X-Validation-Key", "YOUR_VALIDATION_KEY");

var reportsJson = await http.PostAsync(
        "https://testapi.suretax.com/suretax-reporting/api/Reports?api-version=1.0",
        new StringContent(string.Empty));
reportsJson.EnsureSuccessStatusCode();

var available = JsonDocument.Parse(await reportsJson.Content.ReadAsStringAsync());
var reportId = available.RootElement[0].GetProperty("reportId").GetInt32();

var runPayload = JsonSerializer.Serialize(new {
        reportOutputFormat = "csv",
        parameters = new { ComplianceYear = "2026", ComplianceMonth = "Q2" }
});

var runResp = await http.PostAsync(
        $"https://testapi.suretax.com/suretax-reporting/api/Reports/{reportId}/run?api-version=1.0",
        new StringContent(runPayload, Encoding.UTF8, "application/json"));
runResp.EnsureSuccessStatusCode();

var runDoc = JsonDocument.Parse(await runResp.Content.ReadAsStringAsync());
var requestId = runDoc.RootElement.GetProperty("requestId").GetInt32();

string status;
do
{
        var statusResp = await http.GetAsync(
                $"https://testapi.suretax.com/suretax-reporting/api/Reports/{requestId}/status?api-version=1.0");
        statusResp.EnsureSuccessStatusCode();
        var statusDoc = JsonDocument.Parse(await statusResp.Content.ReadAsStringAsync());
        status = statusDoc.RootElement.GetProperty("status").GetString()!;
        if (status != "Completed" && status != "CompletedWithNoData" && status != "Failed")
                await Task.Delay(TimeSpan.FromSeconds(5));
}
while (status != "Completed" && status != "CompletedWithNoData" && status != "Failed");

var downloadResp = await http.GetAsync(
        $"https://testapi.suretax.com/suretax-reporting/api/Reports/{requestId}/download?api-version=1.0",
        HttpCompletionOption.ResponseHeadersRead);
downloadResp.EnsureSuccessStatusCode();

await using var file = File.Create($"report-{requestId}.csv");
await downloadResp.Content.CopyToAsync(file);

🔑 Key Points

  • Always run first, then poll — Run Report is asynchronous and returns requestId; it does not return report bytes directly.
  • Use terminal statuses — Stop polling only when status is Completed, CompletedWithNoData, or Failed.
  • Download only after Completed — Downloading too early can return 404 Not Found by design.
  • Treat X-Validation-Key as sensitive — Never log or persist this credential in plaintext.

How It Fits the Workflow

Transactions → Calculation → Batch Upload → Returns Generation → Report Extraction → Analysis & Audit

Report extracts close the loop on the compliance lifecycle by providing the data you need to verify filed returns, reconcile tax liability across jurisdictions, prepare for audits, and feed downstream financial systems. By scheduling reports to run automatically after each filing period, you can build a fully automated compliance data pipeline from transaction ingestion through audit-ready reporting.

SSO Integration

SureTax supports Single Sign-On (SSO) integration using the OpenID Connect (OIDC) protocol, enabling your users to access the SureTax Portal seamlessly using their existing corporate credentials. With SSO enabled, users authenticate once through your organization's Identity Provider (IdP) and are automatically granted access to the SureTax Portal without a second login prompt.

Key Highlights

How It Works

  1. Configure your IdP — Register SureTax as a client application in your Identity Provider and configure the required claims (user email, first name, last name, and optionally account name and org code for auto-provisioning).
  2. Exchange configuration — Provide your Client ID, Client Secret, and OIDC discovery URL to the SureTax implementation team. SureTax provides the Redirect URI and Application Name.
  3. Integrate — Add the SureTax SSO URL to your portal. Users click a "Launch SureTax" link and are seamlessly authenticated via your IdP.
📝 Full SSO Guide
For complete details — including step-by-step configuration, claims tables, provisioning models, security considerations, troubleshooting, and implementation timeline — see the SureTax Portal SSO Integration Guide.

Custom Integrations

For environments not covered by the off-the-shelf connectors — such as proprietary retail systems, custom-built e-commerce platforms, or specialized workflow engines — SureTax provides the APIs and SDKs needed to build a fully custom integration.

  1. Evaluate your requirements — Determine whether you need realtime, batch, or both integration modes.
  2. Review the API documentation — Familiarize yourself with the SureTax Realtime and Batch API specifications, authentication mechanisms, and data models.
  3. Use the SDK where possible — The SDK simplifies common tasks and reduces development effort.
  4. Test in sandbox — Use the SureTax sandbox environment to validate your integration before going live.
  5. Engage support — Wolters Kluwer's integration support team can assist with design reviews, troubleshooting, and best practices.
📝 Note
Custom integrations follow the same API contracts as the off-the-shelf connectors, ensuring consistent behavior and support.

Summary

SureTax for General Sales and Use Tax provides a comprehensive, automated tax compliance solution purpose-built for multi-jurisdiction sales tax compliance. Delivered as a complete bundle — including SureTax Calculations, SureTax Returns, General Merchandise Content, SureTax ECM, and Compliance Reports — it eliminates the need to procure individual components.

Integration PathBest For
Off-the-Shelf ConnectorsOrganizations using a supported ERP or e-commerce platform (Acumatica, BigCommerce, Dynamics 365, Magento, NetSuite, Salesforce Commerce Cloud, SAP, WooCommerce, etc.)
SureTax Realtime API / SDKPoint-of-sale, e-commerce checkouts, and real-time transactional systems
SureTax BatchHigh-volume, periodic processing (monthly sales cycles, bulk adjustments)
Custom IntegrationProprietary systems, specialized workflows, or multi-modal requirements
SSOCentralized portal access using corporate identity providers

For questions, implementation support, or to get started with SureTax for General Sales and Use Tax, contact your Wolters Kluwer account representative.