0

I am connecting to the BitBucket API and would like to be able to download the zip file of a repository to the server. Due to the repositories being private it requires user access.

I can download the file by the user login details within the link:

https://{user}:{pass}@bitbucket.org/{owner_name}/{repository}/get/master.zip

But I would like to be able to download the file by using the access token via the API most likely by cURL or by any other means.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Ufb007
  • 243
  • 2
  • 8

2 Answers2

2

I've been using this function to download a repository from bitbucket:

function download($url, $destination) {
    try {
        $fp = fopen($destination, "w");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, USERNAME . ":" . PASSWORD);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $resp = curl_exec($ch);

        if(curl_errno($ch)){
            throw new Exception(curl_error($ch), 500);
        }

        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($status_code != 200) {
            throw new Exception("Response with Status Code [" . $status_code . "].", 500);
        }
    }
    catch(Exception $ex) {
        if ($ch != null) curl_close($ch);
        if ($fp != null) fclose($fp);
        throw new Exception('Unable to properly download file from url=[' + $url + '] to path [' + $destination + '].', 500, $ex);
    }
    if ($ch != null) curl_close($ch);
    if ($fp != null) fclose($fp);
}
thmspl
  • 2,437
  • 3
  • 22
  • 48
0

I have found that by cloning the repository using ssh works perfectly. By having a ssh key generated already and then by doing a POST to the Bitbucket API ssh-key, I can then use the git commands without any restrictions. I also had to allow Bitbucket.org within the .ssh/known_hosts file to get access.

Overall this method is the best and only way if you wanted to get access to the src files from the repositories.

Ufb007
  • 243
  • 2
  • 8
  • Just to add to my response. This only works for one account only as the SSH key can not be used for more than one BitBucket account. To get around this I had to use BitBucket's OAuth 2 which gives me clone a repository by the access token provided. – Ufb007 Jul 13 '15 at 00:48