doujiku1028 2017-02-09 06:18
浏览 17

生成goo.gl不能在localhost上工作

i am trying to dynamically generate the goo.gl links via function.php ,when a post is created ...but its not getting updating the field with the link created on localhost..and i just cant figure out the issue

function newlinks($post_id){
    $permaurl=get_permalink($post_id);  
    $shorturl=make_my_url($permaurl);
    update_post_meta('$post_id','shorturl',$shorturl)

  }
  add_action( 'save_post', 'newlinks' );
    function make_my_url($myurl)
    {

    //got te key from https://console.developers.google.com/iam-admin/projects
    $key = 'AIzBP0';
    $googer = new GoogleURLAPI($key);

    // Test: Shorten a URL
    $shortDWName = $googer->shorten($myurl);
    return $shortDWName; // returns the short url

    }

    // Declare the class
    class GoogleUrlApi {

        // Constructor
        function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
            // Keep the API Url
            $this->apiURL = $apiURL.'?key='.$key;
        }

        // Shorten a URL
        function shorten($url) {
            // Send information along
            $response = $this->send($url);
            // Return the result
            return isset($response['id']) ? $response['id'] : false;
        }
    // Send information to Google
        function send($url,$shorten = true) {
            // Create cURL
            $ch = curl_init();
            // If we're shortening a URL...
            if($shorten) {
                curl_setopt($ch,CURLOPT_URL,$this->apiURL);
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
                curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
            }
            else {
                curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
            }
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            // Execute the post
            $result = curl_exec($ch);
            // Close the connection
            curl_close($ch);
            // Return the result
            return json_decode($result,true);
        }       
    }
  • 写回答

1条回答 默认 最新

  • douxiluan6555 2017-02-09 08:43
    关注

    your code is good. I've created my own API key and tried this and works fine. The problem may be in google console.

    Please login to https://developers.google.com/apis-explorer/?hl=pl#p/urlshortener/v1/ and try to generate short url there. Google should ask you to authorize the key you created before. After that code should work fine.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度