0

This is a piece of code that i`m using to post data via " API "

<?php

    curl_setopt_array($curl, array(
      CURLOPT_URL => "api.ewmjobsystem.com/third-party/add_job",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "license_key=***&customer_id=74&full_name=SystemTest&address=SystemTestAddress&site_address=SystemSiteAddress&short_description=SystemShortDescription&item_id=&item_name=SystemItemName&price=4.99&completion_date=25\04\2019",
      CURLOPT_HTTPHEADER => array(
        "content-type: application/x-www-form-urlencoded",
      ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
        ?>
        <?php
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
        echo $response;



    }
    ?>

now i can do everything i want with this code but there is one part of the API documentation which i do not understand. I can succesfully add everything up to " job products ". Could anyone point me to either good ( curl for dummies ) or maybe show me how i should post the data correctly. I had no idea how t ask the question so any necessary edits are welcomed

Sample Post looks like this

{  
   "license_key":"123456",
   "customer_id":"74",
   "full_name":"Jack",
   "email_address":"test@test.com",
   "telephone":"002125254",
   "mobile":"00787787",
   "address":"126 Unit ",
   "city":"Liverpool",
   "county":"MERSEYSIDE",
   "postcode":"CH41 1EP",
   "site_company_name":"Eworks",
   "site_full_name":"K V P",
   "site_telephone":"012121",
   "site_mobile":"0787878",
   "site_email_address":"site@test.com",
   "site_address":"127",
   "site_city":"Liverpool",
   "site_county":"MERSEYSIDE",
   "site_postcode":"CH41 1EP",
   "site_notes":"this is a site notes",
   "customer_ref":"12",
   "wo_ref":"34",
   "po_ref":"56",
   "completion_date":"25\/04\/2017",
   "short_description":"this is short desc",
   "description":"long desc",
   "customer_notes":"customer notes",
   "job_products":[  
      {  
         "item_id":"221",
         "item_name":"TEST:SMOKE OR PRESSURE TEST",
         "item_code":"039018",
         "item_description":"Test:Carry out smoke or pressure test.",
         "cost_price":"21.09",
         "price":"32.44"
      },
      {  
         "item_id":"255",
         "item_name":"WALL:DEMOLISH EXTERNAL WALL",
         "item_code":"101101",
         "item_description":"Wall:Take down external half brick wall and remove spoil.",
         "cost_price":"12.58",
         "price":"19.35"
      }
   ]
}        

So i have finally got some example files off them ( when told them i will cancel £150 a month im paying them ) and they have sent me this as an example but still doesnt work Server Error: 500 (Internal Server Error)

example1.php

error_reporting(E_ALL);

include_once('includes.php');

$licence_key = '***'; //Your Licence Key here

//getting the customers
//$response = postRequest($licence_key, 'get_customers');
//print_r($response);

//Add Job
$job_products = [
    [
        "item_id"           => "",
        "item_name"         => "Product A",
        "item_code"         => "039018",
        "item_description"  => "Test:Carry out smoke or pressure test.",
        "cost_price"        => "21.09",
        "price"             => "32.44"
    ],
    [
        "item_id"           => "",
        "item_name"         => "Product B",
        "item_code"         => "039018",
        "item_description"  => "Test:Carry out smoke or pressure test.",
        "cost_price"        => "10",
        "price"             => "50"
    ]
];

$data = [
    'completion_date'       =>  '31/03/2019',
    'customer_id'           =>  1,
    'full_name'             =>  'Full Name',
    'email_address'         =>  'email@email.com',
    'telephone'             =>  '012122212',
    'mobile'                =>  '0787878',
    'address'               =>  'Line 1 address'.chr(10).'Line 2 address',
    'city'                  =>  'City',
    'county'                =>  'County',
    'postcode'              =>  'Postcode',
    'site_company_name'     =>  'Site Company Name',
    'site_full_name'        =>  'Site Contact Name',
    'site_telephone'        =>  '012121212',
    'site_mobile'           =>  '07878787',
    'site_fax'              =>  'Depreciated, not in use',
    'site_email_address'    =>  'email@email.com',
    'site_address'          =>  'Site Line 1 address'.chr(10).'Line 2 address',
    'site_city'             =>  'Site City',
    'site_county'           =>  'Site County',
    'site_postcode'         =>  'Site Postcode',
    'site_notes'            =>  'Site Notes',
    'customer_ref'          =>  'Customer Ref',
    'wo_ref'                =>  'Customer Job Ref',
    'po_ref'                =>  'PO Ref',
    'short_description'     =>  'short description of job',
    'description'           =>  'long description of job',
    'customer_notes'        =>  'Customer notes',
    'job_products'          =>  json_encode($job_products)
];

$response = postRequest($licence_key, 'add_job', $data);
print_r($response);

and includes.php

function postRequest($license_key, $method, $data = []){
    $url                = 'http://api.ewmjobsystem.com/third-party/'; 
    $post_string        = '';

    $data['license_key'] = $license_key;    

    $ch = curl_init(); 

    if(is_array($data) && count($data) > 0){
        $post_string = http_build_query($data);
        curl_setopt($ch, CURLOPT_POST, count($data)); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); 
    }

    curl_setopt($ch, CURLOPT_URL, $url.$method); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Eworks Manager Client API"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // this line makes it work under https 

    $response = curl_exec($ch); 
    curl_close($ch);

    return $response;
}
  • 1
    Can you be more specific what you are trying to accomplish? You mention that this does everything you want it to. What is the question, exactly? – tshimkus Feb 16 '19 at 11:13
  • right, so you have the sample post how it should look like so i have `CURLOPT_POSTFIELDS => "license_key=***&customer_id=74&full_name=SystemTest&address=SystemTestAddress&site_address=SystemSiteAddress&short_description=SystemShortDescription&item_id=&item_name=SystemItemName&price=4.99&completion_date=25\04\2019",` but its not adding anything under job_products – Marek Prymula Feb 16 '19 at 12:45
  • is the `CURLOPT_POSTFIELDS` formatted correctly in order to populate `job_products` – Marek Prymula Feb 16 '19 at 12:48
  • So it doesn't work? This depends on the specs of your API. What kind of format is it expecting in the request? – tshimkus Feb 16 '19 at 12:49
  • @tshimkus so it will add everything up to `job_products` – Marek Prymula Feb 16 '19 at 12:50
  • so in `CURLOPT_POSTFIELDS` i have `license_key=***&customer_id=74` question is how should i approach the `job_products` just by adding `&item_id=22&item_name=something` or i need to specify `job_products` – Marek Prymula Feb 16 '19 at 12:53
  • I get that, but it may not be the right way to post data to this API. I can't find a spec so I don't know what kind of input is required to update `job_products`. It might be expecting header data or JSON or XML. It's hard to say what's not working if we don't know how it is supposed to work – tshimkus Feb 16 '19 at 12:54
  • the way i understand it, it would need to look something like this `&job_products={item_id=2&item_name=name}` – Marek Prymula Feb 16 '19 at 12:55
  • @tshimkus here is the [Poor API Documentation](http://api.ewmjobsystem.com/api_doc.php) they had provided me with if that helps – Marek Prymula Feb 16 '19 at 12:56
  • I thought I have seen some bad API docs in the past but these are really bad. They don't specify anything about what the request should look like. I'm going to recommend talking directly with their support team to understand how to actually post something to this API. – tshimkus Feb 16 '19 at 13:01
  • From the looks of it you might need to post JSON and not a query string. See: https://stackoverflow.com/questions/4271621/php-curl-post-json – tshimkus Feb 16 '19 at 13:12
  • @tshimkus, i had a chat with their **Development Department** and did ask them for example which they dont have and when i asked for the copy of the api_doc.php because obiviously it contains all the necessary requests they said " NO " and getting any information of them is impossible because of ** Language barrier** – Marek Prymula Feb 16 '19 at 13:25

1 Answers1

0

put all the data in a php array, and simply encode it to json with json_encode(), like this:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
    'license_key' => '123456',
    'customer_id' => '74',
    'full_name' => 'Jack',
    'email_address' => 'test@test.com',
    'telephone' => '002125254',
    'mobile' => '00787787',
    'address' => '126 Unit ',
    'city' => 'Liverpool',
    'county' => 'MERSEYSIDE',
    'postcode' => 'CH41 1EP',
    'site_company_name' => 'Eworks',
    'site_full_name' => 'K V P',
    'site_telephone' => '012121',
    'site_mobile' => '0787878',
    'site_email_address' => 'site@test.com',
    'site_address' => '127',
    'site_city' => 'Liverpool',
    'site_county' => 'MERSEYSIDE',
    'site_postcode' => 'CH41 1EP',
    'site_notes' => 'this is a site notes',
    'customer_ref' => '12',
    'wo_ref' => '34',
    'po_ref' => '56',
    'completion_date' => '25/04/2017',
    'short_description' => 'this is short desc',
    'description' => 'long desc',
    'customer_notes' => 'customer notes',
    'job_products' => array(
        array(
            'item_id' => '221',
            'item_name' => 'TEST:SMOKE OR PRESSURE TEST',
            'item_code' => '039018',
            'item_description' => 'Test:Carry out smoke or pressure test.',
            'cost_price' => '21.09',
            'price' => '32.44',
        ),
        array(
            'item_id' => '255',
            'item_name' => 'WALL:DEMOLISH EXTERNAL WALL',
            'item_code' => '101101',
            'item_description' => 'Wall:Take down external half brick wall and remove spoil.',
            'cost_price' => '12.58',
            'price' => '19.35',
        ),
    ),
)));

job_products specifically is an array of arrays of data (or when represented as JSON, it's an array of objects containing data)

the source code was generated with this script:

<?php

$json=<<<'JSON'
PUT YOUR JSON HERE
JSON;
$data=json_decode($json,true);
$php_source_code=var_export($data,true);
echo $php_source_code;

and by the way, going by your sample date, you're submitting JSON, not application/x-www-form-urlencoded , so this is wrong:

  CURLOPT_HTTPHEADER => array(
        "content-type: application/x-www-form-urlencoded",
      )

it should actually read

  CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
      )

(and for the record, IF you actually waned to send the data in application/x-www-form-urlencoded-format, the solution would still be the same, but you'd have to use http_build_query(array(...)) instead of json_encode(array(...)) )

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • after using your code it doesnt see my license key and throws `{"status":0,"auth_failed":1,"method":"add_job","message":"Sorry, license key not found.","data":[]}` key is there – Marek Prymula Feb 16 '19 at 19:50
  • @MarekPrymula .. where is the API documentation? – hanshenrik Feb 16 '19 at 20:40
  • @MarekPrymula what happens if you get rid of CURLOPT_HTTPHEADER entierly and just let curl set the headers, and replace `json_encode(...)` with `http_build_query(...)` ? – hanshenrik Feb 16 '19 at 20:43
  • how should my file look right now ? maybe im doing something wrong – Marek Prymula Feb 17 '19 at 08:02
  • @MarekPrymula that API documentation is sorely lacking, they say they support HTTP GET and POST requests, but they don't say what format the POST formats should be. should they be in `application/x-www-form-urlencoded` format? or should they be in `Multipart/form-data`-format? or should they be in `application/json`-format? the API documentation doesn't say.. i would ask and then complain to their customer support service about the lacking information in their API documentation. ask CS what format their HTTP POST requests should be in – hanshenrik Feb 17 '19 at 09:11
  • they are useless, i have spoken with them before i have started doing anything and ive been told " you make the calls like you make with any API " i did ask them for the copy of api_doc.php ( it contains all the necessary calls etc ) but they refused. I did succedd with POST for everything apart from the job_products array. I will call the min the morning and tell them if no support will be provided i will just cancel £150pm im paying them for system thats useless anyway – Marek Prymula Feb 17 '19 at 09:19
  • @MarekPrymula well i sent them an email asking, see https://i.imgur.com/cIeyg1w.png - but you could just try all 3, if you followed my instructions then you have already tried the `application/json`-format. then you can try `application/x-www-form-urlencoded` format, and `multipart/form-data` format, those 3 are the standard ones. – hanshenrik Feb 17 '19 at 09:21
  • wonderful, we have an account with them so ill be able to ask the question and get the answer over the phone from their **technical department**. In the meantime the answer you have submitted, is it the complete code or just partial and i should merge it with the one i already have ? thank you for your help – Marek Prymula Feb 17 '19 at 09:35
  • @MarekPrymula .. it's not the complete code, it's only the code needed to set CURLOPT_POSTFIELDS for the `application/json`-format (which is 1 of 3 standard formats, `application/json`, and `application/x-www-form-urlencoded`, and `multipart/form-data` ) – hanshenrik Feb 17 '19 at 09:41
  • May i ask a stupid question. I have made a variable with your array called `$data` and and did json for it `$data_string = json_encode($data); ` now when i do `echo $datastring;` it seperates the key and value by `:` not by `=` ... i mean i dont know just wanted to check because when i had it this way `CURLOPT_POSTFIELDS => "license_key=***&customer_id=74&full_name=SystemTest&address=SystemTestAddress&site_address=SystemSiteAddress&short_description=SystemShortDescription&item_id=&item_name=SystemItemName&price=4.99&completion_date=25\04\2019",` it did work – Marek Prymula Feb 17 '19 at 10:13
  • oh and `Content-Type: multipart/form-data` comes back with **Server Error: 500 (Internal Server Error)** – Marek Prymula Feb 17 '19 at 10:56
  • my first code works fine but it doesnt add anything to `job_products` and this is the response i get `{"status":1,"auth_failed":0,"method":"add_job","message":"Job added","data":{"job_id":23,"job_items":[],"appointments":[],"job_ref":"JOB-0020","customer_id":"74","project_id":null,"status":1}}` – Marek Prymula Feb 17 '19 at 11:16
  • I have updated my Answer with example file they have provided me with – Marek Prymula Feb 21 '19 at 11:17