Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

PayPal: Get a sandbox access token

See more PayPal Examples

Exchange a sandbox REST app client ID and secret for a bearer token on a merchant-controlled backoffice workstation. PayPal supplies its lifetime in seconds. Store the token in a protected credential store; the companion expiry example reads only timing metadata.

PayPal documentation

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // See Unlock Chilkat before making requests.
  final http = CkHttp();
  // Load these values from the credential store on the merchant backoffice workstation.
  // Never embed the merchant secret in an app distributed to customers.
  http.login = 'SANDBOX_CLIENT_ID';
  http.password = 'SANDBOX_CLIENT_SECRET';
  http.basicAuth = true;
  final issued = CkDateTime();
  issued.setFromCurrentSystemTime();
  final resp = CkHttpResponse();
  try {
    http.httpStr('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', 'grant_type=client_credentials', 'utf-8', 'application/x-www-form-urlencoded', resp);
  } on ChilkatException catch (e) {
    print('No HTTP response: ${e.lastErrorText}');
    return;
  }

  if ((resp.statusCode < 200) || (resp.statusCode >= 300)) {
    final errorInfo = CkJsonObject();
    errorInfo.load(resp.bodyStr);
    print('HTTP ${resp.statusCode} ${errorInfo.stringOf('error')} ${errorInfo.stringOf('error_description')}');
    print('PayPal debug ID: ${errorInfo.stringOf('debug_id')}');
    return;
  }

  final result = CkJsonObject();
  try {
    result.load(resp.bodyStr);
  } on ChilkatException {
    print('Expected a JSON response; HTTP ${resp.statusCode}');
    return;
  }

  final accessToken = result.stringOf('access_token');
  final lifetime = result.intOf('expires_in');
  if ((!result.hasMember('access_token')) || (lifetime <= 0)) {
    print('Missing token or lifetime.');
    return;
  }

  // Supply accessToken to Http.AuthToken. Never log the bearer token or client secret.
  // Save only timing metadata here, relative to the start of the token request.
  final timing = CkJsonObject();
  timing.updateString('issued_at', issued.getAsTimestamp(false));
  timing.updateInt('expires_in', lifetime);
  try {
    timing.writeFile('paypal-token-timing.json');
  } on ChilkatException {
    print('Could not save token timing.');
    return;
  }

  print('Token received; lifetime in seconds: $lifetime');
}