Skip to main content

User Guide

Service Management

Create Service

To create a service through the AnyService console, you need to configure the following basic information:

Basic Configuration

ItemDescriptionRequirement
Service NameDisplay NameFor easy identification and management
Service IdentifierThe unique identifier of the serviceOnly letters, digits, and underscores are allowed. Must be unique within the environment.
RemarksService descriptionOptional, used to record the service purpose
Origin TypeAccess method for backend servicesPublic network access origin or Tencent Cloud resources

Public Network Access Origin Configuration

When you choose to access the origin via public network, you need to configure the following:

ItemDescriptionExample
Origin ProtocolHTTP or HTTPSDefault ports: HTTP(80), HTTPS(443)
Origin Connection InformationIP Address or Domain Name139.186.239.126 or tcb.tencentcloudapi.com:8080

alt

Tencent Cloud Resource Configuration

When you choose to connect to Tencent Cloud resources, you need to configure the following:

ItemDescriptionSupported Range
ResourceSelect specific cloud resource instancesCVM, CLB, Lighthouse in Shanghai region
PortService listening port1-65535

alt

Security Configuration (Optional)

ItemDescriptionNotes
Origin Access CredentialsBasic Auth authentication informationComplies with the Authorization Basic specification

How it works: Once configured, each request adds an x-anyservice-authorization field in the Header, which the origin server can use for authentication or request source identification.

⚠️ Security Notice: When using the HTTP protocol, access credentials will be transmitted in plain text. It is recommended to use HTTPS in production environments.

Managing Services

In the service list, you can view and manage created services:

OperationDescriptionNotes
View DetailsView the service's configuration information and running status-
Edit ServiceModify all configurations except the identifierService identifier cannot be modified
Delete ServicePermanently delete the service and its configurationsEnsure no code dependencies before deletion

⚠️ Important Notice: Modifying or deleting services may affect applications that are using the service. Please carefully assess the impact scope before performing these operations.

Service Invocation

Invoking in Mini Programs

1. Initialize the CloudBase environment

Call the initialization once during the Mini Program loading phase; it only needs to be executed once globally:

// app.js - Global Initialization
App({
async onLaunch() {
// Initialize the CloudBase environment
wx.cloud.init({
env: "your-env-id" // Replace with your environment ID
})
}
})

2. Invoke the AnyService Service

Use the wx.cloud.callContainer method to invoke the AnyService service:

// Invoke Example
const callAnyService = async () => {
try {
const res = await wx.cloud.callContainer({
path: '/api/users', // Backend API path
method: 'POST', // HTTP method
header: {
"X-WX-SERVICE": "tcbanyservice", // Fixed value
"X-AnyService-Name": "my-service", // Your service identifier
"Content-Type": "application/json"
},
data: {
name: 'Zhang San',
email: 'zhangsan@example.com'
}
// dataType: 'text' // Optional: Use when you do not want the SDK to automatically parse JSON
})

console.log('Call succeeded:', res.data)
return res.data
} catch (error) {
console.error('Call failed:', error)
throw error
}
}

Key Parameter Description

ParameterValueDescription
X-WX-SERVICEtcbanyserviceFixed value that identifies the AnyService call
X-AnyService-NameYour service identifierIdentifier set when creating the service
path/api/pathBackend API path, starting from the root directory
methodGET/POST/PUT/DELETEHTTP request method
dataTypejson (default) / textResponse data parsing method

Error Handling and Best Practices

Common Error Handling

const callAnyService = async (path, data = {}) => {
try {
const res = await wx.cloud.callContainer({
path,
method: 'POST',
header: {
"X-WX-SERVICE": "tcbanyservice",
"X-AnyService-Name": "my-service",
"Content-Type": "application/json"
},
data,
timeout: 10000 // Set the timeout
})

return res.data
} catch (error) {
// Handle different types of errors
if (error.errCode === -1) {
console.error('Network request failed:', error.errMsg)
wx.showToast({ title: 'Network connection failed', icon: 'none' })
} else if (error.errCode === 40001) {
console.error('Service not found:', error.errMsg)
wx.showToast({ title: 'Service temporarily unavailable', icon: 'none' })
} else {
console.error('Call failed:', error)
wx.showToast({ title: 'Request failed, please try again', icon: 'none' })
}
throw error
}
}

Best Practice Recommendations

  1. Request Encapsulation: It is recommended to encapsulate AnyService calls into a generic function.
  2. Error Handling: Provide corresponding user prompts for different error types.
  3. Timeout Settings: Set a reasonable timeout period for network requests.
  4. State Management: Display loading status during the call process.
  5. Retry Mechanism: Retry logic can be implemented for transient errors.

📝 Note: Other parameters are consistent with wx.request.

Request and Response Data

Request Header

When calling services through the SDK, the system automatically carries Mini Program-related information in the HTTP Header. The backend can parse these headers to obtain user and environment information:

Header FieldMeaningDescription
X-WX-OPENIDMini Program user openidUnique user identifier
X-WX-APPIDMini Program AppIDMini Program application identifier
X-WX-UNIONIDMini Program user unionidCross-application user identifier (subject to acquisition conditions)
X-WX-FROM-OPENIDUser openid in resource reuse scenariosOriginal user identifier during resource reuse
X-WX-FROM-APPIDMini Program AppID in resource reuse scenariosOriginal application identifier during resource reuse
X-WX-FROM-UNIONIDUser unionid in resource reuse scenariosOriginal user cross-application identifier during resource reuse
X-WX-ENVCloudBase environment IDThe CloudBase environment where the current call is located
X-WX-SOURCECall sourceThe source type that triggered this call
X-WX-PLATFORMCalling platformPlatform information that initiated the call
X-Forwarded-ForClient IP addressSupports IPv4 and IPv6
X-AnyService-NameAnyService service identifierService identifier for the current call

Response Header

AnyService adds the following Header fields in the response for debugging and monitoring:

Header FieldMeaningDescription
X-Cloudbase-Request-IdCloudBase request IDUsed for issue tracking and log queries
X-Cloudbase-Upstream-Status-CodeUpstream response status codeThe actual HTTP status code returned by the backend service
X-Cloudbase-Upstream-TimecostUpstream response timeTime taken by the backend service to process the request (in milliseconds)
X-Cloudbase-Upstream-TypeUpstream service typeType identifier of the backend service