• 沒有找到結果。

JObject jsonObj = (JObject)JsonConvert.DeserializeObject(jsonBody); //将通知消息解析为jsonObj string eventType = jsonObj["eventType"].ToString(); //通知事件类型

if (!"fee".Equals(eventType)) {

Console.WriteLine("EventType error:" + eventType);

return;

}

if (!jsonObj.ContainsKey("feeLst")) {

Console.WriteLine("param error: no feeLst.");

return;

}

JObject[] feeLst = jsonObj["feeLst"].ToObject<JObject[]>(); //呼叫话单事件信息 //Example: 此处以解析sessionId为例,请按需解析所需参数并自行实现相关处理

//短时间内有多个通话结束时语音通话平台会将话单合并推送,每条消息最多携带50个话单 if (feeLst.Length > 1)

{

foreach (JObject loop in feeLst) {

if (loop.ContainsKey("sessionId")) {

Console.WriteLine("sessionId:" + loop["sessionId"]);

} } }

else if (feeLst.Length == 1) {

if (feeLst[0].ContainsKey("sessionId")) {

Console.WriteLine("sessionId:" + feeLst[0]["sessionId"]);

} } else {

Console.WriteLine("feeLst error: no element.");

} } } }

4.2 语音通知代码样例

4.2.1 Node.js

注:为节省开发时间,建议先使用Node.js代码样例进行调测,熟悉接口使用后,再参 考Java、python、PHP或C#代码样例,结合接口文档进行功能开发。

环境要求 Node.js 4.4.4及以上版本。

引用库

-下载链接 点击下载

须知

● 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从 国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。

● 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。

● 本文档信息仅供参考,不构成任何要约或承诺。

4.2.2 Java

注:使用前请务必先仔细阅读使用注意事项。

环境要求 JDK 1.6及以上版本。

引用库

httpclient、httpcore、httpmime、commons-codec、

commons-logging、jackson-databind、jackson-annotations、jackson-core、fastjson、log4j

下载链接 点击下载

须知

● 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从 国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。

● 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。

● 本文档信息仅供参考,不构成任何要约或承诺。

4.2.3 Python

环境要求 Python 3.0及以上版本。

引用库 requests 2.18.1

1. 请自行下载安装Python 3.x,并完成环境配置。

2. 打开命令行窗口,执行pip install requests命令。

3. 执行pip list查看安装结果。

须知

● 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从 国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。

● 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。

● 本文档信息仅供参考,不构成任何要约或承诺。

“语音通知 API”代码样例

# coding: utf-8 -*-import base64 import hashlib

import requests #需要先使用pip install requests命令安装依赖 import time

now = time.strftime('%Y-%m-%dT%H:%M:%SZ') #Created nonce = str(uuid.uuid4()).replace('-', '') #Nonce

digest = hashlib.sha256((nonce + now + appSecret).encode()).hexdigest() digestBase64 = base64.b64encode(digest.encode()).decode() #PasswordDigest

return 'UsernameToken Username="{}",PasswordDigest="{}",Nonce="{}",Created="{}"'.format(appKey, digestBase64, nonce, now);

def voiceNotifyAPI(displayNbr, calleeNbr, playInfoList):

if len(displayNbr) < 1 or len(calleeNbr) < 1 or playInfoList is None:

return

apiUri = '/rest/httpsessions/callnotify/v2.0' #v1.0 or v2.0 requestUrl = base_url + apiUri

header = {

'Content-Type': 'application/json;charset=UTF-8',

'Authorization': 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"', 'X-WSSE': buildWSSEHeader(appKey, appSecret)

}

r = requests.post(requestUrl, json=jsonData, headers=header, verify=False) print(r.text) #打印响应结果

except requests.exceptions.HTTPError as e:

print(e.code)

# 'replayAfterCollection': 'false', #设置是否在收号后重新播放notifyVoice或templateId指定的放音

# 'collectContentTriggerReplaying': '1' #设置触发重新放音的收号内容 }]

return playInfoList if __name__ == '__main__':

playInfoList = getPlayInfoList('notifyvoice.wav', 'xxxxxx', ['3', '人民公园正门']) voiceNotifyAPI('+86531*******4', '+86135*******1', playInfoList)

“呼叫状态通知 API”代码样例

'sessionId': '[email protected]', 'timestamp': '2019-01-24 03:04:24',

jsonObj = json.loads(jsonBody) #将通知消息解析为jsonObj eventType = jsonObj['eventType'] #通知事件类型

if ('fee' == eventType):

statusInfo = jsonObj['statusInfo'] #呼叫状态事件信息 print('eventType: ' + eventType) #打印通知事件类型

print('sessionId: ' + statusInfo['sessionId'])

onCallEvent(jsonBody) #呼叫事件处理

“话单通知 API”代码样例

'sessionId': '[email protected]', #通话链路的

唯一标识 'callerNum': '+86138*******2', #主叫号码

jsonObj = json.loads(jsonBody) #将通知消息解析为jsonObj eventType = jsonObj['eventType'] #通知事件类型

if ('fee' != eventType):

if __name__ == '__main__':

onFeeEvent(jsonBody) #话单处理

4.2.4 PHP

环境要求 PHP 7.0及以上版本。

引用库

-下载链接 点击下载

须知

● 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从 国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。

● 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。

● 本文档信息仅供参考,不构成任何要约或承诺。

4.2.5 C#

