OPENAPI获取sign和params demo
1. php demo
<?php
function getSignMsg($data,$secret) {
$iv = random_bytes(16);
$cipher = 'AES-256-CBC';
$value = openssl_encrypt(serialize($data), $cipher, $secret,0,$iv);
$mac = hash_hmac('sha256',($iv = base64_encode($iv)).$value, $secret);
$json = json_encode(compact('iv', 'value', 'mac'));
return base64_encode($json);
}
function doPost($url,$applicationID,$signMsg) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
$post_data = array(
"applicationID" => $applicationID,
"signMsg" => $signMsg
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$data = array(
'lessonId' => "12345",
'diskId' => "[356]"
);
$url = "直播云提供的URL";
$secret = "直播云提供的密钥";
$applicationID = "直播云提供的applicationID";
$route = "/lesson/add/disk";
$signMsg = getSignMsg($data,$secret);
echo doPost($url . $route,$applicationID,$signMsg);
?>
2. nodejs demo
var zbyopenapi = require("./zbyopenapi")
var http = require("http")
var querystring = require('querystring');
var url = "直播云提供的url"
var secret = "直播云提供的密钥"
var applicationID = "直播云提供的应用id"
var path = "/lesson/add/disk"
var data = {
"lessonId" : "12345",
"diskId" : "[356]"
}
var post_data = querystring.stringify({
"applicationID" : applicationID,
"signMsg" : zbyopenapi.getmsg(data,secret)
});
var post_options = {
host: url,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
});
});
post_req.write(post_data);
post_req.end();
3. java demo
import java.io.IOException;
import java.util.*;
import com.zby.openapi.*;
import com.alibaba.fastjson.JSON;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Example {
public static final String secret = "直播云提供的密钥";
public static final String applicationID = "直播云提供的应用ID";
public static final String url = "直播云提供的url";
public static void main(String[] args) throws Exception {
Map data=new HashMap();
Map form = new HashMap();
data.put("classroomId", "1320447");
data.put("startTime", "2018-07-29 09:00");
data.put("endTime", "2018-07-29 12:00");
data.put("genre", "0");
form.put("applicationID",applicationID);
form.put("signMsg",Example.getMsg(secret,data));
System.out.println(Example.send(url +"/lesson/create",form,"utf-8"));
}
public static String getMsg(String secret,Object data) throws Exception {
Map compact =new HashMap();
String ivString = secret.substring(0,16);
byte[] ivByte = ivString.getBytes();
String str = new String(PHPSerializer.serialize(data));
AES aes = new AES(secret,ivByte);
byte[] crypted = aes.encrypt(str.getBytes());
String value = new String(com.zby.openapi.Base64.encode(crypted));
String iv = com.zby.openapi.Base64.encode(ivString);
String ivv = iv + value;
String mac = HmacSha256.hashHmac(ivv,secret);
compact.put("iv", iv);
compact.put("value", value);
compact.put("mac", mac);
String json = JSON.toJSONString(compact);
String msg = com.zby.openapi.Base64.encode(json);
return msg;
}
public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException {
String body = "";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
response.close();
return body;
}
}
4. golang demo
package main
import (
"fmt"
"encoding/base64"
"crypto/rand"
"math/rand"
"time"
"serialize"
"hmac"
"aes"
"encoding/json"
"net/http"
"net/url"
"io/ioutil"
)
func main() {
devUrl := "直播云提供的Host/user/create"
data := make(map[interface{}]interface{})
user := make(map[interface{}]interface{})
users := make([]interface{},0,20)
user["userPhone"] = "12634658345"
user["userName"] = "张星龙"
user["userType"] = "1"
user["userGender"] = "1"
users = append(users,user)
users = append(users,user)
data["userData"] = users
key := []byte("直播云提供的密钥")
result := getSignMsg(data,key)
client := &http.Client{}
post := url.Values{}
post.Add("applicationID", "直播云提供的应用ID")
post.Add("signMsg",result)
resp, err := client.PostForm(devUrl, post)
defer resp.Body.Close()
if err != nil {
fmt.Println(err.Error())
}
if resp.StatusCode == 200 {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
}
func getSignMsg(data interface{},key []byte) string {
ivBase := randomBytes(16)
compact := make(map[string]string)
serializeResult,_ := serialize.Encode(data)
value := aes.Encode(serializeResult,key,ivBase)
iv := base64.StdEncoding.EncodeToString(ivBase)
inputString := iv + value
mac := hmac.Encode(inputString,key)
compact["iv"] = iv
compact["value"] = value
compact["mac"] = mac
jsonResult,_ := json.Marshal(compact)
return base64.StdEncoding.EncodeToString(jsonResult)
}
func randomBytes(n int, alphabets ...byte) []byte {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
var randby bool
if num, err := r.Read(bytes); num != n || err != nil {
rand.Seed(time.Now().UnixNano())
randby = true
}
for i, b := range bytes {
if len(alphabets) == 0 {
if randby {
bytes[i] = alphanum[rand.Intn(len(alphanum))]
} else {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
} else {
if randby {
bytes[i] = alphabets[rand.Intn(len(alphabets))]
} else {
bytes[i] = alphabets[b%byte(len(alphabets))]
}
}
}
return bytes
}
5. C# demo
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ZbyOpenApi;
using Newtonsoft.Json;
using System;
namespace ApiTest
{
class Test
{
static void Main(string[] args)
{
Hashtable data = new Hashtable();
ArrayList users = new ArrayList();
Hashtable user1 = new Hashtable();
Hashtable user2 = new Hashtable();
user1["userPhone"] = "13895675049";
user1["userName"] = "张一";
user1["userType"] = 1;
user1["userGender"] = 1;
users.Add(user1); //添加第一个人
user2["userPhone"] = "13895675048";
user2["userName"] = "张二";
user2["userType"] = 1;
user2["userGender"] = 1;
users.Add(user2); //添加第二个人
data["userData"] = users;
var applicationID = "applicationID"; //直播云提供的应用ID
var secret = "secret"; //直播云提供的密钥
var url = "http://Host" + "/user/create"; //直播云提供的地址
var signMsg = Aes.getSign(secret,data);
var postData = "applicationID=" + applicationID + "&" + "signMsg=" + signMsg;
Console.WriteLine(postData);
Console.WriteLine(signMsg);
Console.Write(Test.SendHttpRequest(url,"POST", postData));
Console.ReadLine();
}
public static string SendHttpRequest(string requestURI, string requestMethod, string json)
{
try
{
string requestData = json;
string serviceUrl = requestURI;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
myRequest.Method = requestMethod;
byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(requestData);
myRequest.ContentLength = buf.Length;
myRequest.Timeout = 5000;
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.MaximumAutomaticRedirections = 1;
myRequest.AllowAutoRedirect = true;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(buf, 0, buf.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string ReqResult = reader.ReadToEnd();
reader.Close();
myResponse.Close();
return ReqResult;
}
catch (UriFormatException e) {
return "something error";
}
}
}
}