Hướng dẫn laravel salesforce crm

  • April 2, 2021
  • 1069

Hướng dẫn đồng bộ dữ liệu từ web application lên salesforce crm với laravel. Để đồng bộ dữ liệu từ web lên salesforce crm cần làm các bước sau.

Salesforce workflow

1. Get access token


curl -v https://test.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id={client_id}" -d "client_secret={client_secret}" -d "username={user_name}" -d "password={password}"

2. Insert to salesforce


Method: HTTP POST

// Endpoint create data
${endpoint} = ${instance_url}/services/data/v45.0/sobjects

// Command create
curl -v https://${endpoint}/Customer -H 'Authorization: Bearer ${access_token}' -H "Content-Type: application/json" -d "@newcustomer.json"

// Request params
{
    "LastName":"Nguyen",
    "FirstName":"Nguyen",
    "Birthdate":"1999-11-11",
    "Email":"test1@gmail.com",
    "Phone":"09012341178",
    "StartDatetime__c":"2021-04-01T10:00:00+09:00",
}

// Response
{"id":"a00O000000gsLhMIAU","success":true,"errors":[]}
// id là khoá chính dùng để get, update, delete customer in salesforce

3. Get customer


Method: HTTP GET
// Endpoint get data
${endpoint} = ${instance_url}/services/data/v45.0/sobjects

// Command get
curl -v https://${endpoint}/Customer/${Customer.id} -H 'Authorization: Bearer ${access_token}

4. Update customer


// Method: HTTP PATCH
// Endpoint get data
${endpoint} = ${instance_url}/services/data/v45.0/sobjects

// Command update customer
curl -v https://${endpoint}/Customer/${Customer.id} -H 'Authorization: Bearer ${access_token}' -H "Content-Type: application/json" -d "@patchcustomer.json" -X PATCH

// Request params
{
    "LastName":"Nguyen",
    "FirstName":"Nguyen",
    "Birthdate":"1999-11-11",
    "Email":"test@gmail.com",
    "Phone":"09012345118",
    "StartDatetime__c":"2021-04-01T10:00:00+09:00",
}

5. Query to salesforce crm


Method: HTTP GET
// Endpoint get data
${endpoint} = ${instance_url}/services/data/v45.0/query

// Command get
curl -v https://${endpoint}/Customer -H 'Authorization: Bearer ${access_token}' -d "@querystring.json"

Sync data to salesforce crm with laravel

Create config salesforce

Tạo file config salesforce config/salesforce.php


<?php

return [
    'active' => env('SALES_FORCE_ACTIVE', false),
    'url' => env('SALES_FORCE_URL', ''),
    'grant_type' => env('SALES_FORCE_GRANT_TYPE', ''),
    'client_id' => env('SALES_FORCE_CLIENT_ID', ''),
    'client_secret' => env('SALES_FORCE_SECRET_ID', ''),
    'username' => env('SALES_FORCE_USERNAME', ''),
    'password' => env('SALES_FORCE_PASSWORD', ''),
];

Create salesforce service

Tạo service xử lí salesforce app/Services/SalesforceService.php


<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Exception;

class SalesforceService
{
    protected const QUERY_SALESFORCE = 'services/data/v45.0/query';
    protected const CURD_SALESFORCE = 'services/data/v45.0/sobjects';
    protected $config = [];
    protected $authToken = [];
    protected $accessToken = '';

    public function __construct()
    {
        if (!config('salesforce.active')) {
            return ;
        }
        $this->config = [
            'grant_type' => config('salesforce.grant_type'),
            'client_id' => config('salesforce.client_id'),
            'client_secret' => config('salesforce.client_secret'),
            'username' => config('salesforce.username'),
            'password' => config('salesforce.password')
        ];
        $this->setSalesforceToken();
    }

    /**
     * Get and set access token salesforce crm
     *
     * @return void
     */
    private function setSalesforceToken(): void
    {
        try {
            $response = Http::asForm()->post(
                config('salesforce.url'),
                $this->config
            );
            if ($response->successful()) {
                $data = $response->json();
                if (!empty($data['access_token']) && !empty($data['instance_url'])) {
                    $this->authToken = $data;
                    $this->accessToken = $this->authToken['access_token'];
                }
            }
        } catch (Exception $e) {
            Log::error('ERROR_SET_SALESFORCE_TOKEN => ' . $e->getMessage());
        }
    }

