GithubHelp home page GithubHelp logo

xeroapi / xerooauth-php Goto Github PK

View Code? Open in Web Editor NEW
123.0 44.0 85.0 484 KB

PHP class for the Xero API V2

Home Page: https://developer.xero.com/php-tutorial/

License: MIT License

PHP 99.45% Hack 0.55%

xerooauth-php's Introduction

Warning: This lib is no longer maintained.

Looking for OAuth 2.0?

Please checkout Xero PHP sdk for OAuth 2.0 and it's companion kitchen sync app

Looking for OAuth 1.0a?

Please checkout the community project https://github.com/calcinai/xero-php

XeroOAuth-PHP (DEPRECATED)

This repository has been archived and no further issues or pull requests will reviewed. Feel free to fork the repo and work with the code.

PHP library for working with the Xero OAuth API.

Intro

XeroOAuth-PHP is a sample library for use with the Xero API (http://developer.xero.com). The Xero API uses OAuth 1.0a, but we would not recommend using this library for other OAuth 1.0a APIs as the Xero API has one of the more advanced implementations (RSA-SHA1, etc) and thus has many configuration options not typically used in other APIs.

This library is designed to get a developer up and running quickly with the OAuth authentication layer, but there will be some customisation of its implementation required before it can be used in a production environment.

Requirements

  • PHP 5+
  • php_curl extension - ensure a recent version (7.30+)
  • php_openssl extension

Setup

To get setup, you will need to modify the values in the _config.php file to your own requirements and application settings or see the customised example file for each different application type, public.php, private.php or partner.php.

Usage

There are a number of functions used when interacting with Xero:

Make a request

The request function lies at the core of any communication with the API. There are a number of types of requests you may wish to make, all handled by the request() function.

request($method, $url, $parameters, $xml, $format)
Parameters
  • Method: the API method to be used (GET, PUT, POST)
  • URL: the URL of the API endpoint. This is handled by a special function (see below)
  • Parameters: an associative array of parameters such as where, order by etc (see https://developer.xero.com/documentation/api/requests-and-responses/)
  • XML: request data (for PUT and POST operations)
  • Format: response format (currently xml, json & pdf are supported). Note that PDF is not supported for all endpoints

Generate a URL

Create a properly formatted request URL.

url($endpoint, $api)
Parameters
  • Endpoint: the endpoint you wish to work with. Note there are OAuth endpoints such as 'RequestToken' and 'AccessToken' in addition to various API endpoints such as Invoices, Contacts etc. When specifying a resource, such as Invoices/$GUID, you can construct the request by appending the GUID to the base URL.
  • API: there are two APIs: core (core accounting API) and payroll (payroll application API). Default is core.

Parse the response

Once you get data back, you can pass it through the parseResponse function to turn it into something usable.

parseResponse($response, $format)
Parameters
  • Response: the raw API response to be parsed
  • Format: xml pdf and json are supported, but you cannot use this function to parse an XML API response as JSON - must correspond to the requested response format.

Authorise

For public and partner API type applications using the 3-legged OAuth process, we need to redirect the user to Xero to authorise the API connection. To do so, redirect the user to a url generated with a call like this:

url("Authorize", '') . "?oauth_token=".$oauth_token."&scope=" . $scope;
Appendages
  • oauth_token: this is a request token generated in a prior RequestToken call
  • scope: the Payroll API is a permissioned API and required a comma separated list of endpoints the application is requesting access to e.g. $scope = 'payroll.payrollcalendars,payroll.superfunds,payroll.payruns,payroll.payslip,payroll.employees';

Refresh an access token

For partner API applications where the 30 minute access tokens can be programatically refreshed via the API, you can use the refreshToken function:

refreshToken('the access token', 'the session handle')
Parameters
  • Access token: the current access token
  • Session handle: the session identifier handle

Debug

Setup Diagnostics

As you are getting set up, you may run into a few configuration issues, particularly with some of the more advanced application types such as partner.

To make sure your configuration is correct, you can run a diagnostics function:

diagnostics();

This returns an array of error messages (if there are any). These are in human readable form so should be enough to put you on the right track. If not, check the Xero developer centre and forum for more detail.

It would probably be a bad idea to run this in your production code as the errors returned ones only a developer can resolve, not the end user.

Runtime errors

There are many reasons why an error may be encountered: data validation, token issues, authorisation revocation etc. It is important to inspect not just the HTTP response code, but also the associated error string.

A very basic error output function is included in the sample code, which outputs all available information related to an error. It would need to be substantially tidied up before the results could be surfaced in a production environment.

outputError($object);

Response Helpers

Understanding the type of message you are getting from the API could be useful. In each response that is not successful, a helper element is returned:

  • TokenExpired: This means that the access token has expired. If you are using a partner API type application, you can renew it automatically, or if using a public application, prompt the user to re-authenticate
  • TokenFatal: In this scenario, a token is in a state that it cannot be renewed, and the user will need to re-authenticate
  • SetupIssue: There is an issue within the setup/configuration of the connection - check the diagnostics function

TODO

  • Reading a value from a report
  • Better WHERE and ORDER examples
  • Merge OAuthsimple changes for RSA-SHA1 back to parent repo

License & Credits

This software is published under the MIT License.

OAuthSimple

OAuthsimple.php contains minor adaptations from the OAuthSimple PHP class by United Heroes.

tmhOAuth

XeroOAuth class is based on code and structure derived from the tmhOAuth library.

Major change history

0.8 - 16th December 2016

Deprecated Entrust Certificates for Partner Apps by commenting out related code and updating base URL to api.xero.com

0.7 - 1st Feb 2016

PHP7 support via @tomcastleman Moved releases to Github release function

0.6 - 19th April 2015

Added composer support. Modified content-type so is also set for PUT requests

0.5 - 16th November 2014

Added examples for CRU of tracking categories and options. Updated the CA certs to a recent one - warning that if you are using a very old version of curl you may get 'cert invalid' type error. Removed an unused function and tidied up comments on another to make them more sensible.

0.4 - 29th September 2014

Merged some pull requests, addressed an issue with multiple calls having signature validation issues.

0.3 - 3rd January 2014

Merged a number of pull requests, tidied up formatting and extended sample tests.

0.2 - 13th May 2013

Merged to master, added more tests and improved security handling for partner API apps.

0.1 - 10th May 2013

Initial release candidate prepared and released to 'refactor' branch.

xerooauth-php's People

Contributors

drewbroadley avatar dupski avatar elliotchance avatar iansimpson avatar lloydhazlett avatar matthealy avatar mradcliffe avatar philals avatar ronanq avatar sidneyallen avatar tomcastleman avatar torohill avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xerooauth-php's Issues

request() method not working - SSL certificate error

I tried to run a private application test using this library, and I'm getting the following error:

Curl error: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

File ca-bundle.crt is in the correct location and it's loaded correctly, but the authentication fails anyway.

Curl error: SSL certificate problem

Hi

I got a problem when testing.

http://salnan.com/xero/public.php

For 1st time it work ok when i test Organization. But after i close my windows, and then open again, it say

Error: Curl error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Any solution for this. I dont update any code from your server, Only consumer_key , shared_secret, and also OAUTH_CALLBACK

Thank You
Salnan

Invoice Payment dates are returned in .NET DataContractJsonSerializer format

Ultimately this is more a fault of the API itself, but it would be helpful if the library converted these dates to ISO format for us.

Has been an ongoing issue in the forums for 4+ (!!!!!) years now

An easy solution would only have to be a few lines of code (referenced from here):

preg_match('~(\d+)\d{3}((?:\+|-)\d+)~',  $date, $match);
$dt = new DateTime('@' . $match[1]);
$dt = new DateTime($dt->format('Y-m-d H:i:s') . ' ' . $match[2]);
$date = strtotime($dt->format('r'));

Not creating $this->request_params for POST requests in curlit() was breaking OAuth signature

I was receiving the following warnings doing a POST to /Invoices, which was returning a 401 Invalid Signature from the API:


A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'xml'

Filename: libraries/XeroOAuth.php

Line Number: 303
A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: libraries/XeroOAuth.php

Line Number: 329
A PHP Error was encountered

Severity: Warning

Message: implode(): Invalid arguments passed

Filename: libraries/XeroOAuth.php

Line Number: 332

these pointed to the empty POST method switch on Line 226:

case 'POST':

    break;

Simply creating the empty array, ala:

case 'POST':
    $this->request_params = array();
    break;

(or better yet before the switch on 225) fixed the issue, but I am wondering why this whole block was left empty???

To get Profit Loss Report

Actually i want to retieve the Profit and Loss report.it all goes fine until i get an alphanumeric code that is suggested to input into the Xero on AppHarbor url,but when i go back,it neither returns to AppHarbor home page nor to any other page demanding for any code.

So please help me where to input this code and use it to retrieve the P/L report.
Hope for a better response.

Thanks again,
xero code

Undefined index: session_handle

After authenticating with a public application (after directed to API.XERO.COM for authentication (30m period), I'm receiving:
Notice: Undefined index: session_handle in /var/www/html/XeroOAuth-PHP/tests/testRunner.php on line 98

On page: /XeroOAuth-PHP/public.php

SHA-2?

Can you please confirm that your official API works with your API so people don't have to test SHA-2 specifically.

Does API provide this functionality?

if (isset($_REQUEST['users'])) {
        $response = $XeroOAuth->request('GET', $XeroOAuth->url('Users', 'core'), array('Where' => $_REQUEST['where']));
        if ($XeroOAuth->response['code'] == 200) {
            $users = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
            echo "There are " . count($users->Users[0]). " users in this Xero organisation, the first one is: 
"; pr($users->Users[0]->User); } else { outputError($XeroOAuth); } }

To get the user information after connecting with xero?

TokenExpired:

"TokenExpired: This means that the access token has expired. If you are using a partner API type application, you can renew it automatically, or if using a public application, prompt the user to re-authenticate"
Where do I send user user to re-authenticate? Can you you explain? We don't really want xero to fight us same way QuickBooks do. But it appears to be the case.

Bug found

Hello

There's a bug in the codebase when you do 2 simultaneous requests - it isn't apparent in the test suite as this never happens.

e.g. make a GET request, then a POST request and you will be supplied with an oauth invalid signature error.

As a work around at the end of the "curlit" method I reset a few variables:

    $this->request_params = array();
    $this->params = array ();
    $this->headers = array ();
    $this->auto_fixed_time = false;
    $this->buffer = null;
    $this->xml = null;

After that everything works as expected.

Hope this helps someone else, as it had me knocking my head off a wall for a long time!

Ryan

Need help to fix Unknown SSL protocol error in connection during refresh tokens

Hi,
I am using PHP library to access Xero API's and when trying to refresh API tokens I am getting the following error,
"Curl error: Unknown SSL protocol error in connection to api-partner.network.xero.com:443".
It's not happening for all request, but for few.
Can you please let me know how it can be fixed. Below is the complete response,

REQUEST API URL:
https://api-partner.network.xero.com/oauth/AccessToken

RESPONSE CODE:1

RESPONSE:
https://gist.github.com/chethank/af642cdd5379a5eb9119

Thanks
Chethan K

when attempting to access with Partner type

it returns below errors:

ContextErrorException: Notice: Undefined index: signed_url

looking at a line 264: you will see CURLOPT_URL => $this->sign['signed_url'],

where is the sign['signed_url'] from?????

think it's not implemented yet huh?

What is the point of $this->config ['session_handle']

In the file XeroOAuth.php, line 446
if ($this->response ['code'] == 401 && isset ( $this->config ['session_handle'] )) {

What is the point of the isset ( $this->config ['session_handle'] ) test?

I am getting a 401 response for expired token, but it is skipping setting the helper to TokenExpired because i do not have a session_handle set

Argument mixups

Class XeroOAuth expects arguments access_token and access_token_secret, while class OAuthSimple expects consumer_key and shared_secret. This must be tidied up, the examples are confusing enough without this "renaming" through the code.

Hidden exception when signing requests

File XeroOAuth.php, line ~423

try {
    $this->sign = $oauthObject->sign ( array (
            'path' => $url,
            'action' => $method,
            'parameters' => array_merge ( $params, array (
                    'oauth_signature_method' => $this->config ['signature_method']
            ) ),
            'signatures' => $this->config
    ) );
}

catch ( Exception $e ) {
    $errorMessage = $e->getMessage ();
}

Exception is hidden, but it must not be. If the signature fails, the request fails with cryptic errors.

php_self

The php_self function returns http://<>:443 for an https domain which is rejected by apache.

If I change it to the following

I have worked around by forcing https and ignoring port.

contactpersons

Hi Guys,

I am querying contact end point but i am not receiving contactpersons details as i do receive in API Previewer.

Also how can i query based on UpdatedDateUTC field in PHP API?

Unable to specify order as a parameter

The request method always merges the value from $_REQUEST['order'] (which it defaults to an empty string) with parameters specified as the 3rd parameter to the method. It is therefore impossible to pass an order in code like:

$params = array(
    'where' => 'Type="ACCREC"',
    'order' => 'InvoiceNumber ASC'
);

$response = $this->xeroOAuth->request('GET', $this->xeroOAuth->url('Invoices', 'core'), $params);

The value of order specified in the params is overridden by an empty string and the order is ignored.

Failure with blank 'curl_error' executing request.

I'm having problems with this library. I have traced this to the curl_exec call failing.

Unfortunately curl_error is returning a blank string so I really have no idea as to what is going wrong. This is very frustrating and don't know whether this is a PHP bug (am on Centos with PHP 5.4.16) or something else.

I will try and figure out why the error is blank and report back.

Curl Error

I'm posting this here in case anyone else runs into the same issue or the developer decides to include two crt files.

I was getting the following error -
Error: Curl error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I found a solution at http://www.webmyriad.net/tips/xero-api/php-xero-api-getting-the-php-code-sample-working-for-private-applications?id=4403.

The extra step at the end fixed it for me -
Go to the following link https://github.com/bagder/ca-bundle/blob/e9175fec5d0c4d42de24ed6d84a06d504d5e5a09/ca-bundle.crt
Press the "raw" button, select all, copy and paste the contents into the file certs/ca-bundle.crt on your webserver/localhost you can replace the previous file.
Note, this is because the original ca-bundle.crt downloaded with the PHP example code is too new, you need an older version, see the following site http://curl.haxx.se/docs/caextract.html and notice the reference to "an older ca-bundle from github"

CA Bundle is not always inside the project

I normally set the Ca bundle path in php.ini and that can be the case with many other systems. The library tries to set ca bundle explicitly, which I dont think is a good idea.

In my opinion this configuration should be left for the users. They can either set the ca bundle in php.ini or have it somewhere else (outside the project) and specify via configuration.

Right now the library checks for BASE_PATH which itself is a bad idea, and tries to set ca bundle from certs directory which may not resolve in some configurations of autoloaders.

How to use the API to pull the Bank Statement?

Hello,

I'm trying to find examples on how to pull the Bank Statement from the Reports where I have start date, end date and the amount of the transactions (if possible).

Can't find anywhere... I can only find examples of the same stuff... payrolls, contacts...

Could you please point me into the right direction?

Thank you so much!
Kitara

PUT Request returns OAuth error, Corresponding POST Request works correctly.

I am trying to PUT a new Invoice however whenever I send the request I get the following error:

oauth_problem=signature_method_rejected&oauth_problem_advice=Private%20applications%20must%20use%20the%20RSA-SHA1%20signature%20method

The code I am using is as follows:

$xero->request('PUT', $xero->url('Invoices'), null, $request);

When I swap out the PUT for a POST it works correctly.

I noticed a difference in the URL when sending the two requests:

POST:

https://api.xero.com/api.xro/2.0/Invoices?oauth_consumer_key=TAP3V7SPYTCJ48G9TKBJ9EESJ2D5FI&oauth_nonce=RQHuL&oauth_signature=OG0IuuEw94T66Xmt%2BfMZDITrPONc%2FCj6Q1kArMR3a%2Bhl4Q2EN0Ofry42KIx0eyYJ4wGtFFLxa%2FqaIpz5bp5uEMpi52Lxoaa%2FAqbZKu7js7VrHstxvxSh1IB%2FUzdK2bzZDcgs0ZwngjWzWc%2BFe18RpnGUXHY9eSPL1v1vMUxXNLw%3D&oauth_signature_method=RSA-SHA1&oauth_timestamp=1390806595&oauth_token=TAP3V7SPYTCJ48G9TKBJ9EESJ2D5FI&oauth_version=1.0&order=

PUT:

https://api.xero.com/api.xro/2.0/Invoices?oauth_consumer_key=TAP3V7SPYTCJ48G9TKBJ9EESJ2D5FI&oauth_nonce=k20rN&oauth_signature=EYc2x6Hqd7QT74sWiM0cHGf5JzM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1390806630&oauth_token=TAP3V7SPYTCJ48G9TKBJ9EESJ2D5FI&oauth_version=1.0

Am I missing something from the config which would cause it to use HMAC over RSA-SHA1?

Thanks

Bug: Array Merge Fails when doing a GET request because Parameters is not set

In lines https://github.com/XeroAPI/XeroOAuth-PHP/blob/master/lib/XeroOAuth.php#L388-434

Because $params isn't set (if it's a POST request $params['xml'] is set) the try statement fails. This is because array_merge on https://github.com/XeroAPI/XeroOAuth-PHP/blob/master/lib/XeroOAuth.php#L429 is trying to merge an empty $params instead of an array.

It looks like you recently changed this because all I did was make 'useauth' part of $params again and it fixed it on https://github.com/XeroAPI/XeroOAuth-PHP/blob/master/lib/XeroOAuth.php#L389

XML content in POST requests is not properly encoded

I use $XeroOAuth->request() to send requests to Xero.

When trying to send an Invoice with a + character in item Description element (actually, this error was triggered if a plus character was present in any element), I was getting a weird error:

oauth_problem=signature_invalid&oauth_problem_advice=Failed%20to%20validate%20signature

(Failed to validate signature)

It looks like the problem is here:
https://github.com/XeroAPI/XeroOAuth-PHP/blob/0d2578/lib/XeroOAuth.php#L278

Adding rawurlencode() did the trick for me:
$this->request_params['xml'] = rawurlencode($this->xml);

Entrust Certificate not properly deprecated?

Hey guys, I followed the instruction to remove entrust certificates from our side where we removed the following lines from our config.

'curl_ssl_cert'  => realpath($this->erpParams['xero_curl_ssl_cert']),
'curl_ssl_password' => $this->erpParams['xero_curl_ssl_password'],
'curl_ssl_key' => realpath($this->erpParams['xero_curl_ssl_key']),

but then we got the error message
Curl error: unable to use client certificate (no key found or wrong pass phrase?)

Any Ideas?

PHP Version Support

@ronanq Is there any chance the OAuthSimple library is going to be updated to use the newer __construct constructor standard for PHP7?

composer

After add library to required

I see error

Could not find package xero/xerooauth-php at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

How to POST Receipt attachment?

I try

$rid = $response->Receipts->Receipt->ReceiptID;

$this->_instance->request('POST', $this->_instance->url('Receipts', 'core') . "/$rid/Attachments/$file_name/", array("@$local_file"));

But got a oauth_problem=signature_invalid

Payment

Please Can you help in adding the payment PUT Request on tests/test.php file. I have been having problems with this. I would like to change the status of an invoice to paid the custom gateway returns a successful payment of a invoice payment.

Accept JSON post data

I am unable to get json data to POST to Xero this this library. XML works fine but XML is a pain with special characters like &.

Maybe i am doing it wrong....

Profit Loss report

Actually i want to retieve the Profit and Loss report.it all goes fine until i get an alphanumeric code that is suggested to input into the Xero on AppHarbor url,but when i go back,it neither returns to AppHarbor home page nor to any other page demanding for any code.

So please help me where to input this code and use it to retrieve the P/L report.
Thanks ,

No versions available

The package has to be registered on packagist for people to use it. This is very easy, just goto packagist.org and slick the Submit a Package button.

It is bad practice for people to run off your master branch since that could change and isn't guaranteed to be stable. When you add git tags like v1.0 it will be recognised as a release by both composer and Github. For each release in the future just add another tag thats appropriate for the version.

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.