#由內向外打API

#學習如何串接別人的API(試著做出縮網址功能)

1.首先開啟ProductController 建立新的函式, 並建立一個新的Class service專門來與API作交換資料

根據使用者點擊後提供縮網址的功能讓使用者分享

1630345683574.jpg

然後待會在App\Http\Services去建立我們的Class ShortUrlService,這邊先引入

1630345743267.jpg

2.在Http資料夾下建立Services,並創建ShortUrlService.php檔案,作為我們縮網址

1630345863818.jpg

3.於ShortUrlService.php 建立namespace, 並使用Guzzle\Http\Client

<?php

namespace App\\Http\\Services;

use GuzzleHttp\\Client;
use PhpParser\\Node\\Expr\\FuncCall;

Class ShortUrlService{

    protected $client;
    public function __construct()
    {
        $this->client = new Client();
    }

    public function makeShortUrl($url)
    {
        $accesstoken = '20f07f91f3303b2f66ab6f61698d977d69b83d64';
        $data = [
            'url' => $url
        ];
        $response = $this->client->request(
            'POST',
            "<https://api.pics.ee/v1/links/?access_token=$accesstoken>",
            [
                'headers'=> ['Content-Type' => 'appliction/json'],
                'body' => json_encode($data)
            ]
        );

        $contents = $response->getBody()->getContents();
        $contents = json_decode($contents);
        return $contents->data->picseeUrl;
    }
}

4.設定路由

Route::get('/products/{id}/shared-url','ProductController@shareUrl');

5.接著設定前端程式碼

<input class="check_url" type="button" value="短網址">

<script>
    $('.check_url').on('click',function(){
    var id = $(this).data('id');
        $.ajax({
            method: 'GET',
            url:`/product/${id}/shared-url`,
        })
        .done(function(msg){
            alert('請分享此縮網址' + msg.url)
        })
    })
</script>

6.避免將 $accesstoken = '20f07f91f3303b2f66ab6f61698d977d69b83d64';寫在程式碼裡

故通常都會在.env檔裡建立一個名為URL_ACCESS_TOKEN