Date | Description |
24-Sep-2013 | Initial draft |
19-Oct-2013 | Major update |
05-Dec-2013 | Examples and fixes |
06-Jan-2014 | Updates, new functions |
08-Jan-2014 | Indicator for toggles |
13-Jan-2014 | Update company & post |
14-Mar-2014 | New image functions, rawpages > rawpagesnew, deleted rawvotes |
02-Apr-2014 | Fix bug in example, remove trailing slashes, statuscodes |
07-May-2014 | Remove landing, add full images/logos/covers |
23-Jun-2014 | Add multi-language abouttexts and isWebshop, removed know-from |
02-Jul-2014 | Add rawemployees function, fix typos |
07-Aug-2014 | Fix typos |
27-Aug-2014 | Fix documentation for opening hours (company) |
19-Okt-2014 | Add new output to various functions, i.e. files at messages and more |
05-Jan-2015 | Update rawcompany with type and retail-group |
13-Apr-2015 | Update chain-types (new set), update rawvalidate, rawpagesnew, and rawpost (new data added), add rawswitch and rawevents (new) |
See the end of this document for an example of an API call procedure in PHP code.
All returned status codes are standard HTTP 1.1 codes. The below ones are used in this API.
2XX - Success of some kind
4XX - Error occurred in client’s part
5XX - Error occurred in server’s part
Status Code | Description |
200 | OK (success) |
400 | Bad Request (non-existing action) |
401 | Unauthorized (no/invalid authentication) |
403 | Forbidden (illegal action) |
404 | Resource Not Found (the URL is completely wrong or a required parameter is missing) |
405 | Method Not Allowed (wrong request method, e.g. GET/POST) |
500 | Internal Server Error (contact us!) |
502/503/504 | Bad Gateway / Service Unavailable / Gateway Timeout (servers are down, network malfunction, DOS protection, ..) |
Authenticate with the system and obtain a token. This token can be used indefinitely right now. Please logout (see function 2) if this token will no longer be used.
Method | URL |
POST | menu?action=rawlogin |
Params | Values |
token | string string |
mail indicates the full email-address of the main account of the CHAINels company wanting to authenticate itself.
token
token is used for the user’s password here; in all subsequent requests, the token retrieved with this action should be used instead for any token parameter.
Response |
{ "stat": <boolean> "msg": <string> } stat - Indicates the success of the action. msg - If stat is true, this contains the generated token for use in all subsequent requests. If stat is false, this contains a message reporting on the failure. |
Deauthenticate with the system. All further uses of the given token will be blocked. Please do this at all times when a token will no longer be used. Disposing or refreshing a token frequently is recommended for security reasons.
Method | URL |
POST | menu?action=rawlogout |
Params | Values |
token | string |
token
the current session token as retrieved by a login-action.
Response |
{ "stat": <boolean> "msg": <string> } stat - Indicates the success of the action. msg - If stat is false, this contains a message reporting on the failure. If stat is true, this field is not set. |
Validate the authentication with the system.
Method | URL |
GET | menu?action=rawvalidate |
Params | Values |
token | string |
token
the current session token as retrieved by a login-action.
Response |
{ "stat": <boolean> "msg": <mixed> } stat - True if the token was valid; false otherwise. msg - If stat is false, this contains a message reporting on why the token is not valid. If stat is true, this contains an array of the following form: CID - The unique ID of the user’s (current) company. name - The name of the user’s (current) company. group - 1 if the user’s (current) company is a group; 0 otherwise. companies - A key->value array of name->company ID, indicating the set of companies that this account is managing (e.g. can switch to). rights - A number indicating the right level of the account (currently not company-dependent): 1 (manager), 2 (profile editor), 3 (spectator). |
Method | URL |
GET | menu?action=rawswitch |
Params | Values |
token | string |
CID | string |
Response |
None (status-codes only) |
Fetch all chains (connections) of a company.
Method | URL |
GET | chain?action=rawchains |
Params | Values |
token | string |
CID [optional] | string |
token
the current session token as retrieved by a login-action.
CID
the CID of the company requesting the chains for. If left empty, the company belonging to the current session’s account will be used.
Response |
[ { "id": <string> "type": <integer> "cid": <string> "name": <string> "logo": <string> "fullLogo": <string> }, ... ] The result is an array of zero or more objects with the following data: id - The unique identifier of the chain (18 chars: ‘21’ followed by a timestamp). type - The type of the chain. 1: member, 2: partner. cid - The unique identifier of the ‘other’ company in the chain (18 chars; ‘11’ followed by a timestamp). name - The name of the ‘other’ company in the chain (2-50 chars). logo - The URL to the thumb-sized logo (64px) of the ‘other’ company. fullLogo - The URL to the thumb-sized logo (original source) of the ‘other’ company. |
Fetch the static information of a company.
Method | URL |
GET | company?action=rawcompany |
Params | Values |
token | string |
CID [optional] | string |
token
the current session token as retrieved by a login-action.
CID
the CID of the company requesting the information for. If left empty, the company belonging to the current session’s account will be used.
Response |
{ "ID": <string> "name": <string> "industryKey": <string> "industryLabel": <string> "status": <integer> "isGroup": <boolean> "termsStamp": <integer> "logo": <string> "logoSmall": <string> "fullLogo": <string> "fullLogoSmall": <string> "size": <string> "aLong": <string> "aLongFull": <array> "miss": <string> "year": <integer> "COC": <integer> "hours": <array> "sName": <string> "sNum": <string> "zip": <string> "state": <string> "city": <string> "country": <string> "geohash": <string> "lat": <float> "long": <float> "phone": <string> "web": <string> "shop": <integer> "mail": <string> "sector": <string> "branch": <string> "type": <string> "typeName": <string> "retailKey": <string> "retailName": <string> } ID - The unique identifier of the company (18 chars; ‘11’ followed by a timestamp). name - The full name of the company (2-50 chars). industryKey - A 2 char key indicating the main industry of the company. industryLabel - A 2-3 char key indicating indicating the specific (sub)industry of the company. status - The status of the company. 1: new, 2: completed signup step 1, 3: completed signup step 2, 4: completed signup, 5: has a logo and an abouttext, 6: has filled in all possible fields (the fields returned in this object). isGroup - When true, the company is a group. termsStamp - A Unix timestamp (in seconds) of when the company accepted the terms of use. If this value is empty (0), the company has not been active on CHAINels yet. logo - The URL to the full-sized logo (400px) of the company. logoSmall - The URL to the thumb-sized logo (64px) of the company. fullLogo - The URL to the full-sized logo (original source) of the company. fullLogoSmall - The URL to the thumb-sized logo (original source) of the company. size - A small text indicating the size of the company (‘2-5’ in example; possibly empty). aLong - A text that gives information about the company itself (0-5000 chars), preferably in the requesting account’s language (takes first available language otherwise). aLongFull - A key->value array: languageKey->text that gives information about the company itself (0-5000 chars). The current possible languages are: ‘NL’, ‘EN’, and ‘DE’. miss - A text that indicates the mission of the company (0-500 chars). year - The year in which the company was founded (0 or 4 chars). COC - The Chamber of Commerce number of the company (validated; possibly empty). hours - A key-value array in the following format: array($day=>array(timeFrom=>string,timeTimo=>string), ...). All values are optional. sName - The street name in the address of the company (3-100 chars). sNume - The street number in the address of the company (1-20 chars). zip - The zip code in the address of the company (validated; possibly empty). state - The state in the address of the company (validated). city - The name of the city in the address of the company (1-100 chars). country - A standard 2-character key for the country in the address of the company. geohash - The geohash indicating the location of the company. lat - The latitude of the company’s location (0.1 for an invalid address). long - The longitude of the company’s location (0.1 for an invalid address). phone - The phone number of the company (validated; possibly empty). web - The website of the company (validated; possibly empty). shop - 1 if the company’s website is/has a webshop (user-indicated); 0 otherwise. mail - The e-mailaddress of the company (validated; possibly empty). sector - A full string indicating the sector of the company (based on the industryKey, dependent on the current account’s language) branch - A full string indicating the branch of the company (based on the industryLabel, dependent on the current account’s language) type - A key (0, 1, 2 or 3) indicating the type of the company (0 by default) typeName - A full string indicating the type of the company (based on the type, dependent on the current account’s language: 0=Other, 1=Entrepreneur, 2=Franchise, 3=ChainStore) retailKey - A key indicating the retail-branch specific company sector retailName - A full string indicating the retail-branch specific company sector (based on the retailKey, dependent on the current account’s language) |
Fetch the (static) supply of a company.
Method | URL |
GET | company?action=rawsupply |
Params | Values |
token | string |
CID [optional] | string |
token
the current session token as retrieved by a login-action.
CID
the CID of the company requesting the information for. If left empty, the company belonging to the current session’s account will be used.
Response |
{ "id": <string> "title": <string> "content": <string> "img": <string> "fullimg": <string> "tags": <array> } id - The unique identifier of the supply (18 chars; ‘18’ followed by a timestamp). title - The title of the supply (1-100 chars). content - The full content of the supply (description, 1-10000 chars). img - A full URL to the (optional) image (400px) belonging to the supply. fullimg - A full URL to the (optional) image (original source) belonging to the supply. tags - A plain array of strings containing 1 to 3 tags (labels) for the supply. |
Fetch the employees of a company. Please note that ‘employee’ is interpreted as ‘board member‘ when the company is a group.
Method | URL |
GET | company?action=rawemployees |
Params | Values |
token | string |
CID [optional] | string |
token
the current session token as retrieved by a login-action.
CID
the CID of the company requesting the information for. If left empty, the company belonging to the current session’s account will be used.
Response |
{ "id": <string> "name": <string> "function": <string> "male": <integer> "img": <string> "fullimg": <string> "phone": <string> "web": <string> "mail": <string> } id - The unique identifier of the employee (18 chars; ‘10’ followed by a timestamp). name - The full name of the employee (0-50 chars). function - The function of the employee within the company (0-50 chars). male - 1 if the employee is a male; 0 otherwise (female). img - A full URL to the (optional) image (150px) belonging to the employee. fullimg - A full URL to the (optional) image (original source) belonging to the employee. phone - The phone number of the employee (validated; possibly empty). web - The website of the employee (validated; possibly empty). mail - The e-mailaddress of the employee (validated; possibly empty). |
Fetch the available pages in the journal of a company.
Method | URL |
GET | journal?action=rawpagesnew |
Params | Values |
token | string |
token
the current session token as retrieved by a login-action. The company belonging to this token will be used for retrieving the pages.
Response |
[ { "id": <string> "name": <string> "color": <array> "default": <boolean> }, ... ] The result is an array of zero or more objects with the following data: id - The page identifier; this can be a company id (the current company’s own id or groups that the company is a member of), ‘network’, or ‘local’. name - A display-name for the identifier (the company name or a localized descriptor). color - An array of (R,G,B) indicating an associated color with the page (e.g. header). default - True for one page in the response: this should be the default page to be open. targets - A key->value array of id -> description, indicating the set of possible targets for a message (all group members, your own street, specific public clusters, etcetera). |
Fetch the messages that would normally appear in the business magazine.
This only fetches the meta-data that is required to load each message individually (see next function).
Method | URL |
GET | journal?action=rawmessages |
Params | Values |
token | string |
type | string |
p | integer |
token
the current session token as retrieved by a login-action.
type
the type of magazine-page we want to display, which is an ID as fetched by the journalpages action (see function 8).
page
the current page to display; messages are grouped in 5s, sorted by date (latest first).
Response |
[ { "msg": <string> "holder": <string> }, ... ] The result is an array of zero or more objects with the following data: msg - The unique identifier of the message (18 chars; a message-type dependent prefix followed by a timestamp). holder - Internal information (see next function) |
Fetch messages that would normally appear in the business magazine.
Method | URL |
GET | journal?action=rawmessage |
Params | Values |
token | string |
msg | string |
holder | string |
token
the current session token as retrieved by a login-action.
msg
the identifier of the message we want to fetch, which is an ID as fetched by the journalmessages action (see previous function).
holder
internal information, which is needed as fetched by the journalmessages action (see previous function).
Response |
{ "id": <string> "title": <string> "content": <string> "private": <integer> "img": <string> "fullImg": <string> "file": <string> "filename": <string> "filetype": <string> "type": <integer> "time": <string> "recoms": <integer> "reps": <integer> "presences": <integer> "recomA": <integer> "repA": <integer> "presenceA": <integer> "fromID": <string> "from": <string> "fromName": <string> "inGroupID": <string> "inGroup": <string> "logo": <string> "fullLogo": <string> "logoID": <string> "links": <array> (2: "place": <string>) (2: "date": <integer>) (2: "dateTime": <string>) (3: "endTime": <integer>) (3: "tags": <array of strings>) (4: "poll": <string>) (4: "votes": <string>) (4: "voteA": <integer>) (5: "alerttype": <string>) (5: "what": <string>) (5: "where": <string>) (5: "who": <string>) (6: "holdertype": <string>) } id - The unique identifier of the message (18 chars; a message-type dependent prefix followed by a timestamp). title - The title of the message (1-100 chars). content - The content of the message (1-10000 chars, HTML). private - 0 (public) or 1 (private; group only). img - The URL to the (optional) image (400px) belonging to the message. fullimg - The URL to the (optional) image (original source) belonging to the message. file - The URL to the (optional) file belonging to the message. filename - The name (including extension) of the (optional) file belonging to the message. filetype - The general type of the (optional) file belonging to the message: txt, video, audio, presentation, spreadsheet, pdf, or document (the default). type - A digit indicating the message-type: 1 (news), 2 (event), 3 (supply), 4 (question), 5 (alert), 6 (other; first message and alike). time - A full string indicating the date and time at which the message was posted (format: %H:%M %d %b). recoms - The amount of recommends (follows/stay-up-to-dates/likes) for the message. recomA - If the current user’s company has recommended the message (0/1). reps - The amount of replies on the message. repA - If the current user’s company has replied on the message (0/1). fromID - The unique identifier of the company that has posted the message. from - The name of the company that has posted the message. fromName - The (optional) name of the actual person (account of the from-company) that has posted the message. inGroupID - The unique identifier of the (optional) group that the message is posted in. inGroup - The name of the (optional) group that the message is posted in. logo - The URL to the thumb-sized logo (64px) of the company that has posted the msg. fullLogo - The URL to the thumb-sized logo (original source) of the company that has posted the msg. logoID - The unique identifier of the company’s logo (useful for caching). links - An array of all URLs that were possibly in the message content. And depending on the message type, these fields might also be present: presences - The amount of companies that have indicated to be present at the event. presenceA - If the current user’s company has indicated to be present at the event (0/1). place - Event: an optional string indicating the location of the event (0-150 chars) date - Event: a Unix timestamp (seconds) indicating the date of the event (mandatory; use only the date here, not the exact time). dateTime - Event: a full string using the required date of the event, but possibly also an end-date, starting-time, or ending-time (all optionally set). endTime - Supply: a Unix timestamp (seconds) indicating the expiration date of the dynamic supply (mandatory; use only the date here, not the exact time). tags - Supply: a plain array of strings (with at least 1 element) indicating the tags belonging to this supply object (plain words, no spaces). poll - Question: if a question message is multiple choice (which does not have to be the case), this field contains the ID of the corresponding poll object, used for the voting action. votes - Question: if a question message is multiple choice (which does not have to be the case), this field contains information about the questions/votes, in an array of zero or more objects with the following ordered data (the index matters for voting): label - The (unique) label for a certain answer (1 to 500 chars). value - The amount of current votes for the answer. active - If the current user’s company has voted for this answer (1) or not (0). voteA - Question: if the current user’s company has voted for this question already (1) or not (0). If so, the company is not allowed to vote (or change vote) anymore! alerttype - Alert: a string indicating the (mandatory) alert-type (crime/calamity/warning) what - Alert: an (optional) string of 0-150 characters giving additional alert information. where - Alert: an (optional) string of 0-150 characters giving additional alert information. who - Alert: an (optional) string of 0-150 characters giving additional alert information. holdertype - Other: when applicable, a string indicating the type of a system-generated message: ‘loner’ (empty neighborhood journal page), ‘new’ (the first message of a company, generated using its abouttext), ‘first’ (empty journal page of the current company), ‘firstgroup’ (empty journal page of a group the company is a member of). |
Fetch the replies for a certain message.
Method | URL |
GET | journal?action=rawreplies |
Params | Values |
token | string |
MID | string |
token
the current session token as retrieved by a login-action.
MID
the MID of the message we want to get the replies for.
Response |
[ { "id": <string> "content": <string> "time": <string> "fromID": <string> "from": <string> "fromName": <string> "logo": <string> "fullLogo": <string> "logoID": <string> }, ... ] The result is an array of zero or more objects with the following data: id - The unique identifier of the reply (18 chars; ‘16’ followed by a timestamp). content - The content of the reply (1-10000 chars, HTML). time - A full string indicating the date and time at which the reply was posted (format: %H:%M %d %b). fromID - The unique identifier of the company that has posted the reply. from - The name of the company that has posted the reply. fromName - The (optional) name of the actual person (account of the from-company) that has posted the reply. logo - The URL to the thumb-sized logo (64px) of the company that has posted the reply. fullLogo - The URL to the thumb-sized logo (original source) of the company that has posted the reply. logoID - The unique identifier of the company’s logo (useful for caching). |
Toggle recommending (stay-up-to-date, follow, like, etc.) a message, so enable or disable depending on currently enabled or disabled.
Method | URL |
POST | message?action=rawsuptd |
Params | Values |
token | string |
MID | string |
token
the current session token as retrieved by a login-action.
MID
the MID of the message we want to toggle the recommend-status for.
Response |
{ "stat": <boolean> "msg": <string> "active": <integer> } stat - Indicates the success of the action. msg - If stat is true, this contains the (new) total amount of recommends for the given message. If stat is false, this contains a message reporting on the failure. active - If, after this action, the current user’s company is still recommending the message (1) or not (0). |
Toggle being present at an event, so enable or disable depending on currently enabled or disabled (only possible for eventmessages).
Method | URL |
POST | message?action=rawpresence |
Params | Values |
token | string |
MID | string |
token
the current session token as retrieved by a login-action.
MID
the MID of the (event)message we want to toggle the presence-status for.
Response |
{ "stat": <boolean> "msg": <string> "active": <integer> } stat - Indicates the success of the action. msg - If stat is true, this contains the (new) total amount of presencies for the given event(message). If stat is false, this contains a message reporting on the failure. active - If, after this action, the current user’s company is still indicating to be present at the event (1) or not (0). |
Post a reply on a message.
Method | URL |
POST | message?action=rawreply |
Params | Values |
token | string |
MID | string |
content | string |
token
the current session token as retrieved by a login-action.
MID
the MID of the message we want to reply on.
content
the actual content of the reply; should be properly encoded and 1-10000 chars long.
Response |
{ "stat": <boolean> "msg": <string> "active": <integer> } stat - Indicates the success of the action. msg - If stat is true, this contains the (new) total amount of replies for the given message. If stat is false, this contains a message reporting on the failure. active - If the current user’s company has replied on the message (always true if stat is true of course, but this might differ if posting the reply failed). |
Vote on a poll.
Method | URL |
POST | message?action=rawvote |
Params | Values |
token | string |
poll | string |
choice | integer |
token
the current session token as retrieved by a login-action.
poll
the identifier of the poll we want to vote on, which is an ID as fetched by a rawmessage action (see function 10) if applicable.
choice
the actual choice for the vote, which is the exact 1-based position (so not starting at 0) of the desired option in the array as returned by the rawvotes action (see function 10).
Response |
{ "stat": <boolean> "msg": <string> } stat - Indicates the success of the action. Note that currently, the company cannot retract this vote or vote again if this is true. msg - If stat is true, this contains the poll’s (new) information in an array, as returned from the rawvotes function (so for all answers; see function 10). If stat is false, this contains a message reporting on the failure. |
Post a (new) message.
Method | URL |
POST | message?action=rawpost |
token
the current session token as retrieved by a login-action.
type
the (numeric) type of the message we want to post. Depending on this, some parameters become required. An overview:
title
the title of the message; should be properly encoded and 1-10000 chars long.
img
the ID of the image of an image that should be added to the message. An image can be added by POSTing the image’s raw data to https://cdn.chainels.com/image/?CID=cid, where cid is the ID of the company that is adding the image. The reply will be a JSON array in the following form:
success - Present only if everything went well (value doesn’t matter).
error - Present only if an error occurred, and contains a reason for the error.
imgid - The ID of the newly created image, present on success only.
cont
the actual content of the message; should be properly encoded and 1-10000 chars long.
tag1, tag2, tag3
an applicable tag (1 to 3) tag for a (dynamic) supply message; should be 1-60 chars long, and at least one should be set (in the right order; so tag1 first).
place
the optional place for an event(message); should be 0-150 chars long.
timeFrom
the optional starting time for an event(message); indicated by a Unix timestamp (a time on any date will suffice).
timeTo
the optional ending time for an event(message); indicated by a Unix timestamp (a time on any date will suffice).
etime
the optional ending date for (dynamic) supply message; indicated by a string in ‘d-m-Y’ format.
date
the optional ending date for an event(message); indicated by a string in ‘d-m-Y’ format.
enddate
the optional ending date for an event(message); indicated by a string in ‘d-m-Y’ format.
range
the optional range for any message (required for an alert message); this is the unique identifier of a group (CID) the posting company is a member of and this message should be posted in.
target
the optional target for any message; this is the unique identifier of cluster this message should be posted in (see the targets field of the rawpagesnew function for possible options).
alert
the alert type for an alert message; this can be either ‘misdrijf’ (crime, the default), ‘calamiteit’ (calamity), or ‘ongeval’ (warning).
who
for an alert (optionally): who is involved? Should be properly encoded and 0-150 chars long.
what
for an alert (optionally): what has happened? Should be properly encoded and 0-150 chars long.
where
for an alert (optionally): where did it happen? Should be properly encoded and 0-150 chars long.
img
a url-safe base64 encoded (using ‘-’, ‘_’, and ‘,’ instead of ‘+’, ‘/’, and ‘=’) image (png/jpeg/gif) that is to be attached to the message (optional).
answer#
for a question (optionally): the possible (unique) answers to the poll (multiple-choice question), as indicated by a string. Replace the # with any number from 1 to 26 (ordered of course).
Response |
[ { "field": <string> "msg": <string> }, ... ] The result is an array of zero or more objects with the following data: field - The field this result is for (matching the name of the input key) msg - The relevant error message for the given field. If the result is an empty array, everything went well, and the message has been posted. |
Register a mobile device for push notifications.
Method | URL |
POST | company?action=rawregister |
Params | Values |
token | string |
device | string |
token
the current session token as retrieved by a login-action.
device
the ID of the device to register for notifications, as fetched on an Android/iOS device.
Response |
None (status-codes only) |
Unregister a mobile device for push notifications.
Method | URL |
POST | company?action=rawunregister |
Params | Values |
token | string |
device | string |
token
the current session token as retrieved by a login-action.
device
the ID of the device to unregister for notifications, as fetched on an Android/iOS device.
Response |
None (status-codes only) |
Fetch the notifications for a company.
Method | URL |
GET | company?action=rawnotifications |
Params | Values |
token | string |
token
the current session token as retrieved by a login-action.
Response |
[ { "msg": <string> "id": <string> "time": <string> "read": <integer> "logoID": <string> "logo": <string> "fullLogo": <string> }, ... ] The result is an array of zero or more objects (max 15) with the following data: msg - The content of the notification itself. id - The unique identifier of the message a notification belongs to (possibly empty). time - A string indicating how long ago the notification was created. read - 0 if this notification is new (unread); 1 otherwise. logoID - The unique identifier of the company’s logo (useful for caching). logo - The URL to the thumb-sized logo (64px) of the company that has caused the notification. fullLogo - The URL to the thumb-sized logo (original source) of the company that has caused the notification. |
Fetch the cover images for a company.
Method | URL |
GET | company?action=rawcovers |
Params | Values |
token | string |
CID [optional] | string |
full [optional] | string |
token
the current session token as retrieved by a login-action.
CID
the CID of the company requesting the cover images for. If left empty, the company belonging to the current session’s account will be used.
full
if set to any value (e.g. 1), the returned images will be the full version, e.g. the original source instead of a version resized to 800px (the default).
Response |
A JSON array of strings: the image IDs. The URL to an image can be constructed in the following way: https://cdn.chainels.com/image/ID, replacing ID with a result from the fetched array. A ‘w’ or ‘h’ parameter can be added to the image URL in order to get the image in a specific size (can take some time though, as this is done on-the-fly). |
Method | URL |
GET | journal?action=rawevents |
Params | Values |
token | string |
members | integer |
CID [optional] | string |
CID
the CID of the company requesting the events for. If left empty, the company belonging to the current session’s account will be used. Otherwise, only public events can be fetched.
EXAMPLE
The code below is an example of an API call procedure in PHP:
function apiCall( $url, $method, $body = null, array $headers = array() )
{
if( $method == 'GET' && !empty( $body ) )
{
throw new Exception( 'No body expected for GET request' );
}
if( $method == 'POST' && !empty( $body ) )
{
if( is_array( $body ) ) $body = http_build_query( $body, '', '&' );
if( empty( $headers['Content-Type'] ) ) $headers['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded';
}
$parts = parse_url( $url );
if( empty( $parts ) )
{
throw new Exception( 'Invalid URL: ' . $url );
}
$headers['Host'] = 'Host: ' . $parts['host'];
$headers['Connection'] = 'Connection: close';
$context = stream_context_create( array(
'http' => array(
'method' => $method,
'header' => array_values( $headers ),
'content' => $body,
'protocol_version' => '1.1'
)) );
$level = error_reporting( 0 );
$response = file_get_contents( $url, false, $context );
error_reporting( $level );
if( empty( $response ) )
{
$lastError = error_get_last();
$responseHeaders = '';
if( !empty( $http_response_header ) ) $responseHeaders = print_r( $http_response_header, true );
if( empty( $lastError ) ) throw new Exception( 'Failed to request resource!' . PHP_EOL . $responseHeaders );
throw new Exception( $lastError['message'] . PHP_EOL . $responseHeaders );
}
return $response;
}
function example( $debug = true )
{
$baseurl = 'https://www.chainels.com/ajax/';
$login = array('mail' => 'group@example.com', 'token' => 'password');
try
{
$response = apiCall( $baseurl . 'menu?action=rawlogin', 'POST', $login );
$result = json_decode( $response );
if( $result->stat )
{
$token = $result->msg;
}
else
{
throw new Exception( $result->msg );
}
}
catch( Exception $ex )
{
if( $debug ) echo $ex->getMessage();
else mail( 'developer@example.com', 'API Error', $ex->getMessage() );
return;
}
try
{
$response = apiCall( $baseurl . 'company?action=rawcompany&token=' . $token, 'GET' );
$company = json_decode( $response );
print_r( $company );
}
catch( Exception $ex )
{
if( $debug ) echo $ex->getMessage();
else mail( 'developer@example.com', 'API Error', $ex->getMessage() );
return;
}
$logout = array('token' => $token);
try
{
$response = apiCall( $baseurl . 'menu?action=rawlogout', 'POST', $logout );
$result = json_decode( $response );
if( !$result->stat )
{
throw new Exception( $result->msg );
}
}
catch( Exception $ex )
{
if( $debug ) echo $ex->getMessage();
else mail( 'developer@example.com', 'API Error', $ex->getMessage() );
return;
}
}