Tencent AI authentication demo (PHP version)

<?php
/*
Tencent AI authentication DEMO
Applicable to POST authentication
@Liang Yongye
November 24, 2017
*/

$ ai = new AI ();
$textChat = $ai->textChat('your app_id','your app_key','Guangzhou weather','your session');
echo '<pre>';
  var_dump($textChat);
echo '</pre>';


class AI
{
  
  public function textChat($app_id,$app_key,$question,$session)
  {
    // request parameters
    $signPackage = array(
      "app_id"=>$app_id,
      "time_stamp"=>time(),
      "nonce_str"=>$this->createNonceStr(),
      "session"=>$session,
      "question"=>$question
    );
    // sort by key name dictionary in ascending order    
    ksort($signPackage, SORT_STRING);
    //Key-value url encoding and splicing into a string
    $tempArr = $this->array2string($signPackage);
    //splicing app_key
    $tempArr .= '&app_key='.$app_key;
    //Get the MD5 value and convert it to uppercase
    $sign = strtoupper(MD5($tempArr));
    //Request parameter plus sign
    $post = $signPackage;
    $post["sign"] = $sign;
    //interface address
    $url = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat';
    //Initiate request
    $response = $this->httpPost($url,$post);
    //return result
    return $response;
  }
 
  //Generate 16-bit random string
  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;
  }  
  
  // Concatenate strings and encode the key value 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 request
  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;
    }   
    
}

Tencent AI's authentication is relatively complicated, and it is easy to confuse newbies.

4096 error, illegal parameter

16388 Error, invalid request signature

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325833005&siteId=291194637