<?php 
/*
腾讯AI鉴权DEMO
适用于POST方式鉴权
@梁永烨
2017年11月24日
*/

$ai = new AI();
$textChat = $ai->textChat('你的app_id','你的app_key','广州天气','你的session');
echo '<pre>';
var_dump($textChat);
echo '</pre>';


class AI
{

public function textChat($app_id,$app_key,$question,$session)
{
//请求参数
$signPackage = array(
"app_id"=>$app_id,
"time_stamp"=>time(),
"nonce_str"=>$this->createNonceStr(),
"session"=>$session,
"question"=>$question
);
//按键名字典升序排序
ksort($signPackage, SORT_STRING);
//键值url编码,并拼接成字符串
$tempArr = $this->array2string($signPackage);
//拼接app_key
$tempArr .= '&app_key='.$app_key;
//取得MD5值,并转化为大写
$sign = strtoupper(MD5($tempArr));
//请求参数加上sign
$post = $signPackage;
$post["sign"] = $sign;
//接口地址
$url = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat';
//发起请求
$response = $this->httpPost($url,$post);
//返回结果
return $response;
}

//生成16位随机字符串
private function createNonceStr($length = 16)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}

//拼接字符串,并对键值url编码
private function array2string($array)
{
$string = array();
if(isset($array) && is_array($array))
{
foreach($array as $key=>$val)
{
$string[] = $key.'='.urlencode($val);
}
}
$result = implode('&',$string);
return $result;
}

//curl请求
private function httpPost($url,$data) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}

}

腾讯AI的鉴权比较绕,很容易让新手蒙圈。

4096错误,参数非法

16388错误,请求签名无效

更多相关文章

  1. 查找具有特定数据字符串的数组并返回其具有的另一个数据字符串
  2. 在php中,从字符串中删除逗号后的所有内容
  3. 如何通过PHP将HTML页面作为字符串获取?
  4. php 基本的常用字符串函数
  5. 用PHP计算字符串中元音的简单方法?
  6. 将DOMDocument中的特定元素导出为字符串
  7. PHP实现字符串转换成查询语句
  8. mysql 判断null 和 空字符串
  9. mysql如何判断一个字符串是否包含另外一个字符串?

随机推荐

  1. Android安全机制(2) Android Permission权
  2. Android 匿名共享内存Java接口分析
  3. Android 安全机制(1)uid 、 gid 与 pid
  4. 无废话Android之android下junit测试框架
  5. 【雨松MOMO】Android 软件开发与游戏开发
  6. android通过NFC读取卡号
  7. Android帮助文档翻译——开发指南(一)应用
  8. Android调用系统摄像头--使用MediaRecord
  9. Android的Gradle插件
  10. Android Web应用高级编程:移动与嵌入式开