Authentication via OAuth

If you're developing an app designed for other ThriveCart users, you'll need to create an app, and get your credentials. You'll be given a client ID (e.g. my-example-app) and a client secret (e.g. sk_d73e286f2e7b2e9e3564325e630bq9c6). You'll need these to launch the OAuth process.

You will pass the client ID, client secret, and a redirect URL to your OAuth library.

Using our PHP SDK, you can ensure that your Composer vendor/autoload.php script is included, and then set up the OAuth library as follows:


$provider = new \ThriveCart\Oauth([
	'clientId' => 'my-example-app', // Your application's client ID
	'clientSecret' => 'sk_d73e286f2e7b2e9e3564325e630bq9c6', // Your application's client secret
	'redirectUri' => 'http://localhost/thrivecart-api-demo/oauth_example.php', // URL to be redirected to after the customer grants access to their account
]);

When you're ready to display the button for the user to connect their ThriveCart account, you can get the authorisation URL as follows:


// Fetch the authorization URL to get the user to grant access to their ThriveCart account
$authorizationUrl = $provider->getAuthorizationUrl();

// Get the state generated for you and store it in the session (helps prevent CSRF attacks)
$_SESSION['oauth2state'] = $provider->getState();

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

When the user makes their decision to grant or deny access, they will be returned to the redirectUri parameter you provided when generating their authorisation URL. On that script, you can check for an error, or get their access token:


if(isset($_GET['error'])) { // There's an error! They either denied access, or another error occurred
	switch($_GET['error']) {
		case 'access_denied':
			die('You did not grant access to your ThriveCart account.');
			break;
		default:
			die('An unknown error occurred!: '.$_GET['error']);
			break;
	}
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { // Ensure the state parameter matches
	if(isset($_SESSION['oauth2state'])) {
		unset($_SESSION['oauth2state']);
	}

	exit('Invalid state - CSRF attack?');
} else {
	try {
		// Try to get an access token
		$accessToken = $provider->getAccessToken('authorization_code', [
			'code' => $_GET['code']
		]);

		// We have our access token!
		echo 'Access Token: ' . $accessToken->getToken();

	} catch (Exception $e) {
		//
	}
}

Congratulations! You now have a valid access token! You can pass this to the PHP SDK to get started!:


$token = $accessToken->getToken();
$tc = new \ThriveCart\Api($token);