PHP code example of freee / freee-accounting-sdk

1. Go to this page and download the library: Download freee/freee-accounting-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

freee / freee-accounting-sdk example snippets


        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            // ↓↓ ここから ↓↓
            $table->unsignedBigInteger('freee_id')->unique();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('first_name')->nullable();
            $table->string('last_name')->nullable();
            $table->string('token')->nullable();
            $table->rememberToken();
            // ↑↑ ここまで編集 ↑↑
            $table->timestamps();
        });

    protected $fillable = [
        // ↓↓ ここから ↓↓
        // 'name', 'email', 'password',
        'name', 'email', 'freee_id', 'first_name', 'last_name', 'token'
        // ↑↑ ここまで編集 ↑↑
    ];

    'providers' => [
        // ... 中略 ...
        SocialiteProviders\Generators\GeneratorsServiceProvider::class,
        SocialiteProviders\Manager\ServiceProvider::class,
        // ... 中略 ...
    ],

// Auth::routes();
Auth::routes([
    'register' => false,
    'reset' => false,
]);

Route::get('login', 'Auth\LoginController@redirectToProvider')->name('login');
Route::get('auth-callback', 'Auth\LoginController@handleProviderCallback')->name('authCallback');



return [

    // ... 中略 ...

    // ↓↓ ここから ↓↓
    'freeeaccounting' => [
        'client_id' => env('FREEE_ACCOUNTING_CLIENT_ID'),
        'client_secret' => env('FREEE_ACCOUNTING_CLIENT_SECRET'),
        'redirect' => 'http://localhost:8000/auth-callback',
    ],
    // ↑↑ ここまで編集 ↑↑
];

    protected function getUserByToken($token)
    {
        // ... 中略 ...

        // ↓↓ ここから ↓↓
        // return json_decode($response->getBody(), true);
        $body = json_decode($response->getBody(), true);
        return $body['user'];
        // ↑↑ ここまで編集 ↑↑
    }

    protected function mapUserToObject(array $user)
    {
        // ↓↓ ここから ↓↓
        $user['name'] = $user['last_name'] . ' ' . $user['first_name'];
        // ↑↑ ここまで追加 ↑↑

        return (new User())->setRaw($user)->map([
            'id'       => $user['id'],
            // 'nickname' => $user['username'],
            'name'     => $user['name'],
            'email'    => $user['email'],
            // 'avatar'   => $user['avatar'],
            // ↓↓ ここから ↓↓
            'display_name' => $user['display_name'],
            'first_name' => $user['first_name'],
            'last_name' => $user['last_name'],
            'first_name_kana' => $user['first_name_kana'],
            'last_name_kana' => $user['last_name_kana'],
            // ↑↑ ここまで追加 ↑↑
        ]);
    }



namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
// ↓↓ ここから ↓↓
// use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use App\User;
// ↑↑ ここまで編集 ↑↑

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    // ↓↓ ここから ↓↓
    // use AuthenticatesUsers;
    // ↑↑ ここまで編集 ↑↑

    // ... 中略 ...

    // ↓↓ ここから ↓↓
    /**
     * Redirect the user to the Freee Accounting authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('freeeaccounting')->redirect();
    }

    /**
     * Obtain the user information from Freee Accounting.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('freeeaccounting')->user();

        $loggedInUser = User::updateOrCreate(
            [
                'freee_id' => $user->id,
            ],
            [
                'name' => $user->name,
                'email' => $user->email,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'token' => $user->token,
            ]
        );

        Auth::login($loggedInUser);
        return redirect($this->redirectTo);
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->intended('/');
    }
    // ↑↑ ここまで追加 ↑↑
}



namespace App\Providers;

// ... 中略 ...

// ↓↓ ここから ↓↓
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\FreeeAccounting\FreeeAccountingExtendSocialite;
// ↑↑ ここまで追加 ↑↑

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        // ↓↓ ここから ↓↓
        SocialiteWasCalled::class => [
            FreeeAccountingExtendSocialite::class,
        ],
        // ↑↑ ここまで追加 ↑↑
    ];

    // ... 略 ...
}




namespace App\Http\Controllers;

// ↓↓ ここから ↓↓
// use Illuminate\Http\Request;
use Freee\Accounting\Configuration;
use Freee\Accounting\Api\CompaniesApi;
use Freee\Accounting\Api\DealsApi;
use Illuminate\Support\Facades\Auth;
// ↑↑ ここまで編集 ↑↑

class AccountController extends Controller
{
    //

    // ↓↓ ここから ↓↓
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display information of current user.
     *
     * @return \Illuminate\View\View
     */
    public function me()
    {
        $user = Auth::user();

        $config = Configuration::getDefaultConfiguration()->setAccessToken($user->token);

        $companiesApiInstance = new CompaniesApi(null, $config);
        $companiesResponse = $companiesApiInstance->getCompanies();

        $dealsApiInstance = new DealsApi(null, $config);
        $targetCompanyId = $companiesResponse->getCompanies()[0]->getId();
        $dealsNumberlimit = 5;
        $dealsResponse = $dealsApiInstance->getDeals(
            $targetCompanyId,
            null, null, null, null, null, null, null, null, null, null, null, null,
            $dealsNumberlimit);
        $deals = $dealsResponse->getDeals();

        $invoicesApiInstance = new InvoicesApi(null, $config);
        $invoicesResponse = $invoicesApiInstance->getInvoices($targetCompanyId);
        $invoices = $invoicesResponse->getInvoices();

        return view('account.me', compact('user', 'deals', 'invoices'));
    }
    // ↑↑ ここまで追加 ↑↑
}

Route::get('/account/me', 'AccountController@me')->name('me');

<!-- ... 中略 ... -->

<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
    <!-- Authentication Links -->
    @guest
        <li class="nav-item">
            <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
        </li>
        @if (Route::has('register'))
            <li class="nav-item">
                <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
            </li>
        @endif
    @else
        <li class="nav-item dropdown">
            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                {{ Auth::user()->name }} <span class="caret"></span>
            </a>

            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                <!-- ↓↓ ここから ↓↓ -->
                <a class="dropdown-item" href="{{ route('me') }}">
                    {{ __('Me') }}
                </a>
                <!-- ↑↑ ここまで追加 ↑↑ -->
                <a class="dropdown-item" href="{{ route('logout') }}"
                    onclick="event.preventDefault();
                                  document.getElementById('logout-form').submit();">
                    {{ __('Logout') }}
                </a>

<!-- ... 略 ... -->
bash
# パッケージをインストールする
composer install

# Application encryption key を発行する
php artisan key:generate

# sqlite ファイルを作成し、マイグレーションを実行する
touch database/database.sqlite
php artisan migrate

# Laravel の内蔵サーバーを実行する
php artisan serve

# ※ Docker で動かしている場合は、下記のように host を指定する
php artisan serve --host 0.0.0.0
bash
# パッケージをインストールする
composer install

# php を interactive modeで実行する
php -a
php >figuration::getDefaultConfiguration()->setAccessToken($token);
php >$partnersApiInstance = new Freee\Accounting\Api\PartnersApi(null, $config);
php >echo $partnersApiInstance->getPartners($cid);
bash
# 自動作成されたマイグレーションファイルを削除する
rm database/migrations/2014_10_12_000000_create_users_table.php
# マイグレーションを作成する
php artisan make:migration create_users_table --create=users
bash
# sqlite ファイルを作成し、マイグレーションを実行する
touch database/database.sqlite
php artisan migrate
bash
php artisan make:controller AccountController