PHP调用百度api生成短网址&根据短网址恢复长网址

时间:2024-02-21 19:00:58
  • 接口api文档地址:http://dwz.cn/#/apidoc?_k=i9ev5p
  •  代码demo
    header("Content-type: text/html; charset=utf-8");
        /**
         * 生成短网址
         */
        //短网址生成接口地址&传递的参数
        $url = "http://dwz.cn/admin/create";
        $param = [
            "url"=>"http://www.baidu.com",
        ];
    
        //curl初始化&curl配置
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        //执行cURL会话
        $ret = curl_exec($ch);
        //获取cURL连接资源句柄的信息
        $retInfo = curl_getinfo($ch);
    
        if($retInfo[\'http_code\'] == 200){
            $data = json_decode($ret, true);
            /**
             * Code:0:正常返回短网址,-1:短网址生成失败,-2:长网址不合法,-3:长网址存在安全隐患,-4:长网址插入数据库失败,-5:长网址在黑名单中,不允许注册;
             * ShortUrl:短网址
             * LongUrl:长网址(原网址)
             * ErrMsg:错误信息
             */
            if($data[\'Code\'] != 0){
                echo \'短网址生成失败,错误原因为:\' . $data[\'ErrMsg\'];
            }else{
                echo \'短网址生成成功!由[\'.$data[\'LongUrl\'].\']生成的短网址为:[\'.$data[\'ShortUrl\'].\']\';
            }
        }else{
            echo \'make short url failed\';
        }
    
    echo "<hr>";
        /**
         * 短网址还原
         */
        //短网址还原接口地址&传递的参数
        $url = "http://dwz.cn/admin/query";
        $param = [
            "shortUrl"=>"http://dwz.cn/de3rp2Fl",
        ];
    
        //curl初始化&curl配置
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        //执行cURL会话
        $ret = curl_exec($ch);
        //获取cURL连接资源句柄的信息
        $retInfo = curl_getinfo($ch);
    
        if($retInfo[\'http_code\'] == 200){
            $data = json_decode($ret, true);
            /**
             * Code:0:正常返回短网址,-1:短网址对应的长网址不合法,-2:短网址不存在,-3:查询的短网址不合法;
             * ShortUrl:短网址
             * LongUrl:长网址(原网址)
             * ErrMsg:错误信息
             */
            if($data[\'Code\'] != 0){
                echo \'短网址恢复失败,错误原因为:\' . $data[\'ErrMsg\'];
            }else{
                echo \'短网址恢复成功!由[\'.$data[\'ShortUrl\'].\']恢复的短网址为:[\'.$data[\'LongUrl\'].\']\';
            }
        }else{
            echo \'make short url failed\';
        }

     

  • 还可以使用ajax调用接口获取短链接

  •