腾讯AI鉴权demo(PHP版)

<?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错误,请求签名无效

猜你喜欢

转载自blog.csdn.net/gdali/article/details/78622607