Add User Via API

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Penguin
    Junior Member
    • May 2018
    • 28

    Add User Via API

    My PHP scripts to add user are working fine. No error whatsoever! But I don't get the user added even when I get 'User added' message and no error. I can clear the Local Cache but if I use the link in administration, I get 'Error 500: Error while clearing the cache'. WhenI click on Rebuild I get exactly same error. What is the problem? When I check in the EspoCRM error log, I get the following and I need help on that!
    [2018-08-21 09:25:07] Espo.WARNING: E_WARNING: unlink(data/cache/templates/note-post-email-subject.php): Permission denied {"code":2,"message":"unlink(data/cache/templates/note-post-email-subject.php): Permission denied","file":"/home/twashuka/public_html/timsonline/application/Espo/Core/Utils/File/Manager.php","line":587,"context":{"dirPath":"data/cache/templates","removeWithDir":true,"fileList":["note-post-email-body.php","note-post-email-subject.php"],"result":0,"file":"note-post-email-subject.php","fullPath":"data/cache/templates/note-post-email-subject.php"}} []
    [2018-08-21 09:25:07] Espo.ERROR: API [POST]:/Admin/clearCache, Params:Array ( ) , InputData: - Error while clearing cache [] []
    [2018-08-21 09:25:07] Espo.ERROR: Display Error: Error while clearing cache, Code: 500 URL: /timsonline/api/v1/Admin/clearCache [] []
    [2018-08-21 09:25:12] Espo.WARNING: E_WARNING: unlink(data/cache/templates/note-post-email-body.php): Permission denied {"code":2,"message":"unlink(data/cache/templates/note-post-email-body.php): Permission denied","file":"/home/twashuka/public_html/timsonline/application/Espo/Core/Utils/File/Manager.php","line":587,"context":{"dirPath":"data/cache/templates","removeWithDir":true,"fileList":["note-post-email-body.php","note-post-email-subject.php"],"result":true,"file":"note-post-email-body.php","fullPath":"data/cache/templates/note-post-email-body.php"}} []
    [2018-08-21 09:25:12] Espo.WARNING: E_WARNING: unlink(data/cache/templates/note-post-email-subject.php): Permission denied {"code":2,"message":"unlink(data/cache/templates/note-post-email-subject.php): Permission denied","file":"/home/twashuka/public_html/timsonline/application/Espo/Core/Utils/File/Manager.php","line":587,"context":{"dirPath":"data/cache/templates","removeWithDir":true,"fileList":["note-post-email-body.php","note-post-email-subject.php"],"result":0,"file":"note-post-email-subject.php","fullPath":"data/cache/templates/note-post-email-subject.php"}} []
    [2018-08-21 09:25:12] Espo.ERROR: API [POST]:/Admin/rebuild, Params:Array ( ) , InputData: - Error while clearing cache [] []
    [2018-08-21 09:25:12] Espo.ERROR: Display Error: Error while clearing cache, Code: 500 URL: /timsonline/api/v1/Admin/rebuild [] []

    Please senior programmers I need help... client will kill me!
  • tanya
    Senior Member
    • Jun 2014
    • 4308

    #2
    check the permission and the owner of data folder (and permission of the file data/cache/templates/note-post-email-subject.php)

    Comment

    • Penguin
      Junior Member
      • May 2018
      • 28

      #3
      Ok great... I will report back...

      Comment

      • Penguin
        Junior Member
        • May 2018
        • 28

        #4
        I will try my best... But if I may ask, who should be the rightful owner of that file? EspoCRM admin or OS admin or Apache2 (web server)?

        Comment

        • tanya
          Senior Member
          • Jun 2014
          • 4308

          #5
          web server user

          Comment

          • Penguin
            Junior Member
            • May 2018
            • 28

            #6
            Thanks great... will report back...

            Comment

            • Penguin
              Junior Member
              • May 2018
              • 28

              #7
              All the files and folders in my ESPOCRM DIR are owned by 'daemon' and group 'daemon'..... am using Cent OS 7.. and EspoCRM 5.3.5. I am still getting Error 500: and the same log errors as posted. I have the permissions properly set and even went as far as '777'. This file: data/cache/templates/note-post-email-subject.php is owned by daemon. My API does not produce any error when I run it but it does not insert any users at all. On my dev machine all works fine but on the server that aspect breaks. The rest of the system works fine except this component I am trying to add.

              Comment

              • Penguin
                Junior Member
                • May 2018
                • 28

                #8
                After tinkering with permissions here and there, the Error 500 has dissappeared... But my Script is not inserting users into the DB... the json payload is perfect. This same script is working fine on my windows dev machine but not working on the server... NO meaningful errors to debug with.

                Comment

                • Penguin
                  Junior Member
                  • May 2018
                  • 28

                  #9
                  below is the code for my API:

                  $postFields = json_encode(array(
                  'userName' => $_POST['userName'],
                  'firstName' => $_POST['firstName'],
                  'lastName' => $_POST['lastName'],
                  'password' => $_POST['password'],
                  'passwordConfirm' => $_POST['passwordConfirm'],
                  'isActive' => $_POST['isActive'],
                  'isAdmin' => $_POST['isAdmin'],
                  'defaultTeamId' => $_POST['defaultTeamId'])
                  );
                  echo $postFields;

                  $url = "http://twashuka.com/timsonline/api/v1/User";
                  $httpMethod = "POST";

                  $httpHeaders = [];
                  $httpHeaders['Authorization'] = 'Basic ' . base64_encode('admin:xxxxxxx2312');
                  $httpHeaders["Content-type"] = "application/json";

                  $curlOptions = array(
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => true,
                  CURLOPT_CUSTOMREQUEST => $httpMethod
                  );

                  $curlOptions[CURLOPT_POST] = true;
                  $curlOptions[CURLOPT_POSTFIELDS] = $postFields;
                  $curlOptions[CURLOPT_URL] = $url;

                  $curlOptHttpHeader = array();
                  foreach ($httpHeaders as $key => $value) {
                  $curlOptHttpHeader[] = "{$key}: {$value}";
                  }
                  $curlOptions[CURLOPT_HTTPHEADER] = $curlOptHttpHeader;

                  $ch = curl_init();
                  curl_setopt_array($ch, $curlOptions);

                  curl_setopt($ch, CURLOPT_HEADER, 1);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

                  $response = curl_exec($ch);

                  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                  $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
                  $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

                  $responceHeader = substr($response, 0, $headerSize);
                  $responceBody = substr($response, $headerSize);
                  $resultArray = null;

                  if ($curlError = curl_error($ch)) {
                  throw new Exception($curlError);
                  } else {
                  $resultArray = json_decode($responceBody, true);
                  }
                  curl_close($ch);

                  echo('User name Created.');

                  Comment

                  • Penguin
                    Junior Member
                    • May 2018
                    • 28

                    #10
                    Will apreciate your help

                    Comment

                    • Penguin
                      Junior Member
                      • May 2018
                      • 28

                      #11
                      I am also getting a <url>malformed error...:

                      [23-Aug-2018 10:55:52 UTC] PHP Fatal error: Uncaught exception 'Exception' with message '<url> malformed' in /home/twashuka/public_html/timsonline/api.php:57
                      Stack trace:
                      #0 {main}
                      thrown in /home/twashuka/public_html/timsonline/api.php on line 57

                      Comment

                      • Penguin
                        Junior Member
                        • May 2018
                        • 28

                        #12
                        that is from the error_log file

                        Comment

                        • Penguin
                          Junior Member
                          • May 2018
                          • 28

                          #13
                          My head is spinning... On my dev machine all is working seamlessly... All permissions are properly set... but fails to do the job on the production server.

                          Comment

                          • pavutinka
                            Junior Member
                            • Aug 2018
                            • 4

                            #14
                            in my callback page i use this code, i marked line where you need to change url, username and password

                            Code:
                            <html>
                            <head>
                            <meta charset="utf-8">
                            <link href='style.css' rel='stylesheet' type='text/css'>
                            </head>
                            <body>
                            <div class="container">
                            <?php
                            error_reporting(0);
                            $action=$_REQUEST['action'];
                            if ($action == "") /** display the contact form */
                            {
                            ?>
                            <form action ="" method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="submit">
                            <input name="name" type="text" value="" size="30" placeholder="Имя"/><br><br>
                            <input name="phone" type="text" value="" size="30" placeholder="Телефон"/><br><br>
                            <input name="email" type="text" value="" size="30" placeholder="E-mail"/><br><br>
                            <textarea name="message" rows="7" cols="30" placeholder="Сообщение"></textarea><br><br>
                            <input type="submit" value="Отправить"/>
                            </form>
                            <?php
                            }
                            else/* send the submitted data */
                            {
                            class EspoApiClient
                            {
                            private $url;
                            
                            private $userName;
                            
                            private $password;
                            
                            protected $urlPath = '/api/v1/';
                            
                            protected $userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36';
                            
                            private $lastCh;
                            
                            private $lastResponse;
                            
                            public function __construct($url = null, $userName = null, $password = null)
                            {
                            if (isset($url)) {
                            $this->url = $url;
                            }
                            
                            if (isset($userName)) {
                            $this->userName = $userName;
                            }
                            
                            if (isset($password)) {
                            $this->password = $password;
                            }
                            }
                            
                            public function setUrl($url)
                            {
                            $this->url = $url;
                            }
                            
                            public function setUserName($userName)
                            {
                            $this->userName = $userName;
                            }
                            
                            public function setPassword($password)
                            {
                            $this->password = $password;
                            }
                            
                            /**
                            * 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)
                            {
                            $method = strtoupper($method);
                            
                            $this->checkParams();
                            
                            $this->lastResponse = null;
                            $this->lastCh = null;
                            
                            $url = $this->normalizeUrl($action);
                            
                            $ch = curl_init($url);
                            
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            if ($this->userName) {
                            curl_setopt($ch, CURLOPT_USERPWD, $this->userName.':'.$this->password);
                            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                            }
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                            curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
                            curl_setopt($ch, CURLOPT_HEADER, true);
                            
                            if (isset($data)) {
                            if ($method == 'GET') {
                            curl_setopt($ch, CURLOPT_URL, $url. '?' . http_build_query($data));
                            } else {
                            $payload = json_encode($data);
                            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                            'Content-Type: application/json',
                            'Content-Length: ' . strlen($payload))
                            );
                            }
                            }
                            
                            $this->lastResponse = curl_exec($ch);
                            $this->lastCh = $ch;
                            
                            $parsedResponse = $this->parseResponce($this->lastResponse);
                            
                            if ($this->getResponseHttpCode() == 200 && !empty($parsedResponse['body'])) {
                            curl_close($ch);
                            return json_decode($parsedResponse['body'], true);
                            }
                            
                            $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, $this->getResponseHttpCode());
                            }
                            
                            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' => trim( substr($response, 0, $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;
                            }
                            }
                            
                            [I][U][B]$client = new EspoApiClient('<url of CRM>', '<user>', '<password>');[/B][/U][/I]
                            $response = $client->request('POST', 'Lead', [
                            'firstName' => $_REQUEST['name'],
                            'phoneNumber' => $_REQUEST['phone'],
                            'emailAddress' => $_REQUEST['email'],
                            'commentary' => $_REQUEST['message'],
                            'source' => 'Веб-сайт',
                            ]);
                            if ($response){
                            echo "Заявка успешно отправленна!<br>";
                            }else{
                            echo "Ошибка при отправке заявки, попробуйте еще раз.";
                            }
                            }
                            ?>
                            </div>
                            </body>
                            </html>
                            Last edited by pavutinka; 08-29-2018, 08:42 AM.

                            Comment

                            • Penguin
                              Junior Member
                              • May 2018
                              • 28

                              #15
                              Thanks a lot. I will give feedback...

                              Comment

                              Working...