接入授权中心的产品提供方需关注两个事项:
1、将销售产品时涉及的客户、授权载体类型、产品以及产品使用权限信息按照授权中心约定的数据格式传递给授权中心。
2、从授权中心获取许可信息,包括客户信息,产品信息与产品使用权限信息等。
本例以授权业务中最复杂的企业云授权为入门点,讲解产品提供方接入授权中心的方法。
企业云授权通过调用创建企业主帐号API、获取资产编号API和批量创建基本授权订单API完成将销售产品涉及的使用权限信息传递给授权中心的功能,完成产品提供方接入授权中心。

创建应用,获取appkey、appsecret;
获取服务调用token;
开通服务,scope授权通过;
以上步骤可参考前置准备

step1:maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.0</version>
</dependency>
step2:IOStreamUtil工具类
package com.utils;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 提供IO流的一些工具方法
*
* @author liaolh
*/
public final class IOStreamUtil {
private static Logger logger = LoggerFactory.getLogger(IOStreamUtil.class);
private IOStreamUtil() {
}
/**
* 安全关闭IO流
*
* @param stream
*/
public static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException ioe) {
logger.error("Close:", ioe);
}
stream = null;
}
}
/**
* 把流中的数据按照指定的编码一次性读到一个字符串中, 然后把流关闭
*
* @param stream
* @param encoding
* 编码
* @return 如果读取成功返回读到的字符串,如果有异常返回null
*/
public static String readFully(InputStream stream, String encoding) {
try {
return readFully(new BufferedReader(new InputStreamReader(stream,
encoding)));
} catch (UnsupportedEncodingException e) {
logger.error("ReadFully:", e);
return null;
}
}
/**
* 把字符流中的字符一次性读到一个字符串中, 然后把字符串流关闭
*
* @param reader
* @return 如果读取成功返回读到的字符串,如果有异常返回null
*/
public static String readFully(Reader reader) {
try {
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
int n;
while ((n = reader.read(buffer)) != -1) {
sb.append(buffer, 0, n);
}
close(reader);
return sb.toString();
} catch (IOException e) {
logger.error("ReadFully:", e);
return null;
}
}
/**
* 关闭多个流
*
* @param streams
*/
public static void close(Closeable... streams) {
for (Closeable s : streams) {
close(s);
}
}
}
step3:StringUtil工具类
package com.utils;
public class StringUtil {
/**
* 判断字符串是否为空串或者不为空但无任何内容
*
* @param str
* @return
*/
public static boolean isNull(String str) {
return str == null || str.trim().equalsIgnoreCase("".trim());
}
/**
* 判断字符串是否是真实有内容的非空串
*
* @param str
* @return
*/
public static boolean isNotNull(String str) {
return !isNull(str);
}
}
step4:okhttp工具类
package com.utils.url;
import com.utils.IOStreamUtil;
import com.utils.StringUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
/**
* @author liao.lh
*/
public class OkHttp_Get_Post_Put_Delete {
private static Logger logger = LoggerFactory
.getLogger(OkHttp_Get_Post_Put_Delete.class);
private OkHttpClient client = new OkHttpClient();
private Request.Builder createBuilder(String url,Map<String, String> requestProperty) {
Request.Builder builder = new Request.Builder()
.url(url);
if (requestProperty != null) {
Set<String> keys = requestProperty.keySet();
for (String key : keys) {
builder.addHeader(key, requestProperty.get(key));
}
}
return builder;
}
private String loadResponseStr(Request.Builder builder) {
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("LoadResponseStr:", e);
}
return null;
}
private RequestBody createRequestBody(Map<String, String> params){
FormBody.Builder formBody = new FormBody.Builder();
if (params != null) {
Set<String> keys = params.keySet();
for (String key : keys) {
formBody.add(key, params.get(key));
}
}
return formBody.build();
}
/**
* 采用Get方式
*
* @param urlStr
* @param param
* @param requestProperty 请求头
* @return
*/
public String doGet(String urlStr, String param,
Map<String, String> requestProperty) {
String url = StringUtil.isNull(param) ? urlStr : urlStr + "?"
+ param;
return loadResponseStr(createBuilder(url,requestProperty));
}
/**
* 异步Get方式
*
* @param urlStr
* @param param
* @param requestProperty 请求头
* @param callback
*/
public void doGetAsync(String urlStr, String param,
Map<String, String> requestProperty, Callback callback) {
String url = StringUtil.isNull(param) ? urlStr : urlStr + "?"
+ param;
client.newCall(createBuilder(url,requestProperty).build()).enqueue(callback);
}
/**
* 采用Post方式,模拟form提交
*
* @param urlStr
* @param params
* @param requestProperty 请求头
* @return
*/
public String doPost(String urlStr, Map<String, String> params,
Map<String, String> requestProperty) {
return loadResponseStr(createBuilder(urlStr,requestProperty).post(createRequestBody(params)));
}
/**
* 异步Post方式,模拟form提交
*
* @param urlStr
* @param params
* @param requestProperty 请求头
* @param callback
* @return
*/
public void doPostAsync(String urlStr, Map<String, String> params,
Map<String, String> requestProperty, Callback callback) {
client.newCall(createBuilder(urlStr,requestProperty).post(createRequestBody(params)).build()).enqueue(callback);
}
/**
* 采用Post方式,提交json
*
* @param urlStr
* @param jsonBody
* @param requestProperty 请求头
* @return
*/
public String doPostJson(String urlStr, String jsonBody,
Map<String, String> requestProperty) {
//数据类型为json格式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
return loadResponseStr(createBuilder(urlStr,requestProperty).post(body));
}
/**
* 异步Post方式,提交json
*
* @param urlStr
* @param jsonBody
* @param requestProperty 请求头
* @param callback
*/
public void doPostJsonAsync(String urlStr, String jsonBody,
Map<String, String> requestProperty, Callback callback) {
//数据类型为json格式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
client.newCall(createBuilder(urlStr,requestProperty).post(body).build()).enqueue(callback);
}
/**
* 采用Put方式,提交json
*
* @param urlStr
* @param jsonBody
* @param requestProperty 请求头
* @return
*/
public String doPutJson(String urlStr, String jsonBody,
Map<String, String> requestProperty) {
//数据类型为json格式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
return loadResponseStr(createBuilder(urlStr,requestProperty).put(body));
}
/**
* 异步Put方式,提交json
*
* @param urlStr
* @param jsonBody
* @param requestProperty 请求头
* @param callback
*/
public void doPutJsonAsync(String urlStr, String jsonBody,
Map<String, String> requestProperty, Callback callback) {
//数据类型为json格式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
client.newCall(createBuilder(urlStr,requestProperty).put(body).build()).enqueue(callback);
}
/**
* 采用Put方式,提交json
*
* @param urlStr
* @param jsonBody
* @param requestProperty 请求头
* @return
*/
public String doDeleteJson(String urlStr, String jsonBody,
Map<String, String> requestProperty) {
if(StringUtil.isNull(jsonBody)){
return loadResponseStr(createBuilder(urlStr,requestProperty).delete());
}
//数据类型为json格式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
return loadResponseStr(createBuilder(urlStr,requestProperty).delete(body));
}
/**
* 异步Put方式,提交json
*
* @param urlStr
* @param jsonBody
* @param requestProperty 请求头
* @param callback
*/
public void doDeleteJsonAsync(String urlStr, String jsonBody,
Map<String, String> requestProperty, Callback callback) {
if(StringUtil.isNull(jsonBody)){
client.newCall(createBuilder(urlStr,requestProperty).delete().build()).enqueue(callback);
return;
}
//数据类型为json格式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
client.newCall(createBuilder(urlStr,requestProperty).delete(body).build()).enqueue(callback);
}
/**
* 上传文件
*
* @param targetURL
* @param localFilePath
* @param requestProperty 请求头
* @return
*/
public String uploadFile(String targetURL, String localFilePath,
Map<String, String> requestProperty) {
MediaType fileType = MediaType.parse("File/*");
File file = new File(localFilePath);
RequestBody body = RequestBody.create(fileType, file);
return loadResponseStr(createBuilder(targetURL,requestProperty).post(body));
}
/**
* 异步上传文件
*
* @param targetURL
* @param localFilePath
* @param requestProperty 请求头
* @param callback
*/
public void uploadFileAsync(String targetURL, String localFilePath,
Map<String, String> requestProperty, Callback callback) {
MediaType fileType = MediaType.parse("File/*");
File file = new File(localFilePath);
RequestBody body = RequestBody.create(fileType, file);
client.newCall(createBuilder(targetURL,requestProperty).post(body).build()).enqueue(callback);
}
/**
* 模拟提交表单
*
* @param targetURL
* @param params
* @param fileMap
* @param requestProperty 请求头
*/
public String formUpload(String targetURL, Map<String, String> params,Map<String, File> fileMap,
Map<String, String> requestProperty){
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
if (params != null) {
Set<String> keys = params.keySet();
for (String key : keys) {
builder.addFormDataPart(key, params.get(key));
}
}
if (fileMap != null) {
Set<String> keys = fileMap.keySet();
for (String key : keys) {
builder.addFormDataPart(key, fileMap.get(key).getName(), RequestBody.create(MediaType.parse(fileMap.get(key).getName()), fileMap.get(key)));
}
}
MultipartBody multipartBody = builder.build();
return loadResponseStr(createBuilder(targetURL,requestProperty).post(multipartBody));
}
/**
* 下载文件
*
* @param targetURL
* @param localFilePath
* @param requestProperty 请求头
* @return
*/
public boolean downloadFile(String targetURL, String localFilePath, Map<String, String> requestProperty){
InputStream is = null;
FileOutputStream fos = null;
try {
Response response = client.newCall(createBuilder(targetURL,requestProperty).build()).execute();
if (response.isSuccessful()) {
is = response.body().byteStream();
File desFile = new File(localFilePath);
File dir = desFile.getParentFile();
if (dir != null) {
if (!dir.exists()) {
dir.mkdirs();
}
}
fos = new FileOutputStream(desFile);
byte[] buf = new byte[1024*8];
int len = 0;
while ((len = is.read(buf)) != -1){
fos.write(buf, 0, len);
}
fos.flush();
}
} catch (Exception e) {
logger.error("DownloadFile:", e);
return false;
} finally {
IOStreamUtil.close(is,fos);
}
return true;
}
}
step5:获取token
public void testLoadToken() throws UnsupportedEncodingException {
String appKey = "vgSYHnnuq1IQQEERpNzU3rPLWbAhVFJ3";
String appSecret = "gRuZBPvVpptLsEw61OnOgylS8rJAZBSk";
String creds = String.format("%s:%s", appKey, appSecret);
String credential = Base64.encode(creds.getBytes("UTF-8"));
OkHttp_Get_Post_Put_Delete http = new OkHttp_Get_Post_Put_Delete();
String urlStr = "http://account-test.hsifue.cn/oauth2/token";
Map<String, String> params = new HashMap();
params.put("grant_type","client_credentials");
Map<String, String> requestProperty = new HashMap();
requestProperty.put("Authorization","Basic "+credential);
String res = http.doPost(urlStr,params,requestProperty);
System.out.println(res);
}
step6:创建企业主帐号
public void testCreateEnterpriseUser(){
String access_token = "cn-dc091e25-5323-43b9-b86f-9dd75b65eeb6";
OkHttp_Get_Post_Put_Delete http = new OkHttp_Get_Post_Put_Delete();
String urlStr = "http://apigate-test.hsifue.cn/order/api/order/v1/enterprise/user/bind?g_nonce=xxx";
Map<String, String> requestProperty = new HashMap();
requestProperty.put("Authorization","Bearer "+access_token);
requestProperty.put("Content-Type","application/json");
String bodyJson = "{\"branchName\":\"北京\",\"channelCode\":\"CRM\",\"channelCustomerId\":\"1-6KAQQP\",\"customerName\":\"AECORE文档DEMO专用客户\",\"enterpriseName\":\"数据中台\",\"passwordMobile\":\"18888888888\"}";
String res = http.doPostJson(urlStr, bodyJson, requestProperty);
System.out.println(res);
}
step7:获取资产编号
public void testLoadShellNums(){
String access_token = "cn-dc091e25-5323-43b9-b86f-9dd75b65eeb6";
OkHttp_Get_Post_Put_Delete http = new OkHttp_Get_Post_Put_Delete();
String urlStr = "http://apigate-test.hsifue.cn/order/api/order/v1/shellnums?g_nonce=xxx";
Map<String, String> requestProperty = new HashMap();
requestProperty.put("Authorization","Bearer "+access_token);
requestProperty.put("Content-Type","application/json");
String bodyJson = "{\"size\":2}";
String res = http.doPostJson(urlStr, bodyJson,requestProperty);
System.out.println(res);
}
step8:下企业云授权订单
public void testBatchOrder(){
String appKey = "vgSYHnnuq1IQQEERpNzU3rPLWbAhVFJ3";
String access_token = "cn-dc091e25-5323-43b9-b86f-9dd75b65eeb6";
OkHttp_Get_Post_Put_Delete http = new OkHttp_Get_Post_Put_Delete();
String urlStr = "http://apigate-test.hsifue.cn/order/api/order/v1/licenseOrder/batchOrder?g_nonce=xxx&appKey="+appKey;
Map<String, String> requestProperty = new HashMap();
requestProperty.put("Authorization","Bearer "+access_token);
requestProperty.put("Content-Type","application/json");
String bodyJson = "{\"channelCode\":\"CRM\",\"channelOrderId\":\"1-2019061101\",\"orderList\":[{\"sequence\":\"0\",\"customerId\":\"408c69f9324f457cafde3def0c78abba\",\"crmCustomerId\":\"1-6KAQQP\",\"customerName\":\"0\",\"channelCustomerId\":\"1-6KAQQP\",\"adminName\":\"邹叶\",\"adminAccount\":\"18791489712\",\"adminEmail\":null,\"adminCellNumber\":\"18791489712\",\"customerType\":\"company\",\"branchCode\":\"北京\",\"branchName\":\"北京\",\"enterpriseGlobalId\":\"6530988208690537107\",\"licenseType\":\"cloud_customer\",\"orderType\":\"new_buy\",\"assets\":[{\"assetNos\":[\"YSA8000000051\"],\"limitStartDate\":null,\"limitEndDate\":null,\"borrowedUsbKey\":null,\"products\":[{\"crmProductId\":\"1-5YQ0YR\",\"parentCrmProductId\":\"1-5Z22RL\",\"productUri\":\"42429\",\"productName\":\"304永利集团造价云管理平台名2\",\"gmsPid\":\"42429\",\"appKey\":null,\"productType\":\"4\",\"limitStartDate\":1556380800000,\"limitEndDate\":1588003200000,\"limitConcurrent\":1,\"limitTimeDuration\":null,\"trial\":0,\"trialEndDate\":null,\"passwords\":null,\"timeUnit\":null,\"timeUnitQuantity\":null,\"timeDurationExpression\":null}]}]}]}";
String res = http.doPostJson(urlStr,bodyJson ,requestProperty);
System.out.println(res);
}