web端与app视频通话,由服务端创建token
@Component
public class AliRtcUtil {
// 监听端口
private int listen;
// 应用ID
@Value("${aliyun.rtc.appID}")
private String appID;
// 应用密钥
@Value("${aliyun.rtc.appKey}")
private String appKey;
// 服务地址
@Value("${aliyun.rtc.gslb}")
private String gslb;
// 频道随机码
private String nonce;
// 频道时间戳
private Long timestamp;
// 用户唯一标识
private String userID;
// 加入频道token
private String token;
// 生成token
public static String createToken(
String appId, String appKey, String channelId, String userId,
String nonce, Long timestamp
) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(appId.getBytes());
digest.update(appKey.getBytes());
digest.update(channelId.getBytes());
digest.update(userId.getBytes());
digest.update(nonce.getBytes());
digest.update(Long.toString(timestamp).getBytes());
String token = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
return token;
}
// 生成userID
public static String createUserID(String channelID, String user) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(channelID.getBytes());
digest.update("/".getBytes());
digest.update(user.getBytes());
String uid = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
return uid.substring(0, 16);
}
/**
* 生成鉴权信息
* @return
*/
public Map<String,Object> authenticationInfo(String callPhone,String calledPhone){
try {
String channelId = UUID.randomUUID().toString();
String userIDCall = createUserID(channelId, callPhone);
String userIDCalled = createUserID(channelId, calledPhone);
//令牌随机码,这里使用AK-+UUID
nonce = String.format("AK-%s", UUID.randomUUID().toString());
Calendar nowTime = Calendar.getInstance();
// 令牌过期时间,48小时
nowTime.add(Calendar.HOUR_OF_DAY, 48);
timestamp = nowTime.getTimeInMillis() / 1000;
String tokenCall = createToken(appID, appKey, channelId, userIDCall, nonce, timestamp);
String tokenCalled = createToken(appID, appKey, channelId, userIDCalled, nonce, timestamp);
// 封装鉴权信息json格式
JSONObject call = new JSONObject()
.put("channelId",channelId)
.put("appId", appID)
.put("userId", userIDCall)
.put("gslb", new JSONArray().put(gslb))
.put("token", tokenCall)
.put("nonce", nonce)
.put("timestamp", timestamp);
JSONObject called = new JSONObject()
.put("channelId",channelId)
.put("appId", appID)
.put("userId", userIDCalled)
.put("gslb", gslb)
.put("token", tokenCalled)
.put("nonce", nonce)
.put("timestamp", timestamp);
Map<String,Object> map = new HashMap<>();
map.put("call",call);
map.put("called",called);
return map;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}