环境要求 .NET Core 2.0及以上版本或.NET Framework 4.7.1及以上版 本。

引用库 Newtonsoft.Json 11.0.2,请参考https://

www.newtonsoft.com/json获取。

须知

● 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从 国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。

● 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。

● 本文档信息仅供参考,不构成任何要约或承诺。

“语音通知 API”代码样例

using Newtonsoft.Json;

using System;

using System.Collections;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.IO;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Security.Cryptography;

using System.Text;

namespace voicecall_csharp_demo_x_wsse_

{

class VoiceNotify

ArrayList playInfoList = getPlayInfoList("notifyvoice.wav", "xxxxxx", ["3", "人民公园正门"]);

//固话号码从控制台号码管理页获取,被叫号码请替换为实际号码.

voiceNotifyAPI("+86531*******4", "+86135*******1", playInfoList);

}

static void voiceNotifyAPI(string displayNbr, string calleeNbr, ArrayList playInfoList) {

if (String.IsNullOrEmpty(displayNbr) || String.IsNullOrEmpty(calleeNbr) || Count(playInfoList) < 1) {

client.DefaultRequestHeaders.Add("Authorization", "WSSE realm=\"SDP\",profile=

\"UsernameToken\",type=\"Appkey\"");

client.DefaultRequestHeaders.Add("X-WSSE", buildWSSEHeader(appKey, appSecret));

//请求Body

HttpContent content = new StringContent(JsonConvert.SerializeObject(body));

//请求Headers中的Content-Type参数

content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var response = client.PostAsync(requestUrl, content).Result;

Console.WriteLine(e.StackTrace);

Console.WriteLine(e.Message); //打印错误信息 }

}

static string buildWSSEHeader(string appKey, string appSecret) {

string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //Created string nonce = Guid.NewGuid().ToString().Replace("-", ""); //Nonce

byte[] material = Encoding.UTF8.GetBytes(nonce + now + appSecret);

byte[] hashed = SHA256Managed.Create().ComputeHash(material);

string hexdigest = BitConverter.ToString(hashed).Replace("-", "");

string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexdigest)); //PasswordDigest return String.Format("UsernameToken Username=\"{0}\",PasswordDigest=\"{1}\",Nonce=

\"{2}\",Created=\"{3}\"",

appKey, base64, nonce, now);

}

static ArrayList getPlayInfoList(string notifyVoice, string templateId, string[] templateParas) {

ArrayList playInfoList = new ArrayList(); //播放信息列表,最大支持5个 /*此处以构建一个playInfoDic,添加到playInfoList为例,请按需构建多个*/

Dictionary<string, object> playInfoDic = new Dictionary<string, object>();

playInfoDic.Add("notifyVoice", notifyVoice);

playInfoDic.Add("templateId", templateId);

playInfoDic.Add("templateParas", templateParas);

//playInfoDic.Add("collectInd", 0); //是否进行收号

//playInfoDic.Add("replayAfterCollection", "false"); //设置是否在收号后重新播放notifyVoice或 templateId指定的放音

//playInfoDic.Add("collectContentTriggerReplaying", "1"); //设置触发重新放音的收号内容 playInfoList.Add(playInfoDic); //playInfoList添加元素

return playInfoList;

}

//低于.NET Framework 4.7.1版本,启用如下方法

//static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)

string jsonBody = JsonConvert.SerializeObject(new Dictionary<string, object>(){

{"eventType", "callout"},

{"statusInfo", new Dictionary<string, object>(){

{"sessionId", "[email protected]"}, {"timestamp", "2019-01-24 03:04:24"},

{"caller", "+86138*******2"}, {"called", "+86138*******1"}, }

}

/// <param name="jsonBody"></param>

static void OnCallEvent(string jsonBody) {

JObject jsonObj = (JObject)JsonConvert.DeserializeObject(jsonBody); //将通知消息解析为jsonObj string eventType = jsonObj["eventType"].ToString(); //通知事件类型

if ("answer".Equals(eventType))

static void Main(string[] args) {

//话单通知样例

string jsonBody = JsonConvert.SerializeObject(new Dictionary<string, object>(){

{"eventType", "fee"},

/// <param name="jsonBody"></param>

static void OnFeeEvent(string jsonBody) {

JObject jsonObj = (JObject)JsonConvert.DeserializeObject(jsonBody); //将通知消息解析为jsonObj string eventType = jsonObj["eventType"].ToString(); //通知事件类型

if (!"fee".Equals(eventType)) {

Console.WriteLine("EventType error:" + eventType);

return;

}

if (!jsonObj.ContainsKey("feeLst")) {

Console.WriteLine("param error: no feeLst.");

return;

}

JObject[] feeLst = jsonObj["feeLst"].ToObject<JObject[]>(); //呼叫话单事件信息 //Example: 此处以解析sessionId为例,请按需解析所需参数并自行实现相关处理

//短时间内有多个通话结束时语音通话平台会将话单合并推送,每条消息最多携带50个话单 if (feeLst.Length > 1)

{

foreach (JObject loop in feeLst) {

if (loop.ContainsKey("sessionId")) {

Console.WriteLine("sessionId:" + loop["sessionId"]);

} } }

else if (feeLst.Length == 1) {

if (feeLst[0].ContainsKey("sessionId")) {

Console.WriteLine("sessionId:" + feeLst[0]["sessionId"]);

} } else {

Console.WriteLine("feeLst error: no element.");

} } } }

相關文件