QuickBooks Online V3 PHP SDK
repository·master·Indexed 43 days ago
https://github.com/intuit/quickbooks-v3-php-sdkA PHP client library for interacting with the QuickBooks Online V3 REST API. It enables developers to perform CRUD operations on QuickBooks data and provides tools for managing OAuth 1.0 and OAuth 2.0 authentication, including the OAuth2LoginHelper and OAuth2AccessToken classes for token lifecycle management.
What's inside QuickBooks PHP SDK
- The QuickBooks API PHP SDK is a PHP client designed for connecting to the QuickBooks Online V3 REST API. It allows developers to perform Create, Update, Read, and Delete (CRUD) operations against QuickBooks Online data.
Use the Payments SDK instead of the QuickBooks API PHP SDK
masterIf you are looking for the Payments SDK, it has moved to a different repository. You can find it here: https://github.com/intuit/PHP-Payments-SDKWhat is Legko XML (XSD2PHP)
masterLegko XML (also known as XSD2PHP) is a library used to compile PHP bindings from XML Schema (XSD) files. Once compiled, these bindings allow you to:
- Unmarshalling: Bind XML files to PHP models.
- Marshalling: Save PHP bindings back into XML format.
- WSDL Generation: Generate WSDL files utilizing existing mappings in classes.
Use the OAuth2AccessToken class to manage credentials
masterThe
OAuth2AccessTokenclass is a data object used to store and manage OAuth 2.0 credentials required for QuickBooks Online API requests. It holds the access token, refresh token, client credentials, and expiration metadata.Important Note on Refresh Tokens: QuickBooks Online access tokens are valid for 1 hour. While refresh tokens are technically valid for longer, the refresh token returned by QBO changes every 24 hours. You must always record the latest refresh token returned from your most recent refresh token API call to ensure continued access.
use QuickBooksOnline//API/Core/OAuth/OAuth2/OAuth2AccessToken; // Initialize with client credentials and token details $accessToken = new OAuth2AccessToken( 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', 'ACCESS_TOKEN', 'REFRESH_TOKEN', 3600, 8726400 );Complete the OAuth 2.0 Authorization flow
masterThe OAuth 2.0 flow using
OAuth2LoginHelperfollows these steps:- Get Authorization URL: Call
getAuthorizationCodeURL()to get the URL where you redirect the user to log in. - Exchange Code for Token: After the user is redirected back to your
redirectUriwith acodeparameter, callexchangeAuthorizationCodeForToken($code, $realmID)to obtain anOAuth2AccessTokenobject.
Note: The
$realmID(Company ID) is used to associate the token with the specific QuickBooks company.// 1. Redirect user to this URL $authUrl = $helper->getAuthorizationCodeURL(); // 2. After redirect, catch the 'code' and 'realmId' from the query string $accessToken = $helper->exchangeAuthorizationCodeForToken($code, $realmID);- Get Authorization URL: Call
Initialize OAuth2LoginHelper for the OAuth 2.0 flow
masterUse
OAuth2LoginHelperto manage the lifecycle of OAuth 2.0 authentication, including generating authorization URLs, exchanging codes for tokens, and refreshing tokens.There are two ways to initialize the helper:
- New Authentication Flow: Pass your application credentials directly.
- Token Refresh Flow: Pass an existing
ServiceContextcontaining anOAuth2AccessTokento allow the helper to perform refresh operations.
Parameters for new flows:
$clientID: Your App's Client ID.$clientSecret: Your App's Client Secret.$redirectUri: The redirect URI specified in your App settings.$scope: The requested scope for the app.$state: (Optional) A string to prevent CSRF. If not provided, a random 5-character string is generated.
// For a new authentication flow $helper = new OAuth2LoginHelper( 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', 'https://your-redirect-uri.com', 'com.intuit.quickbooks.accounting' ); // For refreshing an existing token using a ServiceContext // $serviceContext must contain an OAuth2AccessToken in its requestValidator $helper = new OAuth2LoginHelper( null, // clientID not used when serviceContext is provided null, // clientSecret not used when serviceContext is provided null, null, null, $serviceContext );View QuickBooks API PHP SDK CRUD examples
masterFor concrete implementation examples of Create, Update, Read, and Delete operations, refer to the SampleApp-CRUD-PHP repository: https://github.com/IntuitDeveloper/SampleApp-CRUD-PHP/tree/master/CRUD_ExamplesConfigure the SDK using IppConfiguration
masterThe
IppConfigurationclass is the central configuration object used to set up the QuickBooks Online PHP SDK environment. It allows you to define security mechanisms, message settings, retry policies, base URLs, and authentication modes.Key properties include:
$Security: Handles authentication (e.g.,RequestValidatororOAuth2AccessToken).$OAuthMode: Specifies whether to useCoreConstants::OAUTH1ModeorCoreConstants::OAUTH2Mode.$RealmID: The Company ID (Realm ID) associated with the QuickBooks account.$minorVersion: An integer specifying the API minor version.$RetryPolicy: An instance ofIntuitRetryPolicyto manage service call retries.$Logger: The mechanism used for diagnostics and logging.$BaseUrl: Defines the API endpoints (e.g., Pre-Production URLs).$SSLCheckStatus: A boolean to enable or disable SSL verification.
Initialize OAuth2AccessToken
masterConstruct a new
OAuth2AccessTokeninstance with your application credentials and the tokens received from the OAuth 2.0 flow.Parameters:
$cID(String): The Client ID associated with your app.$cS(String): The Client Secret associated with your app.$atk(String, optional): The OAuth 2 Access Token.$refreshtk(String, optional): The OAuth 2 Refresh Token.$atei(int, optional): Access token expiration in seconds (typically 3600).$refreshtei(int, optional): Refresh token expiration in seconds (typically 8726400).$tk(String, optional): The token type. Defaults to"bearer".
$token = new OAuth2AccessToken($clientID, $clientSecret, $accessToken, $refreshToken, $accessTokenExpiresIn, $refreshTokenExpiresIn);Check token status in OAuth2AccessToken
masterUse these methods to verify if tokens are present before attempting to use them in API calls.
isAccessTokenSet(): Returnstrueif an access token is present and not empty.isFreshTokenSet(): Returnstrueif a refresh token is present and not empty.
Extract OAuth credentials from settings arrays
masterThe
CoreConstantsclass provides helper methods to safely extract OAuth credentials from configuration arrays, accounting for common naming variations (e.g., camelCase vs PascalCase).getAccessTokenFromArray(array $settings): Returns the access token. Looks foraccessTokenKey,accessToken, orAccessToken.getRefreshTokenFromArray(array $settings): Returns the refresh token. Looks forrefreshTokenKey,refreshToken, orRefreshToken.getRedirectURL(array $settings): Returns the redirect URL. Handles numerous variations likeredirectURL,RedirectUrl,redirecturi, etc.
use QuickBooksOnline\API\Core\CoreConstants; $settings = [ 'accessToken' => 'your_access_token', 'refreshToken' => 'your_refresh_token', 'redirectUrl' => 'https://your-app.com/callback' ]; $token = CoreConstants::getAccessTokenFromArray($settings); $refresh = CoreConstants::getRefreshTokenFromArray($settings); $redirect = CoreConstants::getRedirectURL($settings);Manually sign a request with sign()
masterIf you need to perform the signing step separately from header generation, use the
signmethod. This updates the internaloauthParametersarray with a newoauth_signature.Method Signature:
public function sign($uri, $queryParameters, $httpMethod)Parameters:
$uri(String): The complete URL.$queryParameters(Array): Query parameters to include in the signature.$httpMethod(String): The HTTP method (e.g.,'GET','POST').
$oauth->sign($uri, $queryParams, 'GET'); // The $oauth->oauthParameters property now contains the signature.