Jong Communication API learning process and RESTAPI node. js Package

Source: Internet
Author: User
Tags md5 encryption sub account

Enter the body ~ The company has a recent activity, will use the function of cloud communication. As an all-stack engineer, it's natural to be a bit more familiar with JavaScript, so decide to choose Nodejs for development. Looking at the documentation for the cloud communication, there is no Nodejs SDK (´°???????? ω°???????? Fortunately, the rest API is based on the HTTP protocol, and the interface can be implemented easily in other languages (? >?<?).

Maybe it's because there's no concept of cloud communication, and it's foggy to read the document again. How to do it ... So decided to document an interface test, try to come down to the cloud communication function also has a general understanding.

Understand that there are about three interfaces of cloud communication:

    • 1. VoIP clients, including Android, IOS, Windows's client SDK and Flash-based Web SDK, can be assigned a VoIP phone number to achieve the same functions as a floor phone
    • 2. The application initiated by the RESTAPI, the application to the cloud communication request, can achieve sub-accounts, text messages, two-way callback, voice verification code, phone download and create a conference call and so on operations
    • 3. Cloud communication initiates a request to the application server and makes corresponding actions based on the returned results. Commonly used for IVR related functions


Let's start with the second kind of came David, because this operation is more capable of mastering the initiative. (‾??)?

The first is a sub-account that can be used to sign in with a VoIP client. Most of the requests for RESTAPI need to be initiated through the master account, but there are some APIs that need to be initiated through the sub account. So we first try to start a request to create a sub-account.

The document that created the sub-account is
Http://docs.cloopen.com/index.php/%E5%88%9B%E5%BB%BA%E5%AD%90%E8%B4%A6%E6%88%B7

Look at the document saying the requested address is:

/{softversion}/accounts/{accountsid}/subaccounts


Well, these are a good thing, don't understand ah ... Don't worry. There is also a link to "Unified request Header" below the documentation:
Http://docs.cloopen.com/index.php/Rest%E4%BB%8B%E7%BB%8D#2_.E7.BB.9F.E4.B8.80.E8.AF.B7.E6.B1.82.E5.8C.85.E5.A4.B4

First there is a BaseURL:

https://sandboxapp.cloopen.com:8883/2013-12-26