    /**
     * Insert data to salesforce
     *
     * @param array $data Data insert.
     * @param string $table Table in salesforce.
     *
     * @return null|array
     */
    public function insertToSalesforce(array $data, string $table): ?array
    {
        try {
            if (!config('salesforce.active')) {
                return null;
            }
            $url = sprintf("%s/%s/%s", $this->authToken['instance_url'], self::CURD_SALESFORCE, $table);
            $response = Http::withToken($this->accessToken)->post($url, $data);
            if (!$response->successful()) {
                Log::error('ERROR_INSERT_TO_SALESFORCE: Table '. $table . ' Data: '. json_encode($data));
                
                return null;
            }
            
            return $response->json();
        } catch (Exception $e) {
            Log::error('ERROR_INSERT_TO_SALESFORCE: Table '. $table . ' Message: '. $e->getMessage());

            return null;
        }
    }

    /**
     * Update data to salesforce
     *
     * @param array $data Data insert.
     * @param string $table Table in salesforce.
     * @param string $id Salesforce id.
     *
     * @return null|array
     */
    public function updateToSalesforce(array $data, string $table, string $id): ?array
    {
        try {
            if (!config('salesforce.active')) {
                return null;
            }
            $url = sprintf("%s/%s/%s/%s", $this->authToken['instance_url'], self::CURD_SALESFORCE, $table, $id);
            $response = Http::withToken($this->accessToken)->patch($url, $data);
            if (!$response->successful()) {
                Log::error('ERROR_UPDATE_TO_SALESFORCE: Table '. $table . ' Data: '. json_encode($data));
                
                return null;
            }
            
            return $response->json();
        } catch (Exception $e) {
            Log::error('ERROR_UPDATE_TO_SALESFORCE: Table '. $table . ' Message: '. $e->getMessage());

            return null;
        }
    }

    /**
     * Find data to salesforce
     *
     * @param string $table Table in salesforce.
     * @param string $id Salesforce id.
     *
     * @return null|array
     */
    public function findToSalesforce(string $table, string $id): ?array
    {
        try {
            if (!config('salesforce.active')) {
                return null;
            }
            $url = sprintf("%s/%s/%s/%s", $this->authToken['instance_url'], self::CURD_SALESFORCE, $table, $id);
            $response = Http::withToken($this->accessToken)->get($url);
            if (!$response->successful()) {
                Log::error('ERROR_FIND_TO_SALESFORCE: Table '. $table . 'Id: '. json_encode($id));
                
                return null;
            }
            
            return $response->json();
        } catch (Exception $e) {
            Log::error('ERROR_FIND_TO_SALESFORCE: Table '. $table . ' Message: '. $e->getMessage());

            return null;
        }
    }

    /**
     * Query data to salesforce
     *
     * @param string $table Table in salesforce.
     * @param string $query Query.
     *
     * @return null|array
     */
    public function queryToSalesforce(string $query): ?array
    {
        try {
            if (!config('salesforce.active')) {
                return null;
            }
            $url = sprintf("%s/%s", $this->authToken['instance_url'], self::QUERY_SALESFORCE);
            $data = ['q' => $query];
            $response = Http::withToken($this->accessToken)->get($url, $data);
            if (!$response->successful()) {
                Log::error('ERROR_QUERY_TO_SALESFORCE: '. json_encode($data));
                
                return null;
            }
            
            return $response->json();
        } catch (Exception $e) {
            Log::error('ERROR_QUERY_TO_SALESFORCE: '. $e->getMessage());

            return null;
        }
    }
}

Sync data to salesforce crm

Giờ để sync data với salesforce crm chỉ đơn giản là gọi các function trong service đã viết ở trên. Tạo contronller và sync data thôi.


<?php

namespace App\Http\Controllers;

use App\Services\SalesforceService;

class SalesforceController extends Controller
{
    protected $salesforceService;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->salesforceService = app(SalesforceService::class);
    }

    /**
     * Get data salesforce.
     *
     * @return mixed
     */
    public function index()
    {
        $query = "select Id from Account where Id = '001O000001lxQatIAE'";
        $this->salesforceService->queryToSalesforce($query);
    }

    /**
     * Insert data to salesforce.
     *
     * @return mixed
     */
    public function store()
    {
        $data = [
            "LastName" => "test",
            "FirstName" => "test",
            "Birthdate" => "1999-11-11",
            "Email" => "test123@gmail.com",
            "Phone" => "09012345777"
        ];
        $this->salesforceService->insertToSalesforce($data, 'Account', '001O000001lxQatIAE');
    }

    /**
     * Update data to salesforce.
     *
     * @return mixed
     */
    public function update()
    {
        $data = [
            "FirstName" => "test2",
            "Phone" => "09012345111"
        ];
        $this->salesforceService->updateToSalesforce($data, 'Account', '001O000001lxQatIAE');
    }

    /**
     * Show data salesforce.
     *
     * @return mixed
     */
    public function show()
    {
        $this->salesforceService->findToSalesforce('001O000001lxQatIAE');
    }
}

Như vậy là chúng ta đã sync dữ liệu cho salesforce thành công, giờ thì vào trang quản trị của salesforce để kiểm tra dữ liệu nhé. Chúc các bạn sync data thành công :D