一、企业微信自建应用与后台服务实现交互
1、已需要下载PC版企业微信,并且注册自己的企业,主要为了获取企业ID等与企业微信服务打通,登录企业管理后台企业微信
2、选择自建应用,新建自己的应用,如下,我自建一个小应用就叫【智能客服】
3.点击我的企业,获取企业scorpId
4.设置应用与自己的后台应用的消息接口API
(1)该接口API就是企业微信自建应用与我后台交互的关键,具体实现步骤如下
(2)关键代码,按照企业微信自建应用消息的开发文档,必须实现两个请求方式为GET和POST的相同接口URL的接口:
GET请求
/**
* 智能客服
*
* @param request
* @return R
*/
@GetMapping("/intelligentCustomerService")
public String magicLogin(@RequestParam(value = "state") String state,
HttpServletRequest request) {
log.info("AiManagerController validEntWeChatURL validEntWeChatURL={}", request);
String sReplyEchoStr = null;
//微信加签
String sMsg_signature = request.getParameter("msg_signature");
//解析url
String sTimestamp = request.getParameter("timestamp");
String SNonce = request.getParameter("nonce");
String SEchostr = request.getParameter("echostr");
try {
Map<String, Object> resultMap = wecomCallbackService.intelligentCallback(state, request);
WXBizMsgCrypt crypt = (WXBizMsgCrypt) resultMap.get("crypt");
sReplyEchoStr = crypt.VerifyURL(sMsg_signature, sTimestamp, SNonce, SEchostr);
} catch (AesException e) {
log.error("AiManagerController validEntWeChatURL err={}", e);
}
return sReplyEchoStr;
}
POST请求
/**
* 接收企业微信的消息
*
* @param request
* @return
*/
@PostMapping("/intelligentCustomerService")
public String getEntWXMsg(@RequestParam(value = "state") String state, HttpServletRequest request, HttpServletResponse response) {
String respMsg = "";
//微信加签
String sMsg_signature = request.getParameter("msg_signature");
//解析url
String sTimestamp = request.getParameter("timestamp");
String SNonce = request.getParameter("nonce");
try {
ServletInputStream inputStream = request.getInputStream();
String sReqData = IOUtils.toString(inputStream, "UTF-8");
Map<String, Object> resultMap = wecomCallbackService.intelligentCallback(state, request);
WXBizMsgCrypt crypt = (WXBizMsgCrypt) resultMap.get("crypt");
WecomProvider provider = (WecomProvider) resultMap.get("provider");
String sReplyEchoStr = crypt.DecryptMsg(sMsg_signature, sTimestamp, SNonce, sReqData);
//解析xml数据
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(sReplyEchoStr);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Content");
String content = nodelist1.item(0).getTextContent();
//获取成员UserID
NodeList nodelist2 = root.getElementsByTagName("FromUserName");
String fromUserName = nodelist2.item(0).getTextContent();
String baiduRespMsg = "";
//企业微信发送消息不会有回应。之后在5s内,企业微信会幂等性的重试3次,所以需要加缓存
String resResult = redisManager.get("baiduGpt:" + content);
if (StrUtil.isEmpty(resResult)) {
baiduRespMsg = BaiduUtils.call_ERNIEBot(fromUserName, content);
redisManager.set("baiduGpt:" + content, baiduRespMsg);
} else {
baiduRespMsg = resResult;
}
log.info("AiManagerController call_ERNIE_Bot baiduRespMsg:{}", baiduRespMsg);
Calendar calendar = Calendar.getInstance();
long currentTime = calendar.getTimeInMillis();
//回复的消息
//拼装被动消息返回体
//生成xml 字符串
String xmlMsg = "<xml>\n" +
"<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
"<FromUserName><![CDATA[" + provider.getCorpId() + "]]></FromUserName>\n" +
"<CreateTime>" + currentTime / 1000 + "</CreateTime>\n" +
"<MsgType><![CDATA[text]]></MsgType>\n" +
"<Content><![CDATA[" + baiduRespMsg + "]]></Content>\n" +
"</xml>\n";
log.info("AiManagerController call_ERNIE_Bot xmlMsg =:{}", xmlMsg);
//加密返回
respMsg = crypt.EncryptMsg(xmlMsg, sTimestamp, SNonce);
//log.info("AiManagerController cryptUtil.EncryptMsg respMsg ={}", respMsg);
} catch (AesException e) {
log.error("AiManagerController getEntWXMsg err={}", e);
} catch (ParserConfigurationException e) {
log.error("AiManagerController getEntWXMsg err={}", e);
} catch (IOException e) {
log.error("AiManagerController getEntWXMsg err={}", e);
} catch (SAXException e) {
log.error("AiManagerController getEntWXMsg err={}", e);
}
return respMsg;
}
二、集成百度文心一言应用API
1、登录,自建模型应用,获取AK,SK。 https://console.bce.baidu.com/qianfan/aislconsole/applicationConsole/application
按照百度接口文档,开发相应API实现,调用API
package com.i84.interchanger.common.utils;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 类描述 : 百度工具
* </p>
*
* @author LDH
* @version 0.1
* @since 2023/4/20 16:15
*/
@Slf4j
public class BaiduUtils {
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
public static final String client_id = "jnGh******Gs";
public static final String client_secret = "jqn*********gp8I";
public static void main(String[] args) throws IOException {
String reuslt = BaiduUtils.call_ERNIEBot("fenglangx", "中国第一个皇帝");
System.out.println("resutl:" + reuslt);
}
/**
* @param content
* @throws IOException
*/
public static String call_ERNIEBot(String userId, String content) throws IOException {
String realUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + getAccessToken();
Map<String, String> heads = new HashMap<>();
heads.put("Content-Type", "application/json");
MediaType mediaType = MediaType.parse("application/json");
JSONObject jsonObject = new JSONObject();
JSONArray jsonArrayMessage = new JSONArray();
JSONObject jsonObjectMessage = new JSONObject();
jsonObjectMessage.set("role", "user");
jsonObjectMessage.set("content", content);
jsonArrayMessage.add(jsonObjectMessage);
jsonObject.set("messages", jsonArrayMessage);
RequestBody body = RequestBody.create(mediaType, jsonObject.toString());
Request request = new Request.Builder()
.url(realUrl)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String bodyStr = response.body().string();
bodyStr = bodyStr.replace("data:", "");
JSONObject j = JSONUtil.parseObj(bodyStr);
return j.getStr("result");
}
/**
* 从用户的AK,SK生成鉴权签名(Access Token)
*
* @return 鉴权签名(Access Token)
* @throws IOException IO异常
*/
static String getAccessToken() throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + client_id
+ "&client_secret=" + client_secret);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getStr("access_token");
}
}
三、最终实现效果:
0