goeasy的历史消息数据同步Webhook接口

goeasy的历史消息数据同步Webhook接口

goEasy会根据不同的套餐对历史消息做不同期限的存储,到期后会自动清除,如果你需要长期保存,可以使用goEasy提供的webhook接口同步历史消息到你们服务器上去,然后历史消息的查询接口走你们服务器就好。

webhook相关的文档参考这里:https://www.goeasy.io/cn/im/webhook/webhook.html

下面简单介绍一下如何使用goeasy的webhook接口:

原理解释:

webhook接口本质上是goEasy通过post请求将历史消息打包发送到你的服务器去。你的服务器上只需要根据goEasy的要求实现接收post请求就好,然后解析内容格式,将发送过来的数据存入数据库即可。

以下代码可以用于调试webhook接口,开发者仅需将secretkey修改为自己的即可。待webhook接口调试通过后,再补充自己的业务处理代码。

PHP_webhook参考代码:

<?php
//获取body里的content
$content=$_POST["content"];
//secretKey,在GoEasy控制台应用详情中获取
$secretKey='';
//获取header里的x-goeasy-signature
$x_goeasy_signature= $_SERVER['HTTP_X_GOEASY_SIGNATURE'];

//验证签名合法性
 function getSignature($secretKey, $content) {
        return base64_encode(hash_hmac("sha1", $content, $secretKey, true));
 }

//获取签名结果
$getSignature=getSignature($secretKey, $content);
 
//签名结果与header里的 "x-goeasy-signature"进行对比
if (strcmp($getSignature,$x_goeasy_signature )==0) {
//验证通过,返回{"code":200,"content":"success"}
echo json_encode(['code'=>200,'content'=>'success']);

//验证成功后保存数据:这里是保存到本地文件,开发者可根据实际业务需求做更多个性化操作
file_put_contents("content.txt","$content",FILE_APPEND);
}
else{
echo json_encode(['code'=>500,'content'=>'fail']);
	}
?>

JAVA_webhook参考代码:


//获取 header 里的 "x-goeasy-signature" 值
 String goeasySignature = request.getHeader("x-goeasy-signature"); 

//获取body里的content
String content = request.getParameter(“content”)

//secretKey,在GoEasy控制台应用详情中获取
String secretKey='';

//验证签名
   public static boolean verify(String secretKey, String content,String goeasySignature){
        try {
            SecretKeySpec signinKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signinKey);
            byte[] rawHmac = mac.doFinal(content.getBytes("UTF8"));
            if(new BASE64Encoder().encode(rawHmac).equals(goeasySignature)){
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("HMACSHA1 failed for key:{} and content:{}", secretKey, content, e);
            return false;
        }
    }
 boolean verified = verify(secretKey, content, goeasySignature);

//验证通过,返回{"code":200,"content":"success"}
 Map map = new HashMap();
        if(verified){
            map.put("code",200);
            map.put("content","success");
//验证成功后,可以在此输出content的值
System.out.print(content);
        }else{
            map.put("code",500);
            map.put("content","fail");
        }
 return gson.toJson(map);

Comments are closed.