We recommend that you use an SDK on your application server to call Vision Intelligence Open Platform APIs. Embedding your AccessKeyId and AccessKeySecret in a client-side application creates a security risk. To mitigate this risk, you can use Security Token Service (STS) to authorize users to call the service.
Background
Before calling APIs from a mini program, you must obtain a temporary access credential from Security Token Service (STS). STS allows you to issue credentials that grant users access to Vision Intelligence Open Platform services for a limited time. Because these credentials do not expose your long-term keys, they enhance your account security. To learn how to obtain a temporary access credential, see Obtain temporary credentials for a role.
-
If your file is stored in an Object Storage Service (OSS) bucket in China (Shanghai):
You must use a request signature to call the API. For specific instructions, see Scenario 1: File in Shanghai OSS. For more information about OSS operations, see Activate OSS.
-
If your file is stored locally or at another URL:
You must first convert the file into an OSS link in China (Shanghai). For instructions, see File URL processing. For specific instructions, see Scenario 2: Local file or URL.
For help with API integration, usage, or other issues, contact us in our Vision Intelligence Open Platform DingTalk group (23109592).
Scenario 1: File in Shanghai OSS
If your file is stored in an OSS bucket in China (Shanghai), you can call the API by using a request signature. This topic uses the RecognizeBankCard API as an example and shows only the key steps and code. For a complete example, download the MiniprogramDemo. If you need to call other algorithms, refer to the comments and modify the code accordingly.
Interaction flow
Prerequisites
Obtain an STS temporary access credential:
-
Grant permissions:
Before obtaining an STS temporary access credential, the caller (a RAM user or RAM role) must be authorized to call STS operations. You can grant these permissions by using a RAM policy. For the setup steps and required policies, see Use an STS temporary access credential to access OSS. We recommend that you configure fine-grained authorization policies to avoid granting excessive permissions. For more information, see Custom policies for Vision Intelligence Open Platform.
ImportantFor the following steps, the caller (a RAM user or RAM role) must have the AliyunSTSAssumeRoleAccess permission (to call the STS AssumeRole operation) and the AliyunVIAPIFullAccess permission. The AliyunVIAPIFullAccess permission grants full management access to Vision Intelligence Open Platform APIs. For this example, we use this broad permission for simplicity. However, in a production environment, we highly recommend configuring more fine-grained authorization policies to mitigate security risks. For more information, see Custom policies for Vision Intelligence Open Platform.
-
Call the AssumeRole operation:
Use the authorized RAM user or RAM role to call the AssumeRole operation and provide the required parameters. For detailed information about the operation and its parameters, see the official AssumeRole documentation.
-
Use the STS token:
After successfully calling the AssumeRole operation, you receive an STS token that includes an
AccessKeyId, anAccessKeySecret, and aSecurityToken, as shown in the code sample below. When you call other Alibaba Cloud service APIs, you must replace placeholders in your code, such as<ALIBABA_CLOUD_ACCESS_KEY_ID>,<ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and<ALIBABA_CLOUD_SECURITY_TOKEN>, with the temporaryAccessKeyId,AccessKeySecret, andSecurityTokenfrom the STS token.
{
"RequestId": "429D9967-C809-5A30-B65E-9B742CF*****",
"AssumedRoleUser": {
"Arn": "acs:ram::175805416243****:role/STStokenTestRole/STSsessionName",
"AssumedRoleId": "39779315882322****:STSsessionName"
},
"Credentials": {
"SecurityToken": "exampleToken",
"AccessKeyId": "STS.exampleAccessKeyID",
"AccessKeySecret": "exampleAccessKeySecret",
"Expiration": "2024-06-12T03:21:29Z"
}
}
Step 1: Configure basic parameters
The following code snippet, located in the utils/client.js file of the MiniprogramDemo, shows how to call the Alibaba Cloud RecognizeBankCard service.
-
Parameters:
-
miniProgramType: The type of the mini program that is making the call. Possible values arewx(WeChat),my(Alipay), ordd(DingTalk). Pass these as variables, not as string literals. -
callback: A callback function that receives the request result after the HTTP request completes.
-
-
Alibaba Cloud credentials:
-
The
accessKeyId,accessKeySecret, andsecurityTokenare security credentials provided by Alibaba Cloud. In this code, you must replace the<ALIBABA_CLOUD_ACCESS_KEY_ID>,<ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and<ALIBABA_CLOUD_SECURITY_TOKEN>placeholders with the temporary credentials provided by STS.
-
-
API endpoint and parameters:
-
endpoint: The API endpoint for the Alibaba Cloud OCR service. For bank card recognition, the endpoint isocr.cn-shanghai.aliyuncs.com. -
Action: The name of the specific API operation to request. In this example, it isRecognizeBankCard. -
API_HTTP_METHOD: The recommended HTTP method. Here, it isPOST. -
API_VERSION: A string that specifies the API version, which indicates the release date of the Alibaba Cloud API you are using.
-
-
Build the request:
-
The code first sets a series of system parameters, including the signature method, AccessKeyId, signature version, and timestamp.
-
The
SecurityTokenis obtained from STS and must be included in the request. -
The business parameter
ImageURLis the URL of the bank card image to be recognized.
-
-
Make the API request:
-
Call the
callApiRequestfunction, passing the mini program type, system parameters, HTTP method, API endpoint, and a callback function. Use the callback function to handle the API response.
-
For example, if you want to use the general segmentation feature, the SegmentCommonImage API documentation shows that this feature belongs to the segmentation and matting category (imageseg20191230) and its operation name is SegmentCommonImage. Change the endpoint to imageseg.cn-shanghai.aliyuncs.com (note that this domain must be added to the mini program's allowlist), change the Action to SegmentCommonImage, and keep the API_VERSION as 2019-12-30. The parameter for the image URL is still named ImageURL. When you retrieve the result, you get an ImageURL, which is the URL of the segmented image, not a bank card number.
Before running the code, import the CryptoJS package to calculate the signature. For more information, see the CryptoJS Package Download Address and CDN Address. For details on the signature calculation logic, see Request signature.
npm install crypto-js
/**
* ========================================================================================================================
* This is an example for RecognizeBankCard.
* Replace <ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> with the temporary
* AccessKeyId, AccessKeySecret, and SecurityToken obtained from Alibaba Cloud STS.
* To call the RecognizeBankCard API, see https://www.alibabacloud.com/help/en/vision-intelligence/latest/recognizebankcard
* ========================================================================================================================
*/
// Description of parameters:
// miniProgramType: The type of the mini program. For example, pass wx for WeChat, my for Alipay, or dd for DingTalk. Do not pass these as strings.
// callback: A callback function for the result.
function callRecognizeBankCard(miniProgramType, callback) {
/**
Replace <ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> with the temporary
AccessKeyId, AccessKeySecret, and SecurityToken obtained from the STS token data.
You must grant the AliyunVIAPIFullAccess permission to the RAM user or RAM role. For more information, see https://www.alibabacloud.com/help/en/ram/user-guide/create-a-custom-policy
*/
//AccessKeyId
const accessKeyId = "<ALIBABA_CLOUD_ACCESS_KEY_ID>";
//AccessKeySecret
const accessKeySecret = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>";
//SecurityToken
const securityToken = "<ALIBABA_CLOUD_SECURITY_TOKEN>";
// The endpoint is the API endpoint, which is category-specific. For API endpoints of different categories, see: https://www.alibabacloud.com/help/en/vision-intelligence/latest/endpoints
const endpoint = "ocr.cn-shanghai.aliyuncs.com";
// API Action, which is the feature name. Refer to the Action parameter in the specific algorithm's documentation. This example uses RecognizeBankCard: https://www.alibabacloud.com/help/en/vision-intelligence/latest/recognizebankcard
const Action = "RecognizeBankCard";
// The recommended API_HTTP_METHOD is POST.
const API_HTTP_METHOD = "POST";
// API_VERSION is the API version, which is category-specific. For API versions of different categories, see: https://www.alibabacloud.com/help/en/vision-intelligence/latest/api-version
const API_VERSION = "2019-12-30";
const request_ = {};
//System parameters
request_["SignatureMethod"] = "HMAC-SHA1",
request_["SignatureNonce"] = signNRandom(),
request_["AccessKeyId"] = accessKeyId,
request_["SignatureVersion"] = "1.0",
request_["Timestamp"] = getTimestamp(),
request_["Format"] = "JSON",
request_["RegionId"] = "cn-shanghai",
request_["Version"] = API_VERSION,
request_["Action"] = Action;
request_["SecurityToken"] = securityToken;
// Business parameters. Modify these according to the specific AI feature's API documentation.
request_["ImageURL"] = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk3.jpg";
callApiRequest(miniProgramType, request_, API_HTTP_METHOD, endpoint, accessKeySecret, callback);
}
Step 2: Call API and calculate signature
The following code snippet implements the signing and request sending process for the Vision Intelligence Open Platform API. Signing is a common security measure for cloud services. It ensures that requests are not tampered with and originate from an authenticated user. For more information about the logic, see Request signature.
-
Generate a nonce and a timestamp:
-
signNRandom: Generates a random number to be used as a nonce for the signature. -
getTimestamp: Generates the current UTC timestamp, formatted as an ISO 8601 compliant string. -
pad2: Formats the time to ensure that the month, day, hour, minute, and second are all two-digit numbers.
-
-
Signature calculation helper functions:
-
ksort: Sorts the keys of the request parameters object in lexicographical order. This is a step in constructing the canonicalized request string. -
createHmac: Hashes a string using HMAC-SHA1 with a specified key and encodes the result as a Base64 string. This is a key step in the signing process. -
encode: URL-encodes a string and handles some special characters to comply with signature encoding requirements.
-
-
Signature and request string generation:
-
sha1: A wrapper function for HMAC-SHA1 signing of a string. -
getSignature: Calculates the API request signature based on the request parameters, HTTP method, and AccessKeySecret. -
objToParam: Converts a key-value pair object into a URL query string. -
toQueryPair: Converts a single key-value pair into a part of a URL query string.
-
-
Generate the final request URL:
-
generateUrl: Generates the final, signed API request URL based on the HTTP request method, API endpoint, request parameters object, and AccessKeySecret.
-
-
Module export:
-
The
callRecognizeBankCardmethod is exported viamodule.exports, allowing it to be imported and used in other JavaScript files.
-
Step 3: Encapsulate and send the request
The following code snippet provides a basic framework for making an API request and handling the callback in a mini program.
-
Construct the URL: Use the
generateUrlfunction to generate the complete API request URL, including the signature, based on the provided parameters. -
Make the request: Call
miniProgramType.requestand pass a configuration object that includes:-
url: The complete API request URL. -
method: The request method, hardcoded as"POST"here. -
header: Specifies the request headers. For example,Content-Type: application/json.
-
-
Handle a successful response: If the request is successful, the
successcallback is invoked, and the result is passed to the externally providedcallbackfunction. -
Handle a failed response: If the request fails, the
failcallback is invoked, and the error information is passed to the externally providedcallbackfunction.
Step 4: Call the API service
The following code snippet shows how to call the Alibaba Cloud Vision Intelligence Open Platform's bank card recognition service from a mini program and handle the response.
-
Import the client module: Import the custom
clientmodule from theutilsdirectory. This module likely contains the methods for calling Alibaba Cloud APIs. -
Define the page logic: Use the mini program's
Pagemethod to define the page's data and logic. The initial page data includes the bank card number (cardNumber) and an error message (errorMessage). -
Implement the API call: Define the
callApimethod within the page logic. This method uses theclientmodule to make a call to the Alibaba Cloud bank card recognition API. -
Handle the API response: In the
callApimethod, a callback function handles the API response. If an error is detected, the corresponding error message is displayed. If the call is successful, the recognized bank card number is displayed. -
Update page data: Use the
setDatamethod to update the page data based on the API response, displaying either the bank card number or an error message.
Step 5: Configure the request-valid domain name
When making API requests from a mini program, configure the server domain name. Different AI categories have different endpoints. For more information, see Endpoints.
The following example shows how to configure the request-valid domain name for a WeChat mini program. On the Server Domain Name page in the WeChat Mini Program admin console, find the request-valid domain name configuration item, click Modify, and add the corresponding endpoint.
In a WeChat mini program, you must replace <your appid> in the code with your actual app ID.
Scenario 2: Local file or URL
If your file is stored locally or at an accessible URL, you must first explicitly convert it into an OSS link in China (Shanghai) by following the instructions in File URL processing. Then, make the API call as described in Scenario 1: File in Shanghai OSS. This topic uses the RecognizeBankCard API as an example and shows only the key steps and code. For a complete example, download the MiniprogramDemo. If you need to call other algorithms, refer to the comments and modify the code accordingly.
Interaction flow
Prerequisites
Obtain an STS temporary access credential:
-
Grant permissions:
Before obtaining an STS temporary access credential, the caller (a RAM user or RAM role) must be authorized to call STS operations. You can grant these permissions by using a RAM policy. For the setup steps, see Use an STS temporary access credential to access OSS. We recommend that you configure fine-grained authorization policies to avoid granting excessive permissions. For more information, see Custom policies for Vision Intelligence Open Platform.
ImportantFor the following steps, the caller (a RAM user or RAM role) needs the following permissions: AliyunSTSAssumeRoleAccess (to call the STS AssumeRole operation), permissions to upload files to OSS (see Grant a RAM role permissions to upload files to OSS), and AliyunVIAPIFullAccess. The AliyunVIAPIFullAccess permission grants full management access to Vision Intelligence Open Platform APIs. For this example, we use this broad permission for simplicity. However, you should configure more fine-grained authorization policies to mitigate security risks. For more information, see Custom policies for Vision Intelligence Open Platform.
-
Call the AssumeRole operation:
Use the authorized RAM user or RAM role to call the AssumeRole operation and provide the required parameters. For detailed information about the operation and its parameters, see the official AssumeRole documentation.
-
Use the STS token:
After successfully calling the AssumeRole operation, you receive an STS token that includes an AccessKeyId, an AccessKeySecret, and a SecurityToken, as shown in the code sample below. When you call other Alibaba Cloud service APIs, you must replace placeholders in your code, such as
<ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN>, with the temporaryAccessKeyId, AccessKeySecret, and SecurityTokenfrom the STS token.
{
"RequestId": "429D9967-C809-5A30-B65E-9B742CF*****",
"AssumedRoleUser": {
"Arn": "acs:ram::175805416243****:role/STStokenTestRole/STSsessionName",
"AssumedRoleId": "39779315882322****:STSsessionName"
},
"Credentials": {
"SecurityToken": "exampleToken",
"AccessKeyId": "STS.exampleAccessKeyID",
"AccessKeySecret": "exampleAccessKeySecret",
"Expiration": "2024-06-12T03:21:29Z"
}
}
Step 1: Configure basic parameters
The following code snippet, located in the utils/client.js file of the MiniprogramDemo, shows how to call the Alibaba Cloud RecognizeBankCard service. You must replace placeholders in your code, such as <ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN>, with the temporary AccessKeyId, AccessKeySecret, and SecurityToken from the Alibaba Cloud STS token.
The temporary credentials here are for calling the Vision Intelligence Open Platform API, which protects your long-term keys from client-side exposure. The STS token from Step 2 serves a different purpose: it grants temporary access to upload a file to an OSS bucket.
/**
* For information on how to obtain an Alibaba Cloud STS token, see https://www.alibabacloud.com/help/en/oss/developer-reference/use-temporary-access-credentials-provided-by-sts-to-access-oss
* Replace <ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> with the temporary
* AccessKeyId, AccessKeySecret, and SecurityToken obtained from the Alibaba Cloud STS token data.
* You must grant the AliyunVIAPIFullAccess permission to the RAM user or RAM role. For more information, see https://www.alibabacloud.com/help/en/ram/user-guide/create-a-custom-policy
*/
//AccessKeyID
const accessKeyId = "YOUR_ACCESS_KEY_ID";
//AccessKeySecret
const accessKeySecret = "YOUR_ACCESS_KEY_SECRET";
// miniProgramType: The type of the mini program. For example, pass wx for WeChat, my for Alipay, or dd for DingTalk. Do not pass these as strings.
const miniProgramType = wx;
//SecurityToken
const securityToken = "<ALIBABA_CLOUD_SECURITY_TOKEN>";
Step 2: Get a temporary OSS STS token
The getOssStsToken function retrieves temporary credentials for uploading files to OSS. It calls the generic callApi utility, which constructs and signs a request to the Alibaba Cloud API. callApi handles system parameters like SignatureNonce (to prevent replay attacks) and the timestamp, then uses callApiRequest to send the final request.
Step 3: Upload the file to OSS
The code snippet below shows how to upload a file to Alibaba Cloud OSS and call any Alibaba Cloud API service from a mini program (such as WeChat, Alipay, or DingTalk).
uploadToTempOss function:
-
Generate form data for the upload: Call the
getFormDataParamsfunction to get the form data, including the signature, policy, and security token. -
Construct the upload path: Create a storage path for the file in OSS, combining the user's AccessKeyId, a random string, and the file name.
-
Upload the file using the mini program API: Send the upload request using the mini program's
uploadFileinterface, including the generated form data and file path. -
Handle the upload result: If the upload is successful (based on the response status code), return the complete URL of the file. If it fails, print an error message.
callApiRequest function:
-
Generate a signed request URL: Use the
generateUrlfunction to sign the request parameters and get the complete request URL. -
Make the API request: Send the request to the Alibaba Cloud API service using the mini program's
requestinterface. -
Handle the API response: Call the provided callback function to process the returned result, whether it is a successful response or an error.
For more information, see the client-side signature section for obtaining an STS temporary account and generating a signature in the OSS Direct upload to OSS from a WeChat mini program documentation.
For Alipay or DingTalk mini programs, change name: 'file', in the code to fileName: 'file', fileType: 'image',. For more information, see the client-side signature section in the OSS Direct upload to OSS from an Alipay mini program documentation.
Step 4: Call the API with the OSS URL
The following code snippet shows how to get the OSS URL after an upload and then call the Vision Intelligence Open Platform API. The procedure is the same as calling the API as described in Scenario 1: File in Shanghai OSS. The code for each step is encapsulated. For the complete sample code, download the MiniprogramDemo.
-
Prepare the parameters for the API call:
-
Endpoint: The API endpoint, which is
ocr.cn-shanghai.aliyuncs.com. -
Action: The API operation name, which is
RecognizeBankCard, indicating the bank card recognition service. -
API Version: The API version, which is
2019-12-30. -
Ensure that you grant the necessary permissions to the RAM user or RAM role to call the Vision Intelligence Open Platform API. See Grant permissions in the prerequisites section.
-
-
Construct the request parameters object:
The
request_object contains the system parameters required for the API call (such as signature method, timestamp, and format) and the business parameters (in this case, theImageURLof the bank card image to be recognized). -
Make the API request:
The encapsulated
callApifunction is called, passing the prepared request parameters, API endpoint, and a callback function. The callback function is used to handle the API response.
In the utils/client.js file, the endpoint, Action, API_VERSION, and request_["ImageURL"] parameters in the callRecognizeBankCard function are business-specific. For example, if you want to use the general segmentation feature, the SegmentCommonImage documentation shows that this feature belongs to the segmentation and matting category (imageseg20191230) and its operation name is SegmentCommonImage. Change the endpoint to imageseg.cn-shanghai.aliyuncs.com (note that this domain must be added to the mini program's allowlist), change the Action to SegmentCommonImage, and keep the API_VERSION as 2019-12-30. The name of the parameter in request_["ImageURL"] is still ImageURL. When you retrieve the result, you will get an ImageURL, which in this case is the address of the segmented image, not a bank card number.
Step 5: Configure the request-valid domain name
When making API requests from a mini program, configure the server domain name. Different AI categories have different endpoints. For more information, see Endpoints.
The following example shows how to configure the request-valid domain name for a WeChat mini program.