Before using this package you will need a client id and secret from Atlassian.
In Atlassian's developer portal:
- Create an Oauth2 app
- In Permissions, add permission scopes for 'Jira API' ('read:jira-work', 'write:jira-work', 'manage:jira-webhook')
- In Authorization, add the callback URL endpoint (This will need to be a publicly accessible URL. If this project is hosted on https://example.com, the callback URL will be https://example.com/api/v1/jira/callback)
- In Settings, copy the client id and secret
Create a new Client object with your Jira client id and secret
use Phox\PhpJira\Client;
$client = new Client($jiraClientId, $jiraSecret);Generate a URL for a user to navigate to in order to initiate the OAuth2 flow
$client->getConnectionUrl($state, $callbackUrl);The $state value is a string you can use to uniquely identify your user. Ensure that this is a value that cannot be guessed (Jira API reference)
The $callbackUrl value is an endpoint owned by you that Atlassian will redirect to after a user grants your application access (this will need to match the callback URL endpoint you supplied in Atlassian's developer portal). Atlassian will provide this endpoint with a code query parameter.
Validate the state value returned matches a user and store the token data, then send a request back to Atlassian to complete the OAuth2 flow
$client->handleAuthCallback($code, $state, $callbackUrl);$code is the value provided by Atlassian. This method returns an associative array of the user's access token, refresh token and the token expiration date, which you can store for future requests.
If your user's token has expired, you may refresh the token with
$client->refreshToken($accessToken, $refreshToken, $expiresAt);You can now use the Jira API to access resources and create issues and comments. Here are some examples of how you may go about doing so:
use Phox\PhpJira\Entities\Jira\JiraIssue;
use Phox\PhpJira\Entities\Jira\JiraComment;
$resources = $client->getResources();
$cloudId = $resources[0]['id'];
$projects = $client->getProjects($cloudId);
$selectedProjectId = $projects[0]['id'];
$issueTypes = $client->getIssueTypes($cloudId, $selectedProjectId);
// You can search for issues by project id:
$issueSearchResponse = $client->searchIssues($cloudId, $selectedProjectId);
/**
* Since this returns a relatively light response, you can get additional data through the bulk fetch method
* which takes in a list of issue ids
*/
$issueIds = array_map(static function ($issue) {
return $issue['id'];
}, $issueSearchResponse['issues']);
$issues = $client->bulkFetchIssues($cloudId, $issueIds);
$issue = new JiraIssue()
->projectId($selectedProjectId)
->issueType('Task')
->summary('A new issue');
$issue = $client->createIssue($cloudId, $issue);
$comment = new JiraComment()
->content('A new comment');
$client->createComment($cloudId, $issue['id'], $comment);