# DEMO示例

# 服务场景描述

接入授权中心的产品提供方需关注两个事项:

1、将销售产品时涉及的客户、授权载体类型、产品以及产品使用权限信息按照授权中心约定的数据格式传递给授权中心。

2、从授权中心获取许可信息,包括客户信息,产品信息与产品使用权限信息等。

本例以授权业务中最复杂的企业云授权为入门点,讲解产品提供方接入授权中心的方法。

企业云授权通过调用创建企业主帐号API、获取资产编号API和批量创建基本授权订单API完成将销售产品涉及的使用权限信息传递给授权中心的功能,完成产品提供方接入授权中心。

# 服务调用流程

# 1.本服务调用依赖以下API:

创建企业主帐号

获取资产编号

批量创建基本授权订单

# 2.服务调用前置条件:

  • 创建应用,获取appkey、appsecret;

  • 获取服务调用token;

  • 开通服务,scope授权通过;

以上步骤可参考前置准备

# 3.具体调用步骤

step1:maven依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.3.0</version>
</dependency>
1
2
3
4
5

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);
		}
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

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);
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

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;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320

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 = "https://account-test.glodon.com/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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

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 = "https://apigate-test.glodon.com/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);
}
1
2
3
4
5
6
7
8
9
10
11

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 = "https://apigate-test.glodon.com/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);
}
1
2
3
4
5
6
7
8
9
10
11

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 = "https://apigate-test.glodon.com/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\":\"广联达造价云管理平台名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);
}
1
2
3
4
5
6
7
8
9
10
11
12
  • 在线客服

  • 意见反馈