Coder Social home page Coder Social logo

how-to-connect-to-erpnext-v5-api-with-php5's Introduction

How to connect to ERPNext v5 API with PHP 5

  • ERPNext is trademark of Frappe Technologies Pvt. Ltd.
  • Copyright 2013 Frappe Techlogies Pvt Ltd.
  • This code is licensed under the GNU General Public Lisense (v3) and the Documentation is licensed under Creative Commons (CC-BY-SA-3.0)

Requirements

  • ERPNext v5
  • PHP 5.3 - 5.6
    • php-curl

First of all

  • If you got some error, make sure the bellow points:
    • URL
    • usr
    • pwd
    • Cookie
    • parameter
    • DocType
    • Doc
    • Permissions
    • HTTP response Code

1. Auth

  • This is mandatory before any sequence of requests (except Auth).
  • After pass the auth, you should get and save the cookie.
  • You should send it with your API call, and it should be valid.

URL

  • http(or https)://(ERPNext)/api/method/login

Method

  • POST

Parameters

  • usr
    • mandatory
    • Login name of your ERPNext.
  • pwd
    • mandatory
    • Password for usr.

Return

  • SUCCESS
    • JSON (with message property)
  • FAIL
    • HTTP Status Code 40x

2. Search

URL

  • http(or https)://(ERPNext)/api/resource/(DocType name)

Method

  • GET

Parameters

  • limit_start
    • optional
    • default: 0
    • Offset for pagination
  • limit_page_length
    • optional
    • default: 20
    • Limit for pagination
  • conditions
  • fields
    • optional
    • Keys and values in the DocType.
    • e.g. "name=first_name"

Return

  • SUCCESS
    • JSON
  • FAIL
    • HTTP Status Code 40x

3. Get

URL

  • http(or https)://(ERPNext)/api/resource/(DocType name)/(Doc name)

Method

  • GET

Parameters

  • (none)

Return

  • SUCCESS
    • JSON
  • FAIL
    • HTTP Status Code 40x

4. Insert

URL

  • http(or https)://(ERPNext)/api/resource/(DocType name)

Method

  • POST

Parameters

  • JSON

Return

  • SUCCESS
    • JSON
  • FAIL:
    • HTTP Status Code 40x

5. Update

URL

  • http(or https)://(ERPNext)/api/resource/(DocType name)/(Doc Name)

Method

  • PUT

Parameters

  • JSON

Return

  • SUCCESS
    • JSON
  • FAIL:
    • HTTP Status Code 40x

6. Delete

URL

  • http(or https)://(ERPNext)/api/resource/(DocType name)/(Doc Name)

Method

  • DELETE

Parameters

  • (none)

Return

  • SUCCESS
    • JSON
  • FAIL:
    • HTTP Status Code 40x

Example with php-curl

Auth

$ch = curl_init('https://example.com/api/method/login');
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, array('usr'=>'[email protected]','pwd'=>'password'));
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'POST');
// common description bellow
curl_setopt($ch,CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch,CURLOPT_COOKIEJAR, '(your cookie file)');
curl_setopt($ch,CURLOPT_COOKIEFILE, '(your cookie file)');
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch,CURLOPT_TIMEOUT, (set secounds for timeout));
$response = curl_exec($ch);
$header = curl_getinfo($ch);
// 200? 404? or something?
$error_no = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if($error_no!=200){
  // do something for login error
  // return or exit
}
$body = json_decode($response);
if(JSON_ERROR_NONE == json_last_error()){
  // $response is not valid (as JSON)
  // do something for login error
  // return or exit
}
// use $body

Search

$filters = json_encode(array('employee'=>'EMP/0001','att_date'=>'2017-01-01'));
// check if $filters invalid
$data = array('filters'=>$filters);
$q = http_build_query($data);
$ch = curl_init('https://example.com/api/resource/Attendance?'.$q);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'GET');
// the rest omitted (see Auth)

Get

$ch = curl_init('https://example.com/api/resource/User/[email protected]');
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'GET');
// the rest omitted (see Auth)

Update

$data = json_encode(array('att_date'=>'2017-01-01'));
// check if $data invalid
$ch = curl_init('https://example.com/api/resource/Attendance/ATT-00016');
curl_setopt($ch,CURLOPT_POSTFIELDS,array('data'=>$data));
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'PUT');
// the rest omitted (see Auth)

Insert

$data = json_encode(array('att_date'=>'2017-01-01','employee'=>'EMP/0004','status'=>'Present'));
// check if $data invalid
$ch = curl_init('https://example.com/api/resource/Attendance');
curl_setopt($ch,CURLOPT_POSTFIELDS,array('data'=>$data));
curl_setopt($ch,CURLOPT_POST, true);
// the rest omitted (see Auth)

Delete

$ch = curl_init('https://example.com/api/resource/Attendance/ATT-00016');
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'DELETE');
// the rest omitted (see Auth)

FAQ

  • What is (DocType, Doc or something)?
    • See the reference of ERPNext.
  • I got a something what I did not expect.
    • Re-check your codes, settings, data and your ERPNext.
  • You should correct your codes because I am using ERPNext v6 (or newer).
    • Feel free to publish your codes on GitHub.

how-to-connect-to-erpnext-v5-api-with-php5's People

Contributors

tmimori avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

how-to-connect-to-erpnext-v5-api-with-php5's Issues

Insert issue

When we use insert method, it throw error no json object to decode.

case 'INSERT': $url = $this->_api_url.$params['doctype']; $ch = curl_init($url); $data_string = json_encode($params['data']); curl_setopt( $ch ,CURLOPT_POSTFIELDS ,$data_string ); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); curl_setopt($ch,CURLOPT_POST, true); break;

Please replace code with this in FrappeClient.php , Line No. 201

Getting "Auth fail" error

I did all the settings as per your instructions;
auth_url
api_url
cookie_file

But getting error "Auth fail."
Is there anything, I am missing?

config.php file

<?php if(!defined("ROOTPATH")){die("Access forbidden.".PHP_EOL);}
return array(
    'auth_url' => 'http://mittalclothing.erpnext.com/api/method/login',
    'api_url' => 'http://mittalclothing.erpnext.com/api/resource/',
    'auth' => array('usr' => '[email protected]', 'pwd' => 'CORRECT PASSWORD'),
    'cookie_file' => '/chroot/home/wholesa9/wholesaleraja.com/html/erp/erpnext/cookie.txt',
    'curl_timeout' => 30,
    'basic_auth' => array()
);

Main setting part of FrappeClient.php file

define('ROOTPATH',dirname(__FILE__));

class FrappeClient {

    const CONF_FILE = '/chroot/home/wholesa9/wholesaleraja.com/html/erp/erpnext/config.php';

Sample.php file

// get ----------------------------

    $result = $client->get(
                    "User"
                    ,"[email protected]"
                );

    var_dump($result);

I think I did all settings correct, but still its not giving me proper result.
Please help me to fix this.

order of curl_setopt sentences in insert

In some PHP versions the current order of curl_setopt sentences returns a server error. Maybe because CURLOPT_POSTFIELDS depends on CURLOPT_POST,

This way will fix (INSERT):
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, array ( 'data' => json_encode ( $params ['data'] ) ) );

In some cases, when a doctype has a name with whitespace the client returns a Bad Request error.

public function insert($doctype, $params) {
str_replace ( ' ', '%20',$doctype); // Fix
$this->_auth_check ();
return $this->_curl ( 'INSERT', array (
'doctype' => $doctype,
'data' => $params
) );
}

Data insert issue

If I follow the default code for insert operation I found empty object from erpnext end.

PHP

public function insert(
			$doctype
			,$params
		){
			$this->_auth_check();
			return $this->_curl(
				'INSERT'
				, array('doctype' => $doctype, 'data' => $params )
				);
		}

Return:

2019-11-13 13:31:30,018 Request Error 
 site: testing_erp
 form: {}

Traceback (innermost last):
  File "/home/frappe/test_lucas_erp/frappe-bench/apps/frappe/frappe/app.py", line 72, in application
    response = frappe.api.handle()
  File "/home/frappe/test_lucas_erp/frappe-bench/apps/frappe/frappe/api.py", line 111, in handle
    data = json.loads(frappe.local.form_dict.data)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
 TypeError: expected string or buffer

When I modify php code little bit,:
json_encode(['data' => $params['data']])

I am getting form value along with following error:

2019-11-13 14:18:04,237 New Exception collected with id: 2019-11-13 14:18:04.233967-103.84.38.114-be7 
 site: testing_erp
 form: {'{"data":{"customer_name":"Sakib Al Hasan","first_name":"Sakib","last_name":"Al Hasan Molla","territory":"Lithuania","prersonal_code":"1212","company_phone_1":"016715xx788","company_email_id_1":"[email protected]"}}': u''}

Traceback (innermost last):
  File "/home/frappe/test_lucas_erp/frappe-bench/apps/frappe/frappe/app.py", line 72, in application
    response = frappe.api.handle()
  File "/home/frappe/test_lucas_erp/frappe-bench/apps/frappe/frappe/api.py", line 111, in handle
    data = json.loads(frappe.local.form_dict.data)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
 TypeError: expected string or buffer

Other hand while i try connect this api using https://github.com/frappe/frappe-client it works fine and from posted data seems like:

{'data': u'{"first_name": "Hizbul", "last_name": "Bahar", "doctype": "Customer", "company_phone_1": "+8801918019898", "company_email_id_1": "[email protected]", "personal_code": "090225", "territory": "Lithuania", "customer_name": "Hizbul Bahar"}'}

ERPNEXT: 6.22.4 and PHP 7.1

getting error on insert new data json must be str not byte

Server Error
Traceback (most recent call last):
File "/home/frappe/frappe-bench/apps/frappe/frappe/app.py", line 67, in application
response = frappe.api.handle()
File "/home/frappe/frappe-bench/apps/frappe/frappe/api.py", line 114, in handle
data = json.loads(frappe.local.form_dict.data)
File "/usr/lib/python3.5/json/init.py", line 312, in loads
s.class.name))
TypeError: the JSON object must be str, not 'bytes'
Home
Status: 500

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.