Using the Microsoft Dynamics 365 Business Central API to Get Contacts (with PHP examples)

by Endgrate Team 2024-08-03 5 min read

Microsoft Dynamics 365 Business Central homepage

Introduction to Microsoft Dynamics 365 Business Central

Microsoft Dynamics 365 Business Central is a comprehensive business management solution designed for small to medium-sized businesses. It offers a wide range of functionalities, including finance, sales, service, and operations, all integrated into a single platform. This enables businesses to streamline their processes, make informed decisions, and accelerate growth.

For developers, integrating with Microsoft Dynamics 365 Business Central's API can unlock powerful capabilities to manage and interact with business data programmatically. By connecting with the API, developers can automate tasks such as retrieving and managing contact information, which is crucial for maintaining customer relationships and enhancing business operations.

An example use case for integrating with the Microsoft Dynamics 365 Business Central API is to automate the retrieval of contact details for a company's clients. This can be particularly useful for businesses looking to synchronize their CRM systems with Business Central, ensuring that all customer data is up-to-date and accessible across platforms.

Setting Up a Microsoft Dynamics 365 Business Central Sandbox Account

Before you can start integrating with the Microsoft Dynamics 365 Business Central API, you'll need to set up a sandbox account. This environment allows you to test and develop your applications without affecting live data.

Creating a Microsoft Dynamics 365 Business Central Sandbox Account

To create a sandbox account, follow these steps:

  1. Visit the Microsoft Dynamics 365 Business Central website and sign up for a free trial if you don't already have an account.
  2. Once logged in, navigate to the Admin Center and select Environments.
  3. Click on New to create a new environment, and choose Sandbox as the type.
  4. Fill in the required details and click Create to set up your sandbox environment.

Registering an Application for OAuth Authentication

Since the Microsoft Dynamics 365 Business Central API uses OAuth for authentication, you'll need to register an application in your Microsoft Entra ID tenant. Follow these steps:

  1. Go to the Azure Portal and sign in with your Microsoft account.
  2. Navigate to Azure Active Directory and select App registrations.
  3. Click on New registration and provide a name for your application.
  4. Set the Redirect URI to https://localhost for local development.
  5. Click Register to create the application.

Generating Client ID and Client Secret

After registering your application, you need to generate the client ID and client secret:

  1. In the Azure Portal, navigate to your registered application and select Certificates & secrets.
  2. Under Client secrets, click New client secret.
  3. Provide a description and set an expiration period, then click Add.
  4. Copy the client secret value immediately, as it will not be displayed again.

Assigning API Permissions

To access the Business Central API, assign the necessary permissions:

  1. In your registered application, go to API permissions and click Add a permission.
  2. Select APIs my organization uses and search for Dynamics 365 Business Central.
  3. Choose the appropriate permissions, such as user_impersonation, and click Add permissions.

With your sandbox account and application registration complete, you're ready to start interacting with the Microsoft Dynamics 365 Business Central API using OAuth authentication. For more detailed information, refer to the official documentation on OAuth authentication with Microsoft Dataverse.

Microsoft Dynamics 365 Business Central authentication documentation page.
sbb-itb-96038d7

Making API Calls to Microsoft Dynamics 365 Business Central with PHP

To interact with the Microsoft Dynamics 365 Business Central API using PHP, you'll need to set up your environment and write code to authenticate and make requests. This section will guide you through the process of retrieving contact information using PHP.

Setting Up Your PHP Environment

Ensure you have the following prerequisites installed on your machine:

  • PHP 7.4 or higher
  • Composer for dependency management

You'll also need to install the Guzzle HTTP client, which simplifies making HTTP requests in PHP. Run the following command to install Guzzle:

composer require guzzlehttp/guzzle

Authenticating with OAuth to Access Microsoft Dynamics 365 Business Central API

Before making API calls, authenticate using OAuth to obtain an access token. Here's a sample PHP script to authenticate:


require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();
$response = $client->post('https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token', [
    'form_params' => [
        'client_id' => 'Your_Client_ID',
        'client_secret' => 'Your_Client_Secret',
        'scope' => 'https://api.businesscentral.dynamics.com/.default',
        'grant_type' => 'client_credentials'
    ]
]);

$body = json_decode($response->getBody(), true);
$accessToken = $body['access_token'];

Replace Your_Client_ID, Your_Client_Secret, and {tenant_id} with your actual credentials.

Retrieving Contacts from Microsoft Dynamics 365 Business Central

Once authenticated, you can make a GET request to retrieve contact information. Here's how you can do it:


$response = $client->get('https://api.businesscentral.dynamics.com/v2.0/{businesscentralPrefix}/companies({company_id})/contacts', [
    'headers' => [
        'Authorization' => 'Bearer ' . $accessToken,
        'Content-Type' => 'application/json'
    ]
]);

$contacts = json_decode($response->getBody(), true);
foreach ($contacts['value'] as $contact) {
    echo 'Contact Name: ' . $contact['displayName'] . "\n";
}

Replace {businesscentralPrefix} and {company_id} with your specific Business Central environment details.

Handling API Response and Errors

Check the response status code to ensure the request was successful. A 200 OK status indicates success. Handle errors by checking for other status codes and logging the response:


if ($response->getStatusCode() === 200) {
    // Process the contacts
} else {
    echo 'Error: ' . $response->getStatusCode() . ' - ' . $response->getReasonPhrase();
}

For more detailed error handling, refer to the official API documentation.

Microsoft Dynamics 365 Business Central API call documentation page.

Conclusion and Best Practices for Using Microsoft Dynamics 365 Business Central API with PHP

Integrating with the Microsoft Dynamics 365 Business Central API using PHP provides a powerful way to manage business data programmatically. By following the steps outlined in this guide, you can efficiently retrieve and handle contact information, enhancing your business operations and customer relationship management.

Best Practices for Secure and Efficient API Integration

  • Securely Store Credentials: Always store your client ID and client secret securely, using environment variables or a secure vault, to prevent unauthorized access.
  • Handle Rate Limiting: Be aware of API rate limits and implement retry logic with exponential backoff to handle any rate limit errors gracefully.
  • Standardize Data Fields: Ensure that data retrieved from the API is standardized and transformed as needed to fit your application's data model.
  • Monitor API Usage: Regularly monitor your API usage and performance to identify any potential issues or optimizations.

Streamlining Integrations with Endgrate

While integrating with Microsoft Dynamics 365 Business Central API can be highly beneficial, managing multiple integrations can be challenging. This is where Endgrate can help. By using Endgrate, you can save time and resources by outsourcing integrations, allowing you to focus on your core product. Endgrate provides a unified API endpoint that simplifies the integration process, offering an intuitive experience for your customers.

Explore how Endgrate can enhance your integration capabilities by visiting Endgrate's website and discover how it can streamline your business processes.

Read More

Ready to get started?

Book a demo now

Book Demo