Announcement

Collapse
No announcement yet.

class EspoApiClient problem

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • class EspoApiClient problem

    Hi all,

    I need help with this script, I was using it a long time ago.

    After the upgrade from 7.5.5 of the Espocrm, to 8.x, my API, which was using this script, doesn't work anymore.

    I don't find any tutorials that are working or helping me with this problem.

    I tried to install the composer with Require Espo... but I think I didn't succeed in installing and making it work...

    I was using this script to take data from the CRM, and i was working with data. In my browser, a simple url like ".../api/v1/Invoices" is working, but when is my second virtual server try to take data , it doesn't work.

    It can be my .htaccess or something with my apache config too...

    My error is :​
    Code:
    [B]Fatal error[/B]: Uncaught Exception: EspoClient: Unknown Error in /mnt/data/www/html/billManager/EspoApiClient.php:150 Stack trace: #0​
    My php script wich was working

    PHP Code:
    <?php

    class EspoApiClient
    {
    private 
    $url;

    private 
    $userName null;

    private 
    $password null;

    protected 
    $urlPath '/api/v1/';

    private 
    $lastCh;

    private 
    $lastResponse;

    private 
    $apiKey null;

    private 
    $secretKey null;

    public function 
    __construct($url null$userName null$password null)
    {
    if (isset(
    $url)) {
    $this->url $url;
    //echo '<br> Url: '.$url;
    }
    if (isset(
    $userName)) {
    $this->userName $userName;
    }
    if (isset(
    $password)) {
    $this->password $password;
    }
    }

    public function 
    setUrl($url)
    {
    $this->url $url;
    //echo '<br> Url: '.$url;
    }

    public function 
    setUserName($userName)
    {
    $this->userName $userName;
    //echo '<br> Username: '.$userName;
    }

    public function 
    setPassword($password)
    {
    $this->password $password;
    }

    public function 
    setApiKey($apiKey)
    {
    $this->apiKey $apiKey;
    //echo '<br> ApiKey: '.$apiKey;
    }

    public function 
    setSecretKey($secretKey)
    {
    $this->secretKey $secretKey;
    }

    /**
    * Send request to EspoCRM
    *
    * @param string $method
    * @param string $action
    * @param array|null $data
    *
    * @return array | \Exception
    */
    public function request($method$action, array $data null)
    {
    //echo '<br>'.$method.' - '.$action;

    $method strtoupper($method);

    $this->checkParams();

    $this->lastResponse null;
    $this->lastCh null;

    $url $this->normalizeUrl($action);

    $ch curl_init($url);

    $headerList = [];

    curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
    if (
    $this->userName && $this->password) {
    curl_setopt($chCURLOPT_USERPWD$this->userName.':'.$this->password);
    curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_BASIC);
    } else if (
    $this->apiKey && $this->secretKey) {
    $string $method ' /' $action;
    $authPart base64_encode($this->apiKey ':' hash_hmac('sha256'$string$this->secretKeytrue));
    $authHeader 'X-Hmac-Authorization: ' $authPart;
    $headerList[] = $authHeader;
    } else if (
    $this->apiKey) {
    $authHeader 'X-Api-Key: ' $this->apiKey;
    $headerList[] = $authHeader;
    }

    curl_setopt($chCURLOPT_SSL_VERIFYPEERtrue);
    curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
    curl_setopt($chCURLOPT_HEADERtrue);

    if (
    $method != 'GET') {
    curl_setopt($chCURLOPT_CUSTOMREQUEST$method);
    }

    if (isset(
    $data)) {
    if (
    $method == 'GET') {
    curl_setopt($chCURLOPT_URL$url'?' http_build_query($data));
    } else {
    $payload json_encode($data);
    curl_setopt($chCURLOPT_POSTFIELDS$payload);
    $headerList[] = 'Content-Type: application/json';
    $headerList[] = 'Content-Length: ' strlen($payload);
    }
    }

    if (!empty(
    $headerList)) {
    curl_setopt($chCURLOPT_HTTPHEADER$headerList);
    }

    $this->lastResponse curl_exec($ch);
    $this->lastCh $ch;

    $parsedResponse $this->parseResponce($this->lastResponse);
    $responseCode $this->getResponseHttpCode();
    $responseContentType $this->getResponseContentType();

    if (
    $responseCode == 200 && !empty($parsedResponse['body'])) {
    curl_close($ch);

    if (
    $responseContentType === 'application/json') {
    return 
    json_decode($parsedResponse['body'], true);
    }

    return 
    $parsedResponse['body'];
    }

    $header $this->normalizeHeader($parsedResponse['header']);
    $errorMessage = !empty($header['X-Status-Reason']) ? $header['X-Status-Reason'] : 'EspoClient: Unknown Error';

    curl_close($ch);
    throw new 
    \Exception($errorMessage$responseCode);
    }

    public function 
    getResponseContentType()
    {
    return 
    $this->getInfo(CURLINFO_CONTENT_TYPE);
    }

    public function 
    getResponseTotalTime()
    {
    return 
    $this->getInfo(CURLINFO_TOTAL_TIME);
    }

    public function 
    getResponseHttpCode()
    {
    return 
    $this->getInfo(CURLINFO_HTTP_CODE);
    }

    protected function 
    normalizeUrl($action)
    {
    return 
    $this->url $this->urlPath $action;
    }

    protected function 
    checkParams()
    {
    $paramList = [
    'url'
    ];

    foreach (
    $paramList as $name) {
    if (empty(
    $this->$name)) {
    throw new 
    \Exception('EspoClient: Parameter "'.$name.'" is not defined.');
    }
    }

    return 
    true;
    }

    protected function 
    getInfo($option)
    {
    if (isset(
    $this->lastCh)) {
    return 
    curl_getinfo($this->lastCh$option);
    }
    }

    protected function 
    parseResponce($response)
    {
    $headerSize $this->getInfo(CURLINFO_HEADER_SIZE);

    return [
    'header' => trimsubstr($response0$headerSize) ),
    'body' => substr($response$headerSize),
    ];
    }

    protected function 
    normalizeHeader($header)
    {
    preg_match_all('/(.*): (.*)\r\n/'$header$matches);

    $headerArray = array();
    foreach (
    $matches[1] as $index => $name) {
    if (isset(
    $matches[2][$index])) {
    $headerArray[$name] = trim($matches[2][$index]);
    }
    }

    return 
    $headerArray;
    }
    }
    ?>
    An example how i was using it for post:

    PHP Code:
    $response $client->request('POST''Invoice', [
            
    'name' => htmlspecialchars($_POST['name']),
            
    'receiveAmount' => htmlspecialchars($_POST['amount']),
            
    'description' => htmlspecialchars($_POST['description']),
            
    'incomeOutcome' => $incomeOutcome,
            
    'accountId' => htmlspecialchars($accountChoise),
            
    'financialPlanID' => $planID,
            
    'createdAt' => date('Y-m-d'),
            
    'dateInvoiced' => date_format($date'Y-m-d'),
        ]);
    ​ 
    An example how i was using it for get:
    PHP Code:
        $requestAccountParams = [
        
    'select' => 'id,name'
        
    'orderBy' => 'name',
        
    'order' => 'asc',];

        
    listSelected ($client->request('GET''Account',$requestAccountParams),$_SESSION['UserData']['account'], "account");​ 

    Thank you for helping me

  • #2
    Anything in Espo log related to failed API requests?

    Comment


    • #3
      Thank you for your answer, yurl.

      The logs are empty. I'm trying multiple ways, but I get an error 500, 403, 404 sometimes. The cause is the update, but I don't understand where the problem is.

      Comment


      • #4
        Nobody can help? its important for my accounting system...

        Comment


        • #5
          This likely not related with EspoCRM upgrade. Maybe the problem with the server that makes requests. Such issues usually require investigation that usually programmers quickly solve. It's hard to help through the forum.

          I'm not able to provide help here. I have too much work, all issues have to resolve on my own. Need to take a break from the forum, it's been too much last days.

          Comment


          • #6
            Thank you Yuri, i will try till i solve it, i will check all htacess etc... and network connection

            Comment


            • #7
              PHP Code:
              [php:error] [pid 488276] [client 192.168.188.36:58543PHP Fatal error:  Uncaught Espo\\ApiClient\\Exception\\ErrorCURL exec failurein /vendor/espocrm/php-espo-api-client/src/Client.php:200\nStack trace:\n#0 /testAPI1.php(20): Espo\\ApiClient\\Client->request()\n#1 {main}\n  thrown in /vendor/espocrm/php-espo-api-client/src/Client.php on line 200 
              Hi all, is all i can found in the apache logs...

              Comment


              • #8
                curl_exec​ returned false. It can be a SSL certificate issue on your server. I recommend googling "curl_exec​ returned false".

                Comment


                • #9
                  Thank you Yuri, i tryed to check the SSL stuff, i did with don't checking the SSL in the CURL, but still dont work....

                  i dont understand why in my browser is working and when i use a sctip PHP, i get the error...

                  when i delete cookies, is asking me the user and password, after is working well, but don't work in the php script...

                  all of this happen after upgrading my Espocrm, and my server software (apt-get upgrade)...

                  Thank for your help

                  Comment


                  • #10
                    i found a new files in /public folder, is the web.config
                    PHP Code:
                    <?xml version="1.0" encoding="UTF-8"?>
                    <configuration>
                        <system.webServer>
                            <defaultDocument>
                                <files>
                                    <clear />
                                    <add value="index.php" />
                                    <add value="index.html" />
                                </files>
                            </defaultDocument>
                            <security>
                                <requestFiltering>
                                    <verbs allowUnlisted="false">
                                        <add verb="GET" allowed="true" />
                                        <add verb="POST" allowed="true" />
                                        <add verb="PUT" allowed="true" />
                                        <add verb="PATCH" allowed="true" />
                                        <add verb="DELETE" allowed="true" />
                                    </verbs>
                                </requestFiltering>
                            </security>
                            <rewrite>
                                <rules>
                                    <rule name="rule 1G" stopProcessing="true">
                                        <match url="^api/v1/portal-access/(.*)$" />
                                        <action type="Rewrite" url="api/v1/portal-access/index.php" appendQueryString="true" />
                                    </rule>
                                    <rule name="rule 2G" stopProcessing="true">
                                        <match url="^api/v1/(.*)$" />
                                        <action type="Rewrite" url="api/v1/index.php" appendQueryString="true" />
                                    </rule>
                                    <rule name="rule 3G" stopProcessing="true">
                                        <match url="^portal/(.*)$" />
                                        <action type="Rewrite" url="portal/index.php" appendQueryString="true" />
                                    </rule>
                                </rules>
                            </rewrite>
                            <staticContent>
                                <mimeMap fileExtension=".tpl" mimeType="text/plain" />
                            </staticContent>
                        </system.webServer>
                    </configuration>
                    It is possible this files broke my connection?

                    Comment


                    • #11
                      can i get some support from some dev's? please

                      Comment


                      • #12
                        My error come from the Curl... the curl_init() don't work, i have everything installed, and enable and nothing work.... is really weird this problem...
                        I took the original script for testing.
                        PHP Code:
                            $ch curl_init("http://www.example.com/");
                        $fp fopen("example_homepage.txt""w");

                        curl_setopt($chCURLOPT_FILE$fp);
                        curl_setopt($chCURLOPT_HEADER0);

                        curl_exec($ch);
                        if(
                        curl_error($ch)) {
                            
                        fwrite($fpcurl_error($ch));
                        }
                        curl_close($ch);
                        fclose($fp);​ 
                        This script dont work....
                        Last edited by VVillStone; 11-13-2023, 11:31 AM.

                        Comment

                        Working...
                        X