Alibaba Cloud Visual Intelligence API authenticates every HTTP and HTTPS request to ensure its integrity and security. This prevents data tampering and forgery. The service uses symmetric encryption with an AccessKey ID and an AccessKey secret to authenticate the requester's identity from the signature. The AccessKey ID identifies the requester. The AccessKey secret is the key used to encrypt the signature string and for the server to authenticate the signature. You must keep your AccessKey secret confidential.
If you have questions about API access, interface usage, or the visual AI capabilities in different categories of the Visual Intelligence API, you can contact us by joining the Alibaba Cloud Visual Intelligence API consultation DingTalk group (23109592).
Signature process
Specify the request parameters.
You must specify the request parameters in your code. The parameters must include common request headers and the required API parameters.
NoteThe request parameters cannot include a parameter with the `Signature` key.
The following is the sample code:
// To create an AccessKey ID and AccessKey secret, see https://help.aliyun.com/document_detail/175144.html // If you use the AccessKey of a Resource Access Management (RAM) user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html // Read the AccessKey ID and AccessKey secret from environment variables. Before you run the sample code, you must configure the environment variables. String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// You must set the time zone to GMT. java.util.Map<String, String> params = new java.util.HashMap<String, String>();Specify the parameters:
params.put("SignatureMethod", "HMAC-SHA1"); params.put("SignatureNonce", java.util.UUID.randomUUID().toString()); params.put("AccessKeyId", accessKeyId); params.put("SignatureVersion", "1.0"); params.put("Timestamp", df.format(new java.util.Date())); params.put("Format", "JSON"); params.put("RegionId", "cn-shanghai"); // The API version is related to the category. For the API version of a specific category, see https://help.aliyun.com/document_detail/464194.html params.put("Version", "2019-09-30"); // The API action is the capability name. For the Action parameter, see the product page of the specific algorithm. This example uses image super resolution: https://help.aliyun.com/document_detail/151947.html params.put("Action", "MakeSuperResolutionImage"); // The following are business parameters. Business parameters are all request parameters in the specific algorithm document except for the Action parameter. // Note: When you use the signing mechanism to make a call, file parameters currently only support OSS URLs in the China (Shanghai) region. You can store files in OSS in the China (Shanghai) region. For more information, see https://help.aliyun.com/document_detail/175142.html. For other cases, such as local files or other URLs, you must first explicitly transform them into OSS URLs in the China (Shanghai) region. For more information, see Method 2 in https://help.aliyun.com/document_detail/155645.html. However, this solution does not support direct calls from a web frontend environment. params.put("Url", "http://viapi-demo.oss-cn-shanghai.aliyuncs.com/viapi-demo/images/MakeSuperResolution/sup-dog.png"); // For array fields, you must replace N in the parameter with a specific consecutive number starting from 1. For example, to input two images for the Tasks.N.ImageURL parameter, use the following: // params.put("Tasks.1.ImageURL", "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectLivingFace/DetectLivingFace11.jpg"); // params.put("Tasks.2.ImageURL", "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectLivingFace/DetectLivingFace13.jpg");Signature Keyword Removal:
if (paras.containsKey("Signature")) { paras.remove("Signature"); }Sort the parameters by key in ascending order.
The following code provides an example:
java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>(); sortParas.putAll(paras);Construct the string to be signed.
This step uses a special URL encoding method. This is a special rule for the POP protocol that requires the following three character replacements after standard URL encoding:
Replace the plus sign (
+) with%20.Replace the asterisk (
*) with%2A.Replace the tilde (
~) with%7E.
The following is a code sample:
public static String specialUrlEncode(String value) throws Exception { return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("~", "%7E"); }Then, construct the string to be signed by concatenating the sorted parameters in the following format:
"&" + specialUrlEncode(parameterKey) + "=" + specialUrlEncode(parameterValue)The following is a code sample:
java.util.Iterator<String> it = sortParas.keySet().iterator(); StringBuilder sortQueryStringTmp = new StringBuilder(); while (it.hasNext()) { String key = it.next(); sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(paras.get(key))); } String sortedQueryString = sortQueryStringTmp.substring(1);// Remove the extra ampersand (&) at the beginning.The following code shows the result of printing the `sortQueryString`.
AccessKeyId=yourAccessId&Action=MakeSuperResolutionImage&Format=JSON&RegionId=cn-shanghai&SignatureMethod=HMAC-SHA1&SignatureNonce=4a816d44-6186-4f7e-a45f-ba1b3ed73aed&SignatureVersion=1.0&Timestamp=2019-12-07T13%3A28%3A52Z&Url=http%3A%2F%2Fviapi-demo.oss-cn-shanghai.aliyuncs.com%2Fviapi-demo%2Fimages%2FMakeSuperResolution%2Fsup-dog.png&Version=2019-09-30For comparison, the following code shows the corresponding value before URL encoding:
AccessKeyId=yourAccessId&Action=MakeSuperResolutionImage&Format=JSON&RegionId=cn-shanghai&SignatureMethod=HMAC-SHA1&SignatureNonce=4a816d44-6186-4f7e-a45f-ba1b3ed73aed&SignatureVersion=1.0&Timestamp=2019-12-07T13:28:52Z&Url=http://viapi-demo.oss-cn-shanghai.aliyuncs.com/viapi-demo/images/MakeSuperResolution/sup-dog.png&Version=2019-09-30Concatenate the parts into the final string to be signed according to the POP signing rules. The format is as follows:
HTTPMethod + “&” + specialUrlEncode(“/”) + ”&” + specialUrlEncode(sortedQueryString)The following is the sample code:
StringBuilder stringToSign = new StringBuilder(); stringToSign.append("POST").append("&"); stringToSign.append(specialUrlEncode("/")).append("&"); stringToSign.append(specialUrlEncode(sortedQueryString));The query string in the request to be signed is now complete. The result is as follows:
POST&%2F&AccessKeyId%3DyourAccessId&Action%3DMakeSuperResolutionImage&Format%3DJSON&RegionId%3Dcn-shanghai&SignatureMethod%3DHMAC-SHA1&SignatureNonce%3D4a816d44-6186-4f7e-a45f-ba1b3ed73aed&SignatureVersion%3D1.0&Timestamp%3D2019-12-07T13%253A28%253A52Z&Url%3Dhttp%253A%252F%252Fviapi-demo.oss-cn-shanghai.aliyuncs.com%252Fviapi-demo%252Fimages%252FMakeSuperResolution%252Fsup-dog.png&Version%3D2019-09-30Sign the string.
Sign the string using the HmacSHA1 algorithm and Base64. Use UTF-8 for encoding. Encrypt the string with your AccessKey secret. The following sample code shows how to sign the string:
String sign = sign(accessSecret + "&", stringToSign.toString()); public static String sign(String accessSecret, String stringToSign) throws Exception { javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1"); mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); return new sun.misc.BASE64Encoder().encode(signData); }Parameter
Description
accessSecret
The AccessKey secret that corresponds to your AccessKey ID.
NotePOP requires an ampersand (&) to be appended to the end, which is `accessSecret + "&"`.
stringToSign
The string to be signed that was generated in Step 3.
The following is the signed result:
poMnQhB2W5xndjcsW5VZjSdkvnU=Add the signature result to the request parameters and send the request.
String Signature = specialUrlEncode(sign);// poMnQhB2W5xndjcsW5VZjSdkvnU%3DNoteThe signature must also be URL-encoded based on the special rules.
The complete POST request is as follows:
http://imageenhan.cn-shanghai.aliyuncs.com/?Signature=poMnQhB2W5xndjcsW5VZjSdkvnU%3D&AccessKeyId=yourAccessId&Action=MakeSuperResolutionImage&Format=JSON&RegionId=cn-shanghai&SignatureMethod=HMAC-SHA1&SignatureNonce=4a816d44-6186-4f7e-a45f-ba1b3ed73aed&SignatureVersion=1.0&Timestamp=2019-12-07T13%3A28%3A52Z&Url=http%3A%2F%2Fviapi-demo.oss-cn-shanghai.aliyuncs.com%2Fviapi-demo%2Fimages%2FMakeSuperResolution%2Fsup-dog.png&Version=2019-09-30Note`imageenhan.cn-shanghai.aliyuncs.com` is the endpoint for image enhancement. Endpoints vary by service category. For more information about the API endpoint of a specific category, see Endpoints.
Java examples
Example with simple parameters
The following code provides a complete Java example of how to sign a request that uses the `MakeSuperResolutionImage` action for image super resolution.
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SignDemo {
// Use the POST method.
static final String API_HTTP_METHOD = "POST";
// The API endpoint is related to the category. For the API endpoint of a specific category, see https://help.aliyun.com/document_detail/143103.html
static final String API_ENDPOINT = "imageenhan.cn-shanghai.aliyuncs.com";
// The API version is related to the category. For the API version of a specific category, see https://help.aliyun.com/document_detail/464194.html
static final String API_VERSION = "2019-09-30";
static final java.text.SimpleDateFormat DF = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public static void main(String[] args) throws Exception {
// To create an AccessKey ID and AccessKey secret, see https://help.aliyun.com/document_detail/175144.html
// If you use the AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html
// Read the AccessKey ID and AccessKey secret from environment variables. Before you run the sample code, you must configure the environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessSecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// You must set the time zone to GMT.
// Business parameter names are in UpperCamelCase.
Map<String, String> params = new HashMap<>();
// Note: When you use the signing mechanism to make a call, file parameters currently only support OSS URLs in the China (Shanghai) region. You can store files in OSS in the China (Shanghai) region. For more information, see https://help.aliyun.com/document_detail/175142.html. For other cases, such as local files or other URLs, you must first explicitly transform them into OSS URLs in the China (Shanghai) region. For more information, see Method 2 in https://help.aliyun.com/document_detail/155645.html. However, this solution does not support direct calls from a web frontend environment.
params.put("Url", "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageenhan/MakeSuperResolutionImage/MakeSuperResolutionImage1.png");
// The API action is the capability name. For the Action parameter, see the product page of the specific algorithm. This example uses image super resolution: https://help.aliyun.com/document_detail/151947.html
String action = "MakeSuperResolutionImage";
execute(action, accessKeyId, accessSecret, params);
}
public static void execute(String action, String accessKeyId, String accessSecret, Map<String, String> bizParams) throws Exception {
java.util.Map<String, String> params = new java.util.HashMap<String, String>();
// 1. System parameters
params.put("SignatureMethod", "HMAC-SHA1");
params.put("SignatureNonce", java.util.UUID.randomUUID().toString());// Prevents replay attacks.
params.put("AccessKeyId", accessKeyId);
params.put("SignatureVersion", "1.0");
params.put("Timestamp", DF.format(new java.util.Date()));
params.put("Format", "JSON");
// 2. Business API parameters
params.put("RegionId", "cn-shanghai");
params.put("Version", API_VERSION);
params.put("Action", action);
if (bizParams != null && !bizParams.isEmpty()) {
params.putAll(bizParams);
}
// 3. Remove the signature keyword key
if (params.containsKey("Signature")) {
params.remove("Signature");
}
// 4. Sort the parameters by key
java.util.TreeMap<String, String> sortParams = new java.util.TreeMap<String, String>();
sortParams.putAll(params);
// 5. Construct the string to be signed
java.util.Iterator<String> it = sortParams.keySet().iterator();
StringBuilder sortQueryStringTmp = new StringBuilder();
while (it.hasNext()) {
String key = it.next();
sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(params.get(key)));
}
String sortedQueryString = sortQueryStringTmp.substring(1);// Remove the extra ampersand (&) at the beginning.
StringBuilder stringToSign = new StringBuilder();
stringToSign.append(API_HTTP_METHOD).append("&");
stringToSign.append(specialUrlEncode("/")).append("&");
stringToSign.append(specialUrlEncode(sortedQueryString));
String sign = sign(accessSecret + "&", stringToSign.toString());
// 6. The signature must also be specially URL-encoded at the end.
String signature = specialUrlEncode(sign);
System.out.println(params.get("SignatureNonce"));
System.out.println("\r\n=========\r\n");
System.out.println(params.get("Timestamp"));
System.out.println("\r\n=========\r\n");
System.out.println(sortedQueryString);
System.out.println("\r\n=========\r\n");
System.out.println(stringToSign.toString());
System.out.println("\r\n=========\r\n");
System.out.println(sign);
System.out.println("\r\n=========\r\n");
System.out.println(signature);
System.out.println("\r\n=========\r\n");
// The final valid request URL is generated.
System.out.println("http://" + API_ENDPOINT + "/?Signature=" + signature + sortQueryStringTmp);
// Add a method to directly make a POST request.
try {
// Create a POST request using the generated URL.
URIBuilder builder = new URIBuilder("http://" + API_ENDPOINT + "/?Signature=" + signature + sortQueryStringTmp);
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String specialUrlEncode(String value) throws Exception {
return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
}
public static String sign(String accessSecret, String stringToSign) throws Exception {
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
return new sun.misc.BASE64Encoder().encode(signData);
}
} Example with array parameters
The following code provides a complete Java example of how to sign a request that uses the `DetectLivingFace` action for face liveness detection.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class SignDemo {
// Use the POST method.
static final String API_HTTP_METHOD = "POST";
// The API endpoint is related to the category. For the API endpoint of a specific category, see https://help.aliyun.com/document_detail/143103.html
static final String API_ENDPOINT = "facebody.cn-shanghai.aliyuncs.com";
// The API version is related to the category. For the API version of a specific category, see https://help.aliyun.com/document_detail/464194.html
static final String API_VERSION = "2019-12-30";
static final java.text.SimpleDateFormat DF = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public static void main(String[] args) throws Exception {
// To create an AccessKey ID and AccessKey secret, see https://help.aliyun.com/document_detail/175144.html
// If you use the AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html
// Read the AccessKey ID and AccessKey secret from environment variables. Before you run the sample code, you must configure the environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessSecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// You must set the time zone to GMT.
// Business parameter names are in UpperCamelCase.
Map<String, String> params = new HashMap<>();
// Note: When you use the signing mechanism to make a call, file parameters currently only support OSS URLs in the China (Shanghai) region. You can store files in OSS in the China (Shanghai) region. For more information, see https://help.aliyun.com/document_detail/175142.html. For other cases, such as local files or other URLs, you must first explicitly transform them into OSS URLs in the China (Shanghai) region. For more information, see Method 2 in https://help.aliyun.com/document_detail/155645.html. However, this solution does not support direct calls from a web frontend environment.
// For array fields, you must replace N in the parameter with a specific consecutive number starting from 1. For example, to input two images for the Tasks.N.ImageURL parameter, use the following:
params.put("Tasks.1.ImageURL", "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectLivingFace/DetectLivingFace11.jpg");
params.put("Tasks.2.ImageURL", "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectLivingFace/DetectLivingFace13.jpg");
// The API action is the capability name. For the Action parameter, see the product page of the specific algorithm. This example uses face liveness detection: https://help.aliyun.com/document_detail/151947.html
String action = "DetectLivingFace";
execute(action, accessKeyId, accessSecret, params);
}
public static void execute(String action, String accessKeyId, String accessSecret, Map<String, String> bizParams) throws Exception {
java.util.Map<String, String> params = new java.util.HashMap<String, String>();
// 1. System parameters
params.put("SignatureMethod", "HMAC-SHA1");
params.put("SignatureNonce", java.util.UUID.randomUUID().toString());// Prevents replay attacks.
params.put("AccessKeyId", accessKeyId);
params.put("SignatureVersion", "1.0");
params.put("Timestamp", DF.format(new java.util.Date()));
params.put("Format", "JSON");
// 2. Business API parameters
params.put("RegionId", "cn-shanghai");
params.put("Version", API_VERSION);
params.put("Action", action);
if (bizParams != null && !bizParams.isEmpty()) {
params.putAll(bizParams);
}
// 3. Remove the signature keyword key
if (params.containsKey("Signature")) {
params.remove("Signature");
}
// 4. Sort the parameters by key
java.util.TreeMap<String, String> sortParams = new java.util.TreeMap<String, String>();
sortParams.putAll(params);
// 5. Construct the string to be signed
java.util.Iterator<String> it = sortParams.keySet().iterator();
StringBuilder sortQueryStringTmp = new StringBuilder();
while (it.hasNext()) {
String key = it.next();
sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(params.get(key)));
}
String sortedQueryString = sortQueryStringTmp.substring(1);// Remove the extra ampersand (&) at the beginning.
StringBuilder stringToSign = new StringBuilder();
stringToSign.append(API_HTTP_METHOD).append("&");
stringToSign.append(specialUrlEncode("/")).append("&");
stringToSign.append(specialUrlEncode(sortedQueryString));
String sign = sign(accessSecret + "&", stringToSign.toString());
// 6. The signature must also be specially URL-encoded at the end.
String signature = specialUrlEncode(sign);
System.out.println(params.get("SignatureNonce"));
System.out.println("\r\n=========\r\n");
System.out.println(params.get("Timestamp"));
System.out.println("\r\n=========\r\n");
System.out.println(sortedQueryString);
System.out.println("\r\n=========\r\n");
System.out.println(stringToSign.toString());
System.out.println("\r\n=========\r\n");
System.out.println(sign);
System.out.println("\r\n=========\r\n");
System.out.println(signature);
System.out.println("\r\n=========\r\n");
// The final valid request URL is generated.
System.out.println("http://" + API_ENDPOINT + "/?Signature=" + signature + sortQueryStringTmp);
// Add a method to directly make a POST request.
try {
// Create a POST request using the generated URL.
URIBuilder builder = new URIBuilder("http://" + API_ENDPOINT + "/?Signature=" + signature + sortQueryStringTmp);
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String specialUrlEncode(String value) throws Exception {
return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
}
public static String sign(String accessSecret, String stringToSign) throws Exception {
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
return new sun.misc.BASE64Encoder().encode(signData);
}
} PHP examples
Example with simple parameters
The following code provides a complete PHP example of how to sign a request that uses the `MakeSuperResolutionImage` action for image super resolution.
<?php
date_default_timezone_set("GMT");// You must set the time zone to GMT.
class SignDemo
{
// Use the POST method.
const API_HTTP_METHOD = "POST";
// The API endpoint is related to the category. For the API endpoint of a specific category, see https://help.aliyun.com/document_detail/143103.html
const API_ENDPOINT = "imageenhan.cn-shanghai.aliyuncs.com";
// The API version is related to the category. For the API version of a specific category, see https://help.aliyun.com/document_detail/464194.html
const API_VERSION = "2019-09-30";
const DF = "Y-m-d\TH:i:s\Z";
private $accessKeyId;
private $accessSecret;
public function __construct($accessKeyId, $accessSecret) {
$this->accessKeyId = $accessKeyId;
$this->accessSecret = $accessSecret;
}
public function execute($action, $bizParams) {
$params = array(
// 1. System parameters
"SignatureMethod" => "HMAC-SHA1",
"SignatureNonce" => uniqid(),
"AccessKeyId" => $this->accessKeyId,
"SignatureVersion" => "1.0",
"Timestamp" => gmdate(self::DF),
"Format" => "JSON",
// 2. Business API parameters
"RegionId" => "cn-shanghai",
"Version" => self::API_VERSION,
"Action" => $action
);
if (!empty($bizParams)) {
$params = array_merge($params, $bizParams);
}
unset($params["Signature"]);
ksort($params);
// 3. Construct the string to be signed
$sortedQueryStringTmp = "";
foreach ($params as $key => $value) {
$sortedQueryStringTmp .= "&" . $this->specialUrlEncode($key) . "=" . $this->specialUrlEncode($value);
}
$sortedQueryString = substr($sortedQueryStringTmp, 1);// Remove the extra ampersand (&) at the beginning.
// 4. The signature must also be specially URL-encoded at the end.
$stringToSign = self::API_HTTP_METHOD . "&" . $this->specialUrlEncode("/") . "&" . $this->specialUrlEncode($sortedQueryString);
$signature = $this->specialUrlEncode($this->sign($this->accessSecret . "&", $stringToSign));
// 5. The final valid request URL is generated.
$requestUrl = "http://" . self::API_ENDPOINT . "/?Signature=" . $signature . $sortedQueryStringTmp;
echo $requestUrl . "\n";
try {
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'ignore_errors' => true,
)
));
$response = file_get_contents($requestUrl, false, $context);
echo $response;
} catch (Exception $e) {
echo $e->getMessage();
}
}
private function specialUrlEncode($value) {
return str_replace(array("+", "*", "%7E"), array("%20", "%2A", "~"), rawurlencode($value));
}
private function sign($accessSecret, $stringToSign) {
return base64_encode(hash_hmac("sha1", $stringToSign, $accessSecret, true));
}
}
// Business parameter names are in UpperCamelCase.
// Note: When you use the signing mechanism to make a call, file parameters currently only support OSS URLs in the China (Shanghai) region. You can store files in OSS in the China (Shanghai) region. For more information, see https://help.aliyun.com/document_detail/175142.html. For other cases, such as local files or other URLs, you must first explicitly transform them into OSS URLs in the China (Shanghai) region. For more information, see Method 2 in https://help.aliyun.com/document_detail/155645.html. However, this solution does not support direct calls from a web frontend environment.
$bizParams = array("Url" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageenhan/MakeSuperResolutionImage/MakeSuperResolutionImage1.png");
// The API action is the capability name. For the Action parameter, see the product page of the specific algorithm. This example uses image super resolution: https://help.aliyun.com/document_detail/151947.html
$action = "MakeSuperResolutionImage";
// To create an AccessKey ID and AccessKey secret, see https://help.aliyun.com/document_detail/175144.html
// If you use the AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html
// Read the AccessKey ID and AccessKey secret from environment variables. Before you run the sample code, you must configure the environment variables.
$signDemo = new SignDemo(getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'));
$signDemo->execute($action, $bizParams);
?>