OPENAPI获取sign和params demo

1. php demo


<?php

function getSignMsg($data,$secret) {   //生成signMsg函数,该函数可直接使用
     $iv     = random_bytes(16);    //生成随机16个字节,用于加密摘要 ,该函数仅对php7用
     //$iv =substr($secret,0,16);      //若是php7,可用 substr($secret,0,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_HEADER, 1);
    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        = "直播云提供的密钥";           // secret , 密钥
$applicationID = "直播云提供的applicationID";
$route = "/lesson/add/disk";
$signMsg =  getSignMsg($data,$secret);                         // 生成signMsg

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();
        //用密钥的前16位,生成摘要
        String ivString = secret.substring(0,16);
        byte[] ivByte = ivString.getBytes();

        //对表单数据进行序列化
        String str = new String(PHPSerializer.serialize(data));
        AES aes = new AES(secret,ivByte);
        //进行aes_256_cbc加密
        byte[] crypted = aes.encrypt(str.getBytes());

        //对aes加密结果进行base64编码
        String value = new String(com.zby.openapi.Base64.encode(crypted));

        //对摘要信息进行base64编码
        String iv = com.zby.openapi.Base64.encode(ivString);

        //生成最终的摘要信息
        String ivv = iv + value;

        //生成摘要经过sha256加密后的密文
        String mac = HmacSha256.hashHmac(ivv,secret);

        //将正文信息,摘要信息 放在一块
        compact.put("iv", iv);
        compact.put("value", value);
        compact.put("mac", mac);

        //转换成json格式字符串
        String json = JSON.toJSONString(compact);

        //经过base64编码生成最终的签名
        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 = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        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) {
            //按指定编码转换结果实体为String类型
            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)     //添加用户1
      users = append(users,user)     //添加用户2
      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";
            }
        }

    }
}

results matching ""

    No results matching ""