From the Sandboxapp can be seen this is the test BaseURL (from the cloud communication console can see production BaseURL front is https://app.cloopen.com:8883), and "2013-12-26" is the request address { Softversion} section.
This is the first part of the request address, so the full address of the above request is:

https://sandboxapp.cloopen.com:8883/2013-12-26/accounts/{accountsid}/subaccounts



Next you can see two URL formats:

/accounts/{accountsid}/{func}/{funcdes}?sig={sigparameter}
/subaccounts/{subaccountsid}/{func}/{funcdes}?sig={sigparameter}


The first is initiated through the master account, and the second is through a sub-account. We want to implement the creation of the sub-account interface is the first, need to pass the master account information. When you log in to the Cloud communications console, you can see that there is an account SID, which is {accountsid}. Assuming my account SID is xxxxxx, the request address is:

https://sandboxapp.cloopen.com:8883/2013-12-26/Accounts/xxxxxx/SubAccounts



In order to spell out a request address, Luo Li has written so many, is not very annoying? Okay, okay, here's the more important part, the unified request header.
The interface for cloud communication can be in two formats, XML and JSON. As a JS developer would certainly like to use JSON, unfortunately there are many interfaces such as IVR-related interfaces only support XML.
In the request head must include Content-type,accept, and Content-length. The Content-type field represents the format of the originating request body, and the Accept represents the format that you want to return. If you are sending XML and want to return XML, the request header needs to be

Accept:application/xml;
Content-type:application/xml;charset=utf-8;


Content-length is the length of the request body, the general use of the request library should help to calculate it. I used the request library for node. js.

Then there must be two additional parameters: Sigparameter and Authorization. These two need to be self-explanatory, according to the documentation:

  2. Sigparameter is the rest API Validation parameter
         url must have the sig parameter, for example: SIG=ABCDEFG.
      ·   use MD5 encryption (account ID + account Authorization token + timestamp). Where the account ID and account authorization token correspond to the primary account or sub account based on the authentication level of the URL.
      ·   Timestamp is the current system time, format "YYYYMMDDHHMMSS". Timestamp valid for 24 hours, such as: 20140416142030
         sigparameter parameter requires uppercase   


Here is the implementation:


Implement a method of calculating MD5
Crypto = require (' crypto ')
MD5 = function (str, type= ' hex ') {
md5sum = Crypto.createhash (' MD5 ')
Md5sum.update (str)
return Md5sum.digest (Type)
}
Calculate sig
Sid is the SID of the master account or sub account, in this case the main account is the xxxxxx mentioned above
Token is the token of the master account or sub-account, in this case the main account token, which is the AUTH token seen in the console, assuming my yyyyyy
Timestamp is a timestamp in the form of YYYYMMDDHHMMSS, where it is not a function of sketching timestamp.
Getsig = function (SID, token, timestamp) {
return MD5 (SID + token + timestamp). toUpperCase ()
}

Look at the document also thought Sigparameter also need to add in the request head, practice found in QueryString Riga a sig parameter can be
Then the request address becomes

https://sandboxapp.cloopen.com:8883/2013-12-26/Accounts/xxxxxx/SubAccounts?sig= The results of the calculation.



Go on:


3. Authorization is Baotou authentication information
• Use BASE64 encoding (account ID + colon + timestamp) where the account ID corresponds to the primary account or sub-account based on the authentication level of the URL
• Colon is English colon
• The timestamp is the current system time, in the format "YYYYMMDDHHMMSS", which needs to be the same as the timestamp in Sigparameter.



Authorization need to be added to the request. Realize:

Implement a method of calculating base64 encoding
Base64 = function (str) {
Return (new Buffer (str)). toString (' base64 ')
}
getauthorization = function (SID, timestamp) {
Return base64 (SID + ': ' + timestamp)
}

Looking back at the document creating the sub-account interface, you need to use the POST method and pass AppId and FriendlyName.
To create a sub account, you need to first create an app in the Cloud Communications console, which is the ID of the app you've created. appId FriendlyName is the nickname of the sub-account, must fill in, each sub-account of the friendlyname is unique.

Finally we want to use JSON format to interact, so the method of initiating the request is probably:


Request = require (' request ')
Sid = ' xxxxxx '
token = ' yyyyyy '
appId = ' zzzzzz '
FriendlyName = ' NewUser '
timestamp = Gettimestamp ()
Request ({
URI: ' Https://sandboxapp.cloopen.com:8883/2013-12-26/Accounts/xxxxxx/SubAccounts ',
QS: {sig:getsig (SID, Token, timestamp)},
Header: {
Accept: ' Application/json; ',
' Content-type ': ' Application/json;charset=utf-8; '
Authorization:getauthorization (SID, Timestamp)
},
Body: {
Appid:appid,
Friendlyname:friendlyname
}
}, function (err, response, body) {
callback function
Console.log (body)
})


Results:

{statusCode: ' 000000 ',
Subaccount:
{subaccountsid: ' cdxxxxxxxxxxxxxx90 ',
Voipaccount: ' 8xxxxxxxx7 ',
dateCreated: ' 2014-06-01 12:40:06 ',
Voippwd: ' HXXXXV ',
Subtoken: ' 0xxxxxxxxxxxxxxxa '}}

Done!

The next interfaces are similar, so it's easy. But try to IVR-related interface, but always error, has been unknown so, until the discovery of the IVR document does not have JSON corresponding format description, this thought: I le go, IVR interface does not support json!
So we need to serialize the JS object into XML. Let the dog search, found a js2xmlparser, use is quite simple. Let's say we want to get XML like this:

<?xml version= ' 1.0 ' encoding= ' utf-8 '?>
<Request>
<Appid>111222333444555666777888</Appid>
<createconf action= "createconfresult.jsp" maxmember= "5"/>
</Request>

The serialization method and the format of the incoming object are:

Js2xmlparser = require (' Js2xmlparser ')
Js2xmlparser (' Request ', {
Appid: ' 111222333444555666777888 ',
createconf:{
‘@‘: {
' Action ': ' createconfresult.jsp ',
' Maxmember ': ' 5 '
}
}
})


Js2xmlparserFor detailed usage, you can go to the official website to see:
Https://github.com/michaelkourlas/node-js2xmlparser

Fortunately, the returned result can still be specified as ' Application/json; ', which returns a JSON string that needs to be parsed by calling Json.parse itself.

Finally, some common interfaces of cloud communication are encapsulated and written into a node. js module. Before the time to write documents and test by one, interested students can first look at the code, welcome all kinds of smashing brick newspaper bug~
Https://github.com/ipy/yuntongxun

Jong Communication API learning process and RESTAPI node. js Package

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.