# **步骤1:微信小程序配置域名白名单**
您可以为微信小程序配置域名白名单,以实现微信小程序和OSS Bucket之间的正常通信。
1. 登录[OSS管理控制台]([https://oss.console.aliyun.com/)](https://oss.console.aliyun.com/))。
2. 单击 **Bucket 列表** ,然后单击目标Bucket名称。
3. 在Bucket内的左侧导航栏,单击 **概览** ,然后在**访问端口**区域查看 **Bucket域名** 。
登录微信小程序平台,将上传和下载的合法域名填写为Bucket的外网访问域名。

# 步骤2:微信小程序上传代码
```
请将脸部正对红色显示框内,并保持光线充足
拍摄有反光
动作过快
掺杂多余动作
```
# 步骤3:后台接口代码
```
package com.qfant.common.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
public class OssUtil {
/**
*/
private static String accessKeyId = "";
private static String accessSecret = "";
/**
* cdn 鉴权URL 主key
*/
private static String cdn_oss_a_main_key = "Rv*******Yv";
/**
* CDN站点的域名。---> ***-*** Bucket
*/
private static String cdn_oss_domain = "https://*****.[aliyuncs.com](https://aliyuncs.com/)";
private static String oss_endpoint_domain = "*****.[aliyuncs.com](https://aliyuncs.com/)";
public static AssumeRoleResponse.Credentials getCredentials() {
return getCredentials(accessKeyId, accessSecret);
}
public static AssumeRoleResponse.Credentials getCredentials(String accessKeyId, String accessSecret) {
//构建一个阿里云客户端,用于发起请求。
//设置调用者(RAM用户或RAM角色)的AccessKey ID和AccessKey Secret。
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
IAcsClient client = new DefaultAcsClient(profile);
//构造请求,设置参数。关于参数含义和设置方法,请参见《API参考》。
AssumeRoleRequest request = new AssumeRoleRequest();
request.setRegionId("cn-hangzhou");
request.setRoleArn("acs:ram::1080088734231229:role/ramosstest");
request.setRoleSessionName("RamOssTest");
//发起请求,并得到响应。
try {
AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println(new Gson().toJson(response));
return response.getCredentials();
} catch (ClientException e) {
System.out.println("ErrCode:" + e.getErrCode());
System.out.println("ErrMsg:" + e.getErrMsg());
System.out.println("RequestId:" + e.getRequestId());
}
return null;
}
public static Map wxUploadSignature() {
String accessId = accessKeyId; // 请填写您的AccessKeyId。
String accessKey = accessSecret; // 请填写您的AccessKeySecret。
String endpoint = oss_endpoint_domain; // 请填写您的 endpoint。
String host = "https://" + endpoint; // host的格式为 bucketname.endpoint
// callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
String dir = "record/"; // 用户上传文件时指定的前缀。
Map
respMap = new LinkedHashMap();
OSSClient client = new OSSClient(endpoint, accessId, accessKey);
try {
long expireTime = 30000;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = client.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = client.calculatePostSignature(postPolicy);
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
// System.out.println("accessId : " + accessId);
// System.out.println("policy : " + encodedPolicy);
// System.out.println("signature : " + postSignature);
// System.out.println("host : " + host);
// System.out.println("expire : " + String.valueOf(expireEndTime / 1000));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return respMap;
}
/**
* 获取CDN 鉴权URL
* 鉴权方式A加密URL构成
* [http://DomainName/Filename?auth_key={-rand-uid-}](http://domainname/Filename?auth_key={%3Ctimestamp%3E-rand-uid-%3Cmd5hash%3E})
* [https://help.aliyun.com/document_detail/85113.html?spm=a2c4g.85116.0.i3#concept-oxj-wrm-j2b](https://help.aliyun.com/document_detail/85113.html?spm=a2c4g.85116.0.i3#concept-oxj-wrm-j2b)
*
* sstring = "URI-Timestamp-rand-uid-PrivateKey"(URI是用户的请求对象相对地址,不包含参数,如/Filename)
* md5hash = md5sum(sstring)
*
* @param filename
* @return
*/
public static String createCDNAuthUrl(String filename) {
if (filename.startsWith("/")) {
filename = filename.substring(1);
}
String URI = "/" + filename;
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String rand = UUID.randomUUID().toString().replace("-", "");
String uid = "0";
StringBuilder sstring = new StringBuilder(URI).append("-").append(timestamp).append("-").append(rand).append("-").append(uid).append("-").append(cdn_oss_a_main_key);
String md5hash = Md5Utils.MD5(sstring.toString());
String url = String.format("%s/%s?auth_key=%s-%s-%s-%s", cdn_oss_domain, filename, timestamp, rand, uid, md5hash);
return url;
}
public static String uploadFile() throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "[https://oss-cn-hangzhou.aliyuncs.com](https://oss-cn-hangzhou.aliyuncs.com/)";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
// 填写Bucket名称,例如examplebucket。
String bucketName = "***-***";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = System.currentTimeMillis() + "_1.png";
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath = "C:\\Users\\***\\Pictures\\1.png";
String fileUrl = "https://********.[aliyuncs.com/"](https://aliyuncs.com/%22) + objectName;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessSecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
System.out.println(fileUrl);
return fileUrl;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
}
```