### Go Server: Get Temporary STS Token for OCR Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Server-side Go example to obtain temporary security credentials using Tencent Cloud STS GetFederationToken. It reads fixed keys from environment variables for security. The policy restricts access to OCR services only. ```go // server/GetFederationToken.go package main import ( "fmt" "os" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions" sts "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sts/v20180813" ) func main() { // 从环境变量读取密钥,避免硬编码 credential := common.NewCredential( os.Getenv("secretId"), os.Getenv("secretKey"), ) cpf := profile.NewClientProfile() client, _ := sts.NewClient(credential, regions.Guangzhou, cpf) request := sts.NewGetFederationTokenRequest() // 设置请求参数:名称、有效期、OCR 授权策略 err := request.FromJsonString(`{ "Name": "ocr", "DurationSeconds": 1800, "Policy": "{\"version\":\"2.0\",\"statement\":[{\"action\":[\"ocr:*\"],\"resource\":\"*\",\"effect\":\"allow\"}]}" }`) if err != nil { panic(err) } response, err := client.GetFederationToken(request) if _, ok := err.(*errors.TencentCloudSDKError); ok { fmt.Printf("API 错误: %s\n", err) return } if err != nil { panic(err) } // 打印完整响应(含 TmpSecretId、TmpSecretKey、Token、ExpiredTime) fmt.Printf("%s\n", response.ToJsonString()) // 预期输出: // {"Credentials":{"Token":"xxxTmpToken","TmpSecretId":"AKIDxxxTmpId","TmpSecretKey":"xxxTmpKey"}, // "ExpiredTime":1695221362,"Expiration":"2023-09-20T10:02:42Z","RequestId":"xxx"} } ``` -------------------------------- ### Temporary Key Exchange Response Example Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This JSON object illustrates the structure of a successful response when requesting temporary security credentials. It includes expiration details and the temporary credentials themselves. ```json { "ExpiredTime": 1595221362, "Expiration": "2020-07-20T05:02:42Z", "Credentials": { "Token": "临时Token", "TmpSecretId": "临时TmpSecretId", "TmpSecretKey": "临时TmpSecretKey" }, "RequestId": "返回的RequestId" } ``` -------------------------------- ### STS: GetFederationToken Input Example Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This XML snippet shows an example input URL for the GetFederationToken action of the STS API. It includes parameters like Action, Name, Policy, and DurationSeconds for requesting temporary credentials. ```xml https://sts.tencentcloudapi.com/?Action=GetFederationToken &Name=ocr &Policy=请求入参 &DurationSeconds=120 ``` -------------------------------- ### Node.js Server: Get Temporary STS Token for OCR Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Server-side Node.js example to obtain temporary security credentials (TmpSecretId, TmpSecretKey, Token) using Tencent Cloud STS GetFederationToken. This is the recommended approach for production environments. The policy grants only 'ocr:*' permissions. ```javascript // server/GetFederationToken.js const tencentcloud = require("tencentcloud-sdk-nodejs"); const StsClient = tencentcloud.sts.v20180813.Client; const models = tencentcloud.sts.v20180813.Models; const Credential = tencentcloud.common.Credential; // 使用服务器端安全存储的固定密钥初始化认证对象 let cred = new Credential("AKIDxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx"); let client = new StsClient(cred, "ap-guangzhou"); // 构造获取临时密钥的请求,Policy 仅授权 OCR 服务 let req = new models.GetFederationTokenRequest({ "Name": "ocr", "DurationSeconds": 1800, // 临时密钥有效期(秒),最长 7200 "Policy": JSON.stringify({ "version": "2.0", "statement": [{ "action": ["ocr:*"], "resource": "*", "effect": "allow" }] }) }); client.GetFederationToken(req, function(err, response) { if (err) { console.error("获取临时密钥失败:", err); return; } // 将以下字段下发给客户端 const { TmpSecretId, TmpSecretKey, Token } = response.Credentials; console.log("TmpSecretId:", TmpSecretId); console.log("TmpSecretKey:", TmpSecretKey); console.log("Token:", Token); console.log("过期时间(Unix):", response.ExpiredTime); // 预期输出示例: // TmpSecretId: AKIDxxxxxxxxTmpSecretId // TmpSecretKey: xxxxxxxxTmpSecretKey // Token: xxxxxxxxTemporaryToken // 过期时间(Unix): 1695221362 }); ``` -------------------------------- ### Get Temporary Credentials (JavaScript) Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md Frontend function to request temporary credentials from your server. Ensure your server endpoint is correctly configured to interact with the CAM service. ```javascript const axios = require('axios') // 必选参数 async function getAuthorization (options, callback) { try{ let res = await axios({ method: 'post', url: '您服务器端的接口地址', // 填写您服务器端的接口地址,获取临时密钥 data: {options} }) let credentials = res.Credentials if (!res || !credentials) return console.error('credentials invalid') callback({ TmpSecretId: credentials.TmpSecretId, TmpSecretKey: credentials.TmpSecretKey, Token: credentials.Token, ExpiredTime: res.ExpiredTime, // 临时证书有效的时间,返回 Unix 时间戳,精确到秒 Expiration: res.Expiration, // 证书有效的时间,以 iso8601 格式的 UTC 时间表示 RequestId: res.RequestId }) }catch (err) { return console.error(`${err} error occurs`) } } ``` -------------------------------- ### Get Temporary Credentials for OCR (JavaScript - Mini Program) Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt This JavaScript function demonstrates how a WeChat Mini Program can obtain temporary security credentials for OCR recognition. It makes an asynchronous POST request to a business server, which in turn fetches credentials from Tencent Cloud STS. The obtained credentials are then passed back to the caller via a callback function. ```APIDOC ## getAuthorization (JavaScript - Mini Program) ### Description Obtains temporary security credentials required for OCR recognition. This function is designed for use within WeChat Mini Programs, where it communicates with a business server to retrieve credentials from Tencent Cloud STS. ### Parameters - **options** (Object) - Optional. Custom request parameters (e.g., device information, version number). - **callback** (Function) - Required. A callback function that receives the temporary credentials object upon successful retrieval. ### Request Example ```javascript // miniprogram/utils/auth.js const axios = require('axios'); async function getAuthorization(options, callback) { try { const res = await axios({ method: 'post', url: 'https://your-server.com/api/getTmpToken', // Business server address data: { options } }); const credentials = res.Credentials; if (!res || !credentials) { return console.error('Temporary credentials are invalid. Please check the server response.'); } callback({ TmpSecretId: credentials.TmpSecretId, TmpSecretKey: credentials.TmpSecretKey, Token: credentials.Token, ExpiredTime: res.ExpiredTime, // Unix timestamp (seconds) Expiration: res.Expiration, // ISO8601 format UTC time RequestId: res.RequestId }); } catch (err) { console.error(`Failed to get temporary credentials: ${err}`); } } module.exports = { getAuthorization }; ``` ### Response Example (Callback Data) ```json { "TmpSecretId": "AKIDxxxTmpSecretId", "TmpSecretKey": "xxxTmpSecretKey", "Token": "xxxTemporaryToken", "ExpiredTime": 1695221362, // Unix timestamp (seconds) "Expiration": "2023-09-20T10:02:42Z", // ISO8601 format UTC time "RequestId": "xxx-request-id" } ``` ``` -------------------------------- ### iOS: Get Temporary Token Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This Objective-C code demonstrates how to request and obtain temporary security credentials (Token, TmpSecretId, TmpSecretKey) from a server endpoint. It includes AES encryption for request parameters and decryption for the response. ```objective-c ///获取临时秘钥方法 - (void) doUpdateTmpToken { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"]; NSMutableDictionary *param = [NSMutableDictionary dictionary]; NSString *sdkVersion = [[OcrSDKKit sharedInstance] sdkVersion]; [param setObject:sdkVersion forKey:@"sdkVersion"]; [param setObject:[self currentDateStr] forKey:@"Timestamp"]; [param setObject:[[UIDevice currentDevice] name] forKey:@"Model"]; [param setObject:[[UIDevice currentDevice] systemVersion] forKey:@"OSVersion"]; [param setObject:[self uuidString] forKey:@"uuid"]; NSString *request = [JsonUtil convertToJsonData:param]; /// AES 传参加密 NSString *encodeRequest = [AesUtil AES128EncryptWithContent:request Key:ENCODE_KEY iv:ENCODE_IV]; [param removeAllObjects]; [param setObject:encodeRequest forKey:@"request"]; [manager POST:POST_URL parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"%@",responseObject); NSNumber *stateCode = [responseObject objectForKey:@"statusCode"]; NSString *message = [responseObject objectForKey:@"message"]; if ([stateCode longValue] != 0) { NSLog(@"net err %@",message); } NSString *data = [responseObject objectForKey:@"data"]; /// AES 解密 NSString *content = [AesUtil AES128DecryptWithContent:data Key:DECODE_KEY iv:DECODE_IV]; NSDictionary *resultDict = [JsonUtil dictionaryWithJsonString:content]; NSDictionary *credentials = [resultDict objectForKey:@"Credentials"]; NSString *tempToken = [credentials objectForKey:@"Token"]; NSString *tmpSecretId = [credentials objectForKey:@"TmpSecretId"]; NSString *tmpSecretKey = [credentials objectForKey:@"TmpSecretKey"]; NSLog(@"tempToken:%@\n tmpSecretId:%@\n tmpSecretKey:%@",tempToken,tmpSecretId,tmpSecretKey); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@",error.userInfo); }]; } ``` -------------------------------- ### Get Temporary Secret Key for WeChat Mini Program (JavaScript) Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Use this JavaScript code within a WeChat Mini Program to asynchronously request temporary secret keys from your business server via axios. The keys are then returned via a callback for subsequent OCR signature calculations. Ensure your business server is correctly configured to provide these credentials. ```javascript // miniprogram/utils/auth.js —— 小程序端获取临时密钥 const axios = require('axios'); /** * 获取 OCR 识别所需的临时密钥 * @param {Object} options 自定义请求参数(如设备信息、版本号等) * @param {Function} callback 回调函数,成功时返回临时密钥对象 */ async function getAuthorization(options, callback) { try { const res = await axios({ method: 'post', url: 'https://your-server.com/api/getTmpToken', // 业务服务器地址 data: { options } }); const credentials = res.Credentials; if (!res || !credentials) { return console.error('临时密钥无效,请检查服务器返回数据'); } // 回调返回临时密钥信息 callback({ TmpSecretId: credentials.TmpSecretId, TmpSecretKey: credentials.TmpSecretKey, Token: credentials.Token, ExpiredTime: res.ExpiredTime, // Unix 时间戳(秒) Expiration: res.Expiration, // ISO8601 格式 UTC 时间 RequestId: res.RequestId }); // 回调对象示例: // { // TmpSecretId: "AKIDxxxTmpSecretId", // TmpSecretKey: "xxxTmpSecretKey", // Token: "xxxTemporaryToken", // ExpiredTime: 1695221362, // Expiration: "2023-09-20T10:02:42Z", // RequestId: "xxx-request-id" // } } catch (err) { console.error(`获取临时密钥失败: ${err}`); } } module.exports = { getAuthorization }; ``` -------------------------------- ### iOS: Fixed Key Declaration Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This Objective-C code declares static NSString variables for storing fixed SecretId and SecretKey on iOS. This is part of the fixed key mode setup for client-side initialization. ```objective-c static NSString *secretId = @"SECRET_ID_iOS"; static NSString *secretKey = @"SECRET_KEY_iOS"; ``` -------------------------------- ### Get Temporary Credentials Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This operation retrieves temporary security credentials. You need to provide your cloud API secret ID and secret key, along with a policy defining the permissions for the temporary credentials. The duration of the credentials can also be specified. ```APIDOC ## Get Temporary Credentials ### Description Retrieves temporary security credentials including a token, temporary secret ID, and temporary secret key. This operation requires your cloud API secret ID and secret key, and allows for specifying a policy and the duration for which the credentials will be valid. ### Method POST (Assumed, as it involves sending credentials and policy) ### Endpoint /path/to/get/temporary/credentials (Assumed) ### Parameters #### Request Body Parameters - **Name** (String) - Required - Custom caller name, should be 'ocr' for this API. - **Policy** (String) - Required - CAM policy defining permissions. Example: `{"version": "2.0", "statement": [{"action": ["ocr:*"], "resource": "*", "effect": "allow"}]}` - **DurationSeconds** (Integer) - Optional - The validity period of the temporary credentials in seconds. Defaults to 1800 seconds, maximum 7200 seconds. - **secretId** (String) - Required - Your cloud API secret ID. - **secretKey** (String) - Required - Your cloud API secret key. ### Request Example ```json { "Name": "ocr", "Policy": "{\"version\": \"2.0\", \"statement\": [{\"action\": [\"ocr:*\"], \"resource\": \"*\", \"effect\": \"allow\"}]}", "DurationSeconds": 3600, "secretId": "YOUR_SECRET_ID", "secretKey": "YOUR_SECRET_KEY" } ``` ### Response #### Success Response (200) - **ExpiredTime** (Integer) - The expiration time of the temporary credentials as a Unix timestamp (seconds). - **Expiration** (String) - The expiration time in ISO 8601 UTC format. May be null. - **RequestId** (String) - A unique ID for the request, used for troubleshooting. - **Credentials** (Object) - Contains the temporary security credentials. - **Token** (String) - The token string required for requests. - **TmpSecretId** (String) - The temporary secret ID, used for signature calculation. - **TmpSecretKey** (String) - The temporary secret key, used for signature calculation. #### Response Example ```json { "ExpiredTime": 1595221362, "Expiration": "2020-07-20T05:02:42Z", "Credentials": { "Token": "临时Token", "TmpSecretId": "临时TmpSecretId", "TmpSecretKey": "临时TmpSecretKey" }, "RequestId": "返回的RequestId" } ``` ``` -------------------------------- ### Get Temporary Secret Key via CAM HTTP Interface (REST) Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt This bash command demonstrates how to directly request temporary secret keys from Tencent Cloud STS service using curl. This method is suitable for any backend language. Ensure the 'Policy' parameter is URL-encoded and the 'Authorization' header is correctly generated using Tencent Cloud's signature v3 algorithm. ```bash # 通过 curl 请求 STS 服务获取 OCR 临时密钥 # Policy 内容(URL 解码前):{"version":"2.0","statement":[{"action":["ocr:*"],"resource":"*","effect":"allow"}]} curl -X GET "https://sts.tencentcloudapi.com/" \ -G \ --data-urlencode "Action=GetFederationToken" \ --data-urlencode "Name=ocr" \ --data-urlencode "DurationSeconds=1800" \ --data-urlencode 'Policy={"version":"2.0","statement":[{"action":["ocr:*"],"resource":"*","effect":"allow"}]}' \ -H "Authorization: TC3-HMAC-SHA256 ..." # 需按腾讯云签名 v3 算法生成 # 成功响应示例: # { # "ExpiredTime": 1695221362, # "Expiration": "2023-09-20T10:02:42Z", # "Credentials": { # "Token": "xxxxxxTemporaryToken", # "TmpSecretId": "AKIDxxxxxxTmpSecretId", # "TmpSecretKey": "xxxxxxTmpSecretKey" # }, # "RequestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # } ``` -------------------------------- ### Obtain Temporary Credentials via STS HTTP API (REST) Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt This section details how to directly request temporary security credentials from Tencent Cloud STS using an HTTP GET request. This method is language-agnostic and suitable for any backend environment. It requires proper URL encoding for the Policy parameter and signature generation using Tencent Cloud's signature v3 algorithm. ```APIDOC ## Get Temporary Credentials via STS HTTP API (REST) ### Description Directly request temporary security credentials from Tencent Cloud STS service via HTTPS. This method is suitable for any backend language. The Policy parameter must be URL-encoded. ### Method GET ### Endpoint `https://sts.tencentcloudapi.com/` ### Parameters #### Query Parameters - **Action** (String) - Required - Must be `GetFederationToken`. - **Name** (String) - Required - Custom caller name. For OCR scenarios, it must be `ocr`. - **DurationSeconds** (Integer) - Optional - Validity period of temporary credentials in seconds. Defaults to 1800, maximum 7200. - **Policy** (String) - Required - CAM authorization policy, granting `ocr:*` permission to all OCR interfaces. Must be URL-encoded. - **secretId** (String) - Required - Tencent Cloud root account API Key ID. - **secretKey** (String) - Required - Tencent Cloud root account API Key. ### Request Example (using curl) ```bash # Policy content (before URL decoding): {"version":"2.0","statement":[{"action":["ocr:*"],"resource":"*","effect":"allow"}]} curl -X GET "https://sts.tencentcloudapi.com/" \ -G \ --data-urlencode "Action=GetFederationToken" \ --data-urlencode "Name=ocr" \ --data-urlencode "DurationSeconds=1800" \ --data-urlencode 'Policy={"version":"2.0","statement":[{"action":["ocr:*"],"resource":"*","effect":"allow"}]}' \ -H "Authorization: TC3-HMAC-SHA256 ..." # Must be generated according to Tencent Cloud signature v3 algorithm ``` ### Response #### Success Response (200) - **ExpiredTime** (Integer) - The expiration time of the temporary credentials as a Unix timestamp (seconds). - **Expiration** (String) - The expiration time in ISO8601 format UTC time. - **Credentials** (Object) - Contains the temporary security credentials. - **Token** (String) - The session token. - **TmpSecretId** (String) - The temporary secret ID. - **TmpSecretKey** (String) - The temporary secret key. - **RequestId** (String) - The ID of the request. #### Response Example ```json { "ExpiredTime": 1695221362, "Expiration": "2023-09-20T10:02:42Z", "Credentials": { "Token": "xxxxxxTemporaryToken", "TmpSecretId": "AKIDxxxxxxTmpSecretId", "TmpSecretKey": "xxxxxxTmpSecretKey" }, "RequestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" } ``` ``` -------------------------------- ### iOS SDK Initialization with Fixed Key Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Initialize the OCR SDK in an iOS project using fixed keys. This method is suitable for demo purposes. Replace with temporary keys for production environments. Ensure OcrSDKKit.framework is imported. ```objectivec // ViewController.m —— iOS 固定密钥初始化示例 #import static NSString *SECRET_ID = @"AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; static NSString *SECRET_KEY = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - (void)initOcrSDK { // 初始化 SDK,传入 SecretId、SecretKey,临时 Token 置空 [[OcrSDKKit sharedInstance] initWithSecretId:SECRET_ID secretKey:SECRET_KEY token:@""]; NSLog(@"SDK 版本: %@", [[OcrSDKKit sharedInstance] sdkVersion]); } ``` -------------------------------- ### Frontend: Initialize OCR Client with Fixed Key Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This JavaScript code shows how to initialize the Tencent Cloud OCR client using fixed SecretId and SecretKey. This method is suitable for frontend debugging but should be used with caution to avoid key leakage. ```javascript const tencentcloud = require("tencentcloud-sdk-nodejs"); // 导入sts产品模块的client models。 const OcrClient = tencentcloud.ocr.v20181119.Client; const models = tencentcloud.ocr.v20181119.Models; const Credential = tencentcloud.common.Credential; // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey let credential = new Credential("secretId", "secretKey"); // 实例化ocr产品的client对象 let client = new OcrClient(credential, "ap-guangzhou"); ``` -------------------------------- ### Android SDK Initialization with Fixed Key Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Initialize the OCR SDK on Android using a fixed key for local development and debugging. Ensure SecretPamera.java is correctly configured. Fixed keys are not recommended for production due to security risks. ```java public class SecretPamera { // 腾讯云控制台获取的 SecretId public final static String secretId = "AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 腾讯云控制台获取的 SecretKey public final static String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; } // 在 Activity 中初始化 OCR SDK(以固定密钥为例) OcrSDKKit.getInstance().init( context, SecretPamera.secretId, SecretPamera.secretKey, "" // 固定密钥模式,token 传空字符串 ); ``` -------------------------------- ### Android: Update SDK with Temporary Keys Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Call `doUpdateTmpToken` to fetch temporary keys from your business server and refresh the OCR SDK. Handles success and error callbacks. ```java TmpTokenHelper.getInstance().doUpdateTmpToken(new TmpTokenHelper.TmpTokenListener() { @Override public void onSuccess(String secretId, String secretKey, String tmpToken) { Log.d("OCR", "临时密钥获取成功"); Log.d("OCR", "TmpSecretId: " + secretId); Log.d("OCR", "TmpSecretKey: " + secretKey); Log.d("OCR", "Token: " + tmpToken); // 将最新临时密钥刷新到 OCR SDK OcrSDKKit.getInstance().updateFederationToken(secretId, secretKey, tmpToken); // 密钥更新后即可发起 OCR 识别请求 // 例如:启动身份证识别界面 // OcrSDKKit.getInstance().startActivityForOcr(activity, OcrType.IDCard, requestCode); } @Override public void onError(int errorCode, String errorMsg) { Log.e("OCR", "临时密钥获取失败 errorCode=" + errorCode + " msg=" + errorMsg); // 建议:errorCode == 0x99 时为解析错误,其余为网络错误,可按需重试 } }); ``` -------------------------------- ### iOS: Update SDK with Temporary Keys using AFNetworking Source: https://context7.com/tencentcloud/tc-ocr-sdk/llms.txt Uses AFNetworking to POST an encrypted request to your business server for temporary keys, then decrypts and updates the OcrSDKKit. Requires AES encryption/decryption utilities. ```objective-c #import "TmpTokenHelper.h" #import #import #import "AesUtil.h" #import "JsonUtil.h" static NSString *POST_URL = @"https://your-server.com/api/getTmpToken"; static NSString *ENCODE_KEY = @"your_encode_key_16"; static NSString *ENCODE_IV = @"your_encode_iv_16"; static NSString *DECODE_KEY = @"your_decode_key_16"; static NSString *DECODE_IV = @"your_decode_iv_16"; - (void)doUpdateTmpToken { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // 构造请求参数并 AES128 加密 NSMutableDictionary *param = [NSMutableDictionary dictionary]; [param setObject:[[OcrSDKKit sharedInstance] sdkVersion] forKey:@"sdkVersion"]; [param setObject:[[UIDevice currentDevice] systemVersion] forKey:@"OSVersion"]; NSString *encodeRequest = [AesUtil AES128EncryptWithContent:[JsonUtil convertToJsonData:param] Key:ENCODE_KEY iv:ENCODE_IV]; [manager POST:POST_URL parameters:@{@"request": encodeRequest} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { // 解密服务器响应 NSString *data = [responseObject objectForKey:@"data"]; NSString *content = [AesUtil AES128DecryptWithContent:data Key:DECODE_KEY iv:DECODE_IV]; NSDictionary *resultDict = [JsonUtil dictionaryWithJsonString:content]; NSDictionary *credentials = [resultDict objectForKey:@"Credentials"]; NSString *token = credentials[@"Token"]; NSString *tmpSecretId = credentials[@"TmpSecretId"]; NSString *tmpSecretKey = credentials[@"TmpSecretKey"]; NSLog(@"临时密钥获取成功 TmpSecretId:%@ Token:%@", tmpSecretId, token); // 刷新 SDK 临时密钥 [[OcrSDKKit sharedInstance] updateFederationToken:tmpSecretId tmpSecretKey:tmpSecretKey token:token]; // 之后可发起 OCR 识别请求 } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"临时密钥获取失败: %@", error.userInfo); }]; } ``` -------------------------------- ### Configure API Keys in Objective-C Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/iOS/README.md Modify the SecretId and SecretKey values in your project with your Tencent Cloud API credentials. This method is only suitable for local demo runs and debugging due to security risks of client-side key exposure. ```objective-c //正式 static NSString *SECRET_ID = @"A**********************"; static NSString *SECRET_KEY = @"e*********************"; ``` -------------------------------- ### Update Temporary Token (Android Java) Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md Android method to exchange temporary keys by sending a request to your server. The server then contacts the CAM service to obtain temporary credentials. ```java /** * 本地测试,兑换临时密钥的方法 * * @param listener 结果监听的listener */ public void doUpdateTmpToken(final TmpTokenListener listener) { if (listener == null) { return; } Thread thread = new Thread(new Runnable() { @Override public void run() { // 您服务器端的接口地址 String url = "您服务器端的接口地址"; // 构造请求参数 try { // 构造您的请求参数,请求参数完全可以按照您的需求传入 String param = crateParam(); // 发送请求到服务端,通知服务端访问CAM服务器去兑换临时密钥。 NetWorkConnectUtil.postToUrl(url, param, new NetWorkConnectUtil.NetWorkListener() { @Override public void onSuccess(String result) { // 处理服务器端的返回结果,并解析结果,更新tmpSecretId, tmpSecretKey, tmpToken的值 if (parseValue(result)) { // 将最新获得的密钥信息,通过回调返回到调用的地方,可在调用处主动刷新临时密钥到SDK listener.onSuccess(tmpSecretId, tmpSecretKey, tmpToken); } else { listener.onError(ERROR_CODE_PARSE, "parseValue error!"); } } @Override public void onError(int errorCode, String errorMsg) { listener.onError(errorCode, errorMsg); } }); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } ``` -------------------------------- ### Configure Secret ID and Key in Android Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/Android/README.md Update the secretId and secretKey in the SecretPamera class with your obtained API credentials. This method is suitable for local demo testing and debugging only, as storing keys directly in the client can lead to security risks. ```java /** * 密钥配置信息 */ public class SecretPamera { public final static String secretId = "您的secretId"; public final static String secretKey = "您的secretKey"; } ``` -------------------------------- ### Android: Fixed Key Storage Source: https://github.com/tencentcloud/tc-ocr-sdk/blob/master/临时密钥兑换/README.md This Java code defines a class to store fixed SecretId and SecretKey for Android applications. It's intended for use with the fixed key mode, where credentials are hardcoded. ```java /** * 固定密钥存放封装类 */ public class SecretPamera { /** * 固定密钥信息 */ public final static String secretId = "SECRET_ID_ANDROID"; /** *固定密钥的key值 */ public final static String secretKey = "SECRET_KEY_ANDROID"; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.