本来聊天机器人是前端POST提交给图灵的API,但是这样一来key直接暴露,二来网站https了不能请求http了,所以就用我不成熟的PHP整合了下。

后台:

  1. <?php
  2. //获得聊天
  3. $appkey = '这里填写APIKey';
  4. $talkContent = "";
  5. $info=addslashes($_POST['info']);
  6. $userid=addslashes($_POST['userid']);
  7. function send_post($url, $post_data) {
  8. $postdata = http_build_query($post_data);
  9. $options = array(
  10. 'http' => array(
  11. 'method' => 'POST',
  12. 'header' => 'Content-type:application/x-www-form-urlencoded',
  13. 'content' => $postdata,
  14. 'timeout' => 15 * 60 // 超时时间(单位:s)
  15. )
  16. );
  17. $context = stream_context_create($options);
  18. $result = file_get_contents($url, false, $context);
  19. return $result;
  20. }
  21. //使用方法
  22. $post_data = array(
  23. 'key' => $appkey,
  24. 'info' => $info,
  25. 'userid' => $userid,
  26. );
  27. if($appkey==""){
  28. $talkContent = '{"code":"500","text":"我还没学会聊天功能,快和站长联系吧!"}';
  29. }
  30. else{
  31. $talkContent = send_post('http://www.tuling123.com/openapi/api', $post_data);
  32. }
  33. header('Content-type:text/json');
  34. echo $talkContent;
  35. ?>


前端:
  1. jQuery.ajax({
  2. type: 'POST',
  3. url: 'ajax_talk.php',
  4. data: {
  5. 'info': '聊天内容',
  6. 'userid': '用户称呼',
  7. },
  8. success: function(res) {
  9.  
  10. }
  11. });