---
tags: PHP, Backend, Laravel
disqus: HackMD
---
# Laravel use Business Profile APIs
## 前置條件
1. 前往 [Google API 控制台](https://console.cloud.google.com/cloud-resource-manager),並選取您為商家檔案使用的專案。
1. 如要確認專案 ID,請查看「Project ID」欄。
1. 填寫並提交[存取權申請表](https://docs.google.com/forms/d/e/1FAIpQLSfC_FKSWzbSae_5rOpgwFeIUzXUF1JCQnlsZM_gC1I2UHjA3w/viewform)。
1. 我們會在審查完成後,透過電子郵件通知您。
1. 取得核准之後,請參閱「[基本設定](https://developers.google.com/my-business/content/basic-setup)」來為專案啟用 Business Profile API。
送出審查表單後大約兩到三天就會收到一封確認信件,回信後大概兩三天就會收到審查通過的信件,就可以開始使用`Business Profile API`。
更多[詳細內容](https://developers.google.com/my-business/content/prereqs)
## 創建憑證
需先建立`API`金鑰以及`OAuth`
![](https://i.imgur.com/8uDy0RS.png)
### 建立API金鑰
API部分需先將以下與商家檔案關聯API啟用:
1. [My Business Account Management API](https://console.cloud.google.com/apis/library/mybusinessaccountmanagement.googleapis.com)
2. [My Business Business Calls API](https://console.cloud.google.com/apis/library/mybusinessbusinesscalls.googleapis.com?project=constant-crow-291608)
3. [My Business Lodging API](https://console.cloud.google.com/apis/library/mybusinesslodging.googleapis.com?project=constant-crow-291608)
4. [My Business Notifications API](https://console.cloud.google.com/apis/library/mybusinessnotifications.googleapis.com?project=constant-crow-291608)
5. [My Business Place Actions API](https://console.cloud.google.com/apis/library/mybusinessplaceactions.googleapis.com?project=constant-crow-291608)
6. [My Business Account Management API](https://console.cloud.google.com/apis/library/mybusinessaccountmanagement.googleapis.com?project=constant-crow-291608)
7. [My Business Q&A API](https://console.cloud.google.com/apis/library/mybusinessqanda.googleapis.com?project=constant-crow-291608)
8. [My Business Verifications API](https://console.cloud.google.com/apis/library/mybusinessverifications.googleapis.com?project=constant-crow-291608)
9. [Business Profile Performance API](https://console.cloud.google.com/apis/library/businessprofileperformance.googleapis.com?project=constant-crow-291608)
啟用後建立,可以限制API可以呼叫的範圍
![](https://i.imgur.com/5tiUuWT.jpg)
### 建立 OAuth 用戶端 ID
這邊填上要call back的url位置
![](https://i.imgur.com/Ppop5K0.jpg)
建立好OAuth用戶端後點選下載JSON後面會用到
![](https://i.imgur.com/H20PJRV.jpg)
## 實戰範例
### 測試環境
```
"php": "^7.2",
"laravel/framework": "^7.0",
```
### 安裝Google client
下指令安裝[googleapis/google-api-php-client](https://github.com/googleapis/google-api-php-client)
```shell=
composer require google/apiclient:^2.12.1
```
安裝完成後你可以只選擇你需要的服務,有超過 200 個 Google API 服務。您很可能不想要所有這些。
`composer/json`:
```json=
{
"require": {
"google/apiclient": "^2.12.1"
},
"scripts": {
"pre-autoload-dump": "Google\\Task\\Composer::cleanup"
},
"extra": {
"google/apiclient-services": [
"MyBusinessAccountManagement",
"MyBusinessBusinessCalls",
"MyBusinessBusinessInformation",
"MyBusinessLodging",
"MyBusinessNotificationSettings",
"MyBusinessPlaceActions",
"MyBusinessQA",
"MyBusinessVerifications",
"BusinessProfilePerformance"
]
}
}
```
更改完成後記得下`composer dump-autoload`
### 新建`google`相關`config`檔案
新建完成後記得去 `.env` 檔案填入相關資訊
`google.php`
```php=
<?php
return [
/*
|----------------------------------------------------------------------------
| Google application name
|----------------------------------------------------------------------------
*/
'application_name' => env('GOOGLE_APPLICATION_NAME', ''),
/*
|----------------------------------------------------------------------------
| Google OAuth 2.0 access
|----------------------------------------------------------------------------
|
| Keys for OAuth 2.0 access, see the API console at
| https://developers.google.com/console
|
*/
'redirect_uri' => env('GOOGLE_REDIRECT_URI', ''),
'scopes' => [
'https://www.googleapis.com/auth/business.manage',
'https://www.googleapis.com/auth/plus.business.manage',
],
/*
|----------------------------------------------------------------------------
| Google developer key
|----------------------------------------------------------------------------
|
| Simple API access key, also from the API console. Ensure you get
| a Server key, and not a Browser key.
|
*/
'developer_key' => env('GOOGLE_DEVELOPER_KEY', ''),
/*
|----------------------------------------------------------------------------
| Google service account
|----------------------------------------------------------------------------
*/
'service' => [
/*
* Path to service account json file. You can also pass the credentials as an array
* instead of a file path.
*/
'file' => env('GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION', ''),
],
];
```
### 撈取商家檔案成效範例
接下來將透過API方式去取得**經由商家檔案提出的路線要求**次數
![](https://i.imgur.com/VnCfsVa.jpg)
觀看[文檔](https://developers.google.com/my-business/reference/performance/rest)可以看到撈取商家相關數據是使用 `Business Profile Performance API`
接下來查看`google`已經寫好的`services` ->[google-api-php-client-services](https://github.com/googleapis/google-api-php-client-services/blob/main/src/BusinessProfilePerformance/Resource/Locations.php)
從下圖就可以看到使用此`services`的方法,那就實際操作試試
![](https://i.imgur.com/wNMZTwG.jpg)
先到你管理的商家取得商家ID
![](https://i.imgur.com/Y9TPBfa.jpg)
創建`Controller`,並將`{location_id}`換成你的商家ID
```php=
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Google;
class TestController extends Controller
{
public function __construct()
{
$this->client = new Google\Client();
$this->client->setApplicationName(config('google.application_name'));
$this->client->setDeveloperKey(config('google.developer_key'));
$this->client->setAuthConfig(storage_path(config('google.service.file')));
$this->client->addScope(config('google.scopes'));
}
public function redirect()
{
return redirect($this->client->createAuthUrl());
}
public function callback(Request $request)
{
$code = $request->get('code');
$token = $this->client->fetchAccessTokenWithAuthCode($code);
$this->client->setAccessToken($token);
$businessprofileperformanceService = new Google\Service\BusinessProfilePerformance($this->client);
$locations = $businessprofileperformanceService->locations;
$location = $locations->getDailyMetricsTimeSeries('locations/{location_id}', [
'dailyMetric' => 'BUSINESS_DIRECTION_REQUESTS',
'dailyRange.endDate.day' => 30,
'dailyRange.endDate.month' => 12,
'dailyRange.endDate.year' => 2022,
'dailyRange.startDate.day' => 1,
'dailyRange.startDate.month' => 7,
'dailyRange.startDate.year' => 2022,
// 'dailySubEntityType.timeOfDay.hours' => 0,
// 'dailySubEntityType.timeOfDay.minutes' => 0,
// 'dailySubEntityType.timeOfDay.nanos' => 0,
// 'dailySubEntityType.timeOfDay.seconds' => 0,
]);
$total = 0;
foreach ($location->getTimeSeries() as $key => $value) {
$date = $value->getDate();
$total += $value->getValue();
}
return response()->json([
'status' => 'success',
'message' => '經由商家檔案提出的路線要求次數' . $total
], 200, [], JSON_UNESCAPED_UNICODE);
}
}
```
路由:
```php=
Route::get('redirect/mybusiness', 'TestController@redirect');
Route::get('callback/google/mybusiness', 'TestController@callback');
```
完成後前往`redirect/mybusiness`,可以得到以下回傳值
```json=
{
"status":"success",
"message":"經由商家檔案提出的路線要求次數226"
}
```
如果要使用其他`API`也是依樣畫葫蘆,為以下步驟
**需求 > 查看文檔 > 查找`Google client services`並使用**
有些功能`google`還未其寫成`services`,就可以需要費點力了。
例如我們要對[商家檔案的評論](https://developers.google.com/my-business/reference/rest/v4/accounts.locations.reviews/list)進行查看,仿照`google`撰寫`services`方式,之後就可以透過類似方法取得商家檔案相關評論。
```php=
$myBusinessAccountLocations = new MyBusinessAccountLocations($client);
$reviews = $myBusinessAccountLocations->reviews;
$resList = $reviews->listAccountsLocationsReviews('accounts/{acount_id}/locations/{location_id}');
foreach ($resList->getReviews() as $review) {
// get the reply to the review
$review->getComment();
}
```
## 範例程式碼位置
[Github](https://github.com/joe94113/laravel-business-profile-API-example)