Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Tencentcloud Sdk Php Laravel Package

tencentcloud/tencentcloud-sdk-php

Official Tencent Cloud SDK for PHP, giving PHP applications programmatic access to Tencent Cloud services such as CVM, COS, and more. Install via Composer, configure your credentials, and call APIs with built-in request signing and error handling.

Deep Wiki
Context7

Getting Started

Install and first call. The SDK is a single Composer package that ships every Tencent Cloud service:

composer require tencentcloud/tencentcloud-sdk-php

The only entry point you need is the three-part client construction: Credential → ClientProfile/HttpProfile → service client. A working CVM call is ~15 lines:

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Cvm\V20170312\CvmClient;
use TencentCloud\Cvm\V20170312\Models\DescribeInstancesRequest;

$cred = new Credential(env('TC_SECRET_ID'), env('TC_SECRET_KEY'));
$http = (new HttpProfile())->setEndpoint('cvm.tencentcloudapi.com')->setReqTimeout(15);
$client = new CvmClient($cred, 'ap-guangzhou', (new ClientProfile())->setHttpProfile($http));

$req = new DescribeInstancesRequest();
$req->fromJsonString(json_encode(['Limit' => 10]));
echo $client->DescribeInstances($req)->toJsonString();

Where to look first. Don't read the SDK source top-down — it's tens of thousands of generated model classes. Instead:

  1. Find the API in the Tencent Cloud API Explorer — it generates the exact PHP snippet with the correct namespace, version (V20170312), endpoint, and region.
  2. Map that to vendor/tencentcloud/tencentcloud-sdk-php/src/TencentCloud/<Service>/<Version>/ — you only need XxxClient.php and the handful of Models/*Request.php classes in your call path.
  3. Models/*.php are plain DTOs: constructor-arg-free, populated via setters or fromJsonString(), read via getXxx().

First real use case. The lowest-friction wins are stateless, single-call APIs: SMS (SmsClient::SendSms), CDN cache purging, DNS record updates, or a DescribeInstances health check. Pick one of those to validate credentials, region, and the TC3-HMAC-SHA256 signing handshake before wiring anything stateful.

Implementation Patterns

Client factory in the container. Never new CvmClient(...) at call sites. Bind a factory that reads credentials/region/timeouts from config/services.php, memoizes per service+region, and returns the typed client:

// app/Services/Tencent/CloudFactory.php
public function cvm(string $region = null): CvmClient { /* memoized */ }

Register it as a singleton in a TencentCloudServiceProvider. This gives you one place to swap credentials for STS tokens, flip regions, or inject a fake transport in tests.

Array-in / array-out at the boundary. The SDK's object graph leaks into your domain if you let it. Wrap each capability in a small service class that accepts a plain array, calls fromJsonString(json_encode($input)), and returns json_decode($response->toJsonString(), true). Everything downstream (Eloquent, queues, HTTP resources) then deals in arrays, and the SDK never escapes app/Services/Tencent.

Validation before the wire. Because of the silent-drop behaviour described below, validate user/API input against an explicit allow-list of SDK parameter names (PascalCase, e.g. InstanceIds, Filters) before encoding. A Laravel FormRequest or a typed DTO per request is worth the boilerplate.

Error handling as a decorator. All failures throw TencentCloud\Common\Exception\TencentCloudSDKException. Wrap calls in a single helper that:

try {
    return $this->factory->cvm($region)->DescribeInstances($req);
} catch (TencentCloudSDKException $e) {
    Log::warning('tc.api.error', [
        'code' => $e->getErrorCode(),
        'request_id' => $e->getRequestId(),
        'message' => $e->getMessage(),
    ]);
    throw match (true) {
        str_contains($e->getErrorCode() ?? '', 'RequestLimitExceeded'),
        str_contains($e->getErrorCode() ?? '', 'InternalError') => new RetryableCloudException(previous: $e),
        str_contains($e->getErrorCode() ?? '', 'AuthFailure'),
        str_contains($e->getErrorCode() ?? '', 'UnauthorizedOperation') => new CloudAuthException(previous: $e),
        default => new CloudException(previous: $e),
    };
}

RequestId is the single most useful field for support tickets — always log it.

Queue + retry for anything mutating or slow. The SDK is synchronous with no built-in retry. Push create/delete/scale operations onto a queue job with $tries = 5 and exponential backoff ([1, 5, 30, 60, 120]) limited to the retryable codes above. Never retry AuthFailure or InvalidParameter; you'll just burn quota.

Idempotency via ClientToken. For create-type APIs (run instance, create load balancer, create order), pass a stable ClientToken derived from your own domain identifier (e.g. "order-{$order->id}-run"). This is the only protection against double-creation when a request times out after the server accepted it.

Pagination strategy. Two shapes dominate: Offset/Limit + TotalCount (CVM, CLB, most list APIs) and NextToken/Marker (newer APIs like TAT, TCR). Write one driver per shape rather than a universal one; a LazyCollection wrapping the client call composes beautifully with Laravel pipelines:

foreach ($this->paginate(fn ($offset) => $this->describe($offset, 100)) as $instance) { ... }

Long-running operations. RunInstances returns IDs, not ready instances. Model this explicitly: store the returned ID, then either poll DescribeInstances with backoff in a job, or subscribe to the corresponding event via Tencent Cloud's message queue/EventBridge and handle it as a webhook.

Testing. Subclass the concrete client and override the action method to return a fixture built from (new DescribeInstancesResponse())->fromJsonString($json). That's cheaper and more faithful than mocking HTTP, and it exercises your real response-parsing code.

Gotchas and Tips

The monolith is a deployment cost. One package contains every service and version in Tencent Cloud. composer install is slow, vendor/ grows by tens of MB, and --optimize-autoloader becomes noticeably expensive. Mitigations: keep the package in require (not require-dev), generate the optimized classmap in your build pipeline rather than on deploy, and consider scoping the autoloader. Don't attempt to prune directories manually — you'll break on the next composer update.

fromJsonString() silently drops unknown keys. If you typo InstanceId as InstanceID, nothing throws; you get a request with that parameter absent and either a validation error for a different field or, worse, a default-valued call that succeeds. Symptom to watch for: API rejects with "MissingParameter" for a key you're certain you passed. Diff your array keys against the Models/*Request.php setters.

Always set the endpoint explicitly. HttpProfile::setEndpoint() should be set from the API Explorer value (cvm.tencentcloudapi.com). Relying on defaults is fragile across SDK versions and breaks entirely for global services and non-standard domains.

Region is not optional and is not global. Most services require a real region (ap-guangzhou, ap-singapore, na-ashburn). Some are global and conventionally take ap-guangzhou or an empty string; using the wrong region produces AuthFailure.UnauthorizedOperation-style errors that look like permission problems but are region problems. Verify against the console's region selector for that product.

PHP 8 / dynamic properties. This is generated code from an older era; running it on PHP 8.2+ can surface deprecation notices. error_reporting(E_ALL) in a strict CI job will be noisy. Filter deprecations from vendor/tencentcloud in your error handler rather than globally lowering error_reporting.

The package metadata looks stale. The listed last release (2018-07-02) predates most current API versions present in the tree, which strongly suggests the registry entry lagged the repo. Pin an explicit version in composer.json and verify the installed version has the API version directory you need (V20170312, V20201016, etc.) — if the class isn't there, you're on an old tag, not using the wrong namespace.

No async, no connection pooling. Each call is a blocking cURL round trip. Ten sequential calls at 300 ms each is a second of response time. Batch in a queue job, use the batch variants of APIs where offered (e.g. SMS SendStatusBatch-style endpoints, tag operations), and consider curl_multi-free parallelism only via multiple queued workers.

Timeout tuning is per-HttpProfile. Default ReqTimeout can be too long for web requests. Set setConnTimeout(3) and setReqTimeout(10–30) depending on the operation, and keep separate profiles for "interactive" vs "batch" calls in your factory.

Temporary credentials need the token. STS/CAM-role credentials are a three-argument Credential($id, $key, $token). Forgetting the third argument yields AuthFailure.SignatureFailure, which reads like a bad secret key and sends you down the wrong rabbit hole. Refresh before expiry and rebuild the client — memoized clients will happily keep using an expired token.

Binary and oversized payloads. Parameters expecting binary (face images, OCR documents) generally want base64. SDK size limits per API are enforced server-side with InvalidParameterValue; check the per-API doc, and base64-encode before fromJsonString, not after.

Debugging the wire. There's no verbose flag on the client. To see what's actually sent, log your JSON input before fromJsonString, log $response->toJsonString() after, and correlate with the RequestId from the exception. The SDK embeds a bundled HTTP client rather than depending on Guzzle, so Guzzle middleware/telescope-style instrumentation won't see these requests — add your own timing/log wrapper around the service class.

Extension point: swap the transport. The clients accept an injected HTTP client, which is the cleanest seam for a fake in tests or for adding retry/metrics middleware. If you need per-request tracing, that's the place — not subclassing every service client.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels