Skip to content

Commit

Permalink
init code commit
Browse files Browse the repository at this point in the history
  • Loading branch information
SidneyAllen committed Sep 11, 2019
1 parent 35d698b commit 211fb6b
Show file tree
Hide file tree
Showing 18 changed files with 7,633 additions and 2 deletions.
76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
87 changes: 87 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Contributing to xero-php-oauth2-app
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:

We want to make contributing to this project as easy and transparent as possible, whether it's:

- Reporting a bug
- Discussing the current state of the code
- Submitting a fix
- Proposing new features
- Becoming a maintainer

The following is a set of guidelines for contributing to Xero and its projects, which are hosted in the [XeroAPI Organization](https://github.com/XeroAPI) on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.

### Table Of Contents
[Code of Conduct](#code-of-conduct)

[How Can I Contribute?](#how-can-i-contribute)
* [Reporting Bugs](#reporting-bugs)
* [Suggesting Enhancements](#suggesting-enhancements)
* [Pull Requests](#pull-requests)


## Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](https://github.com/XeroAPI/xero-php-oauth2-app/blob/master/CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.

## I don't want to read this whole thing I just have a question!!!

> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below.
We have an official [message board](https://community.xero.com/developer) where Xero API support and the community chimes in with helpful advice if you have questions.

* [API Documentation](https://developer.xero.com/documentation/)
* [Xero FAQ](https://developer.xero.com/faq)
* [Community, the official Xero message board](https://community.xero.com/developer)
* [Stackoverflow - Xero related](https://stackoverflow.com/questions/tagged/xero-api?sort=Newest)
* [Submit requests for support](https://developer.xero.com/contact-xero-developer-platform-support/) to our API Support team.

# How Can I Contribute?

You can contribute by reporting bugs, suggesting enhancements, improving documentation i.e. [README](https://github.com/XeroAPI/xero-php-oauth2-app/blob/master/README.md) or submitting a pull request.

## Reporting Bugs

Bugs are tracked as issues in this repository.

Before opening a new issue:
* **check [the README](https://github.com/XeroAPI/xero-php-oauth2-app/blob/master/README.md)** to see if the behavior you observed might be expected and if configuration options are available to provide you with the desired behavior.

* **perform a cursory search** to see if there's [an existing issue](https://github.com/XeroAPI/xero-php-oauth2-app/issues) covering your feedback. If there is one and the issue is still open, **add a :+1: reaction** on the issue to express interest in the issue being resolved. That will help the team gauge interest without the noise of comments which trigger notifications to all watchers. Comments should be used only if you have new and useful information to share.

### Write bug reports with detail, background, and sample code

- A quick summary and/or background
- Steps to reproduce
- Be specific!
- Give sample code if you can.
- What you expected would happen
- What actually happens
- Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)

## Suggesting Enhancements

When opening an issue for a feature request:
* **use a clear and descriptive title** for the issue to identify the problem.
* **include as many details as possible in the body**. Explain your use-case, the problems you're hitting and the solutions you'd like to see to address those problems.

## Pull requests

We welcome your feedback and pull requests. Be aware some code is generated and pull requests may not be the best solution - see below.

### Submit a pull request

1. Fork and clone the repository
1. Create a new branch: `git checkout -b my-branch-name`
1. Make your change, add tests if needed
1. Make sure the tests pass on your machine: `mvn test`
1. Push to your fork and submit a pull request
1. Pat your self on the back and wait for your pull request to be reviewed and merged.

Here are a few things you can do that will increase the likelihood of your pull request being accepted:

- Write tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).

## License
By contributing, you agree that your contributions will be licensed under its MIT License.
81 changes: 79 additions & 2 deletions README.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,2 +1,79 @@
# xero-php-oauth2-app
PHP app for demonstrating the xero-php-oauth2 SDK
# Xero PHP oAuth 2 App
This java project demonstrates how to use the Xero-Java SDK. Clone this repository to your local machine to begin.

This is a project is for use with xero-php-oauth2 SDK. This app demonstrates the functionality of Xero accounting API endpoints and their related actions.

You'll be able to connect to a Xero Organisation, make real API calls. The code used to make each API call will be displayed along with the results returned from Xero's API.

## Getting Started
To run locally, you'll need a local web server with PHP support.
* MAMP is a good option [Download MAMP](https://www.mamp.info/en/downloads/)

Follow these steps
* Clone this repo into your webroot. Look in your MAMP folder for `htdocs`
* Launch a terminal app and change to the newly cloned folder `xero-php-oauth2-app`
* Download dependencies with Composer.

`composer init`

New to Composer? You'll want to [install Composer](https://getcomposer.org/doc/00-intro.md)

## Create a Xero App
To obtain your API keys, follow these steps and create a Xero app

* Create a [free Xero user account](https://www.xero.com/us/signup/api/) (if you don't have one)
* Login to [Xero developer center](https://developer.xero.com/myapps)
* Click "Try oAuth2" link
* Enter your App name, company url, privacy policy url.
* Enter the redirect URI (this is your callback url - localhost, etc)
* Agree to terms and condition and click "Create App".
* Click "Generate a secret" button.
* Copy your client id and client secret and save for use later.
* Click the "Save" button. You secret is now hidden.

## Add your API keys to this app
You'll need to set the *clientId, clientSecret and redirectUri* in the following files

* authorization.php
* callback.php
* get.php.

```php
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => '__YOUR_CLIENT_ID__',
'clientSecret' => '__YOUR_CLIENT_SECRET__',
'redirectUri' => 'http://localhost:8888/xero-php-oauth2-app/callback.php',
'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize',
'urlAccessToken' => 'https://identity.xero.com/connect/token',
'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
]);
```

## License

This software is published under the [MIT License](http://en.wikipedia.org/wiki/MIT_License).

Copyright (c) 2019 Xero Limited

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.


51 changes: 51 additions & 0 deletions authorization.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php
ini_set('display_errors', 'On');
require __DIR__ . '/vendor/autoload.php';
require_once('storage.php');

// Storage Classe uses sessions for storing access token > extend to your DB of choice
$storage = new StorageClass();

session_start();

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => '__YOUR_CLIENT_ID__',
'clientSecret' => '__YOUR_CLIENT_SECRET__',
'redirectUri' => 'http://localhost:8888/xero-php-oauth2-app/callback.php',
'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize',
'urlAccessToken' => 'https://identity.xero.com/connect/token',
'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
]);

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
$options = [
'scope' => ['openid email profile offline_access accounting.settings accounting.transactions accounting.contacts accounting.journals.read accounting.reports.read accounting.attachments']
];

// Fetch the authorization URL from the provider; this returns the urlAuthorize option and generates and applies any necessary parameters (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl($options);

// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();

// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit();

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {

}
?>
<html>
<head>
<title>My App</title>
</head>
<body>
Opps! Problem redirecting .....
</body>
</html>
71 changes: 71 additions & 0 deletions callback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
ini_set('display_errors', 'On');
require __DIR__ . '/vendor/autoload.php';
require_once('storage.php');

// Storage Classe uses sessions for storing token > extend to your DB of choice
$storage = new StorageClass();

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => '__YOUR_CLIENT_ID__',
'clientSecret' => '__YOUR_CLIENT_SECRET__',
'redirectUri' => 'http://localhost:8888/xero-php-oauth2-app/callback.php',
'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize',
'urlAccessToken' => 'https://identity.xero.com/connect/token',
'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
]);

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
echo "NO CODE";
header("Location: index.php?error=true");
exit();

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
echo "Invalid State";
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);

$config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken( (string)$accessToken->getToken() );

$config->setHost("https://api.xero.com");
$identityInstance = new XeroAPI\XeroPHP\Api\IdentityApi(
new GuzzleHttp\Client(),
$config
);

// Get Array of Tenant Ids
$result = $identityInstance->getConnections();

// Save my token, expiration and tenant_id
$storage->setToken(
$accessToken->getToken(),
$accessToken->getExpires(),
$result[0]->getTenantId(),
$accessToken->getRefreshToken());

header('Location: ' . './get.php');
exit();

} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
echo "Failed!!!";
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
?>
<html>
<head>
<title>My App</title>
</head>
<body>
Opps! Should have redirected to <a href="get.php">to this page</a>
</body>
</html>
Loading

0 comments on commit 211fb6b

Please sign in to comment.