Google API - URL Shortener with PHP

后端 未结 8 2014
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 12:24

My code is below. The URL shortening service works, but it doesn\'t when I insert my $POST. Does anyone know how to fix this my looking at the code?



        
相关标签:
8条回答
  • 2021-02-02 12:56

    You have a key, but you are not using it correctly

    You should append it to the url, don't send the key in the post

    https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey
    

    Please check https://developers.google.com/url-shortener/v1/url/insert

    0 讨论(0)
  • 2021-02-02 13:00

    Try with this code. I is working for me.

    $api_key = 'YOUR_KEY';
    $request_data = array(
        'longUrl' => 'YOUR_LONG_URL'
    );
    
    $curl_obj = curl_init(sprintf('%s/url?key=%s', 'https://www.googleapis.com/urlshortener/v1', $api_key));
    curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_obj, CURLOPT_POST, true);
    curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($curl_obj, CURLOPT_POSTFIELDS, json_encode($request_data));
    curl_setopt($curl_obj, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_obj, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($curl_obj);
    $json = json_decode($response);
    curl_close($curl_obj);
    
    var_dump($json);
    die();
    
    0 讨论(0)
提交回复
热议问题