Trying To Connect Without Php Plugins

Discussion in 'Shapeways API' started by SandWalletStore, Jul 2, 2018.

  1. I am able to connect and get a token with the below code but every attempt to upload a file fails. Can anyone help? Can't use PECL so example code isn't helpful.


    PHP:
    <?php   session_start();
        require_once 
    'config.php';
        
    /* contains

    define('OAUTH2_CLIENT_ID', 'Redacted');
    define('OAUTH2_CLIENT_SECRET', 'Redacted');

    define('OAUTH2_URL_AUTHORIZE','https://api.shapeways.com/oauth2/authorize');
    define('OAUTH2_URL_TOKEN','https://api.shapeways.com/oauth2/token');
    define('OAUTH2_URL_BASE', 'https://api.shapeways.com/');

        */


    function apiRequest($url$post=FALSE$headers=array()) {
      
    $ch curl_init($url);
      
    curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
      if(
    $post)
        
    curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($post));
      
    $headers[] = 'Accept: application/json';
      if(
    session('access_token'))
        
    $headers[] = 'Authorization: Bearer ' session('access_token');
      
    curl_setopt($chCURLOPT_HTTPHEADER$headers);
      
    $response curl_exec($ch);
      return 
    json_decode($response);
    }

    function 
    session($key$default=NULL) {
      return 
    array_key_exists($key$_SESSION) ? $_SESSION[$key] : $default;
    }

        
    //make sure we are connected to shapeways
        
    if (!isset($_SESSION['access_token'])) {
            
    $token=apiRequest(OAUTH2_URL_TOKEN, array(
                
    "grant_type"=>      "client_credentials",
                
    "client_id"=>       OAUTH2_CLIENT_ID,
                
    "client_secret"=>   OAUTH2_CLIENT_SECRET   
            
    ));
            
    $_SESSION['access_token'] = $token->access_token;
        }

        
    //try to upload file
        
    $filename "model_j5yNGd"//does exist
        
    $file file_get_contents($filename);
        
    $data = array(
          
    "fileName" => $filename.'.zip',
          
    "file" => rawurlencode(base64_encode($file)),
          
    "hasRightsToModel" => 1,
          
    "acceptTermsAndConditions" => 1,

        );
        
    $response apiRequest(OAUTH2_URL_BASE ."models/v1"$data,$array);
        
    print_r($response);
        
    /*  expecting
        {
          "result":"success",
          "fileName":"????",
          "contentLength":2250906,
          "fileMd5Checksum":"8f8db6c000934a5ec03c701548bb0daf",
          "modelId":????,
          "modelVersion":0
        }
        */

        /*get
        {
            "result":"failure",
            "reason":"Field is required, but missing. Field is required, but missing.",
            "rateLimit_OkToGo_InSeconds": 0,
            "rateLimit_Window_InMinutes": 5,
            "rateLimit_Limit": 150,
            "rateLimit_Remaining": 149,
            "rateLimit_History": {
                "201807020054": 1
            },
            "rateLimit": {....}
        }       
        */
     
  2. stonysmith
    stonysmith Well-Known Member Moderator
    What messages or return codes are you getting?
     
  3. mctrivia
    mctrivia Well-Known Member
    sorry should have pointed out was commented at end of code block


    {
    "result":"failure",
    "reason":"Field is required, but missing. Field is required, but missing.",
    "rateLimit_OkToGo_InSeconds": 0,
    "rateLimit_Window_InMinutes": 5,
    "rateLimit_Limit": 150,
    "rateLimit_Remaining": 149,
    "rateLimit_History": {
    "201807020054": 1
    },
    "rateLimit": {....}
    }
     
  4. stonysmith
    stonysmith Well-Known Member Moderator
    You are missing ?page=1 on the url. You have to increase the count for each successive page you wish to retrieve.
     
  5. Thanks for trying to help. It still isn't working though.

    I tried adding ?page=count to the end of url and tried adding as post field. both ways it did not fix problem.
     
  6. stonysmith
    stonysmith Well-Known Member Moderator
    My apologies.. not knowing PHP all that well, I mis-read what you were attempting to accomplish.
    I worked thru several changes.. this version actually executed...

    - turned on error logging
    - added a ton of print_r() statements to watch what was going on
    - changed http_build_query() to json_encode() - the body message should be json format, not http
    - added the extension to the filename - might not be right for you
    - removed rawurlencode()
    - in the upload apiRequest, you reference $array, and I don't think that is necessary

    Code:
    <?php
      ini_set("log_errors", 1);
      ini_set("error_log", "./php-error.log");
      error_log( "Hello, errors!" );
      session_start();
      require_once 'config.php';
      print_r("<pre>");
    
    function apiRequest($url, $post=FALSE, $headers=array()) {
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      //$x=http_build_query($post);
      $x=json_encode($post);
      if ($post) {
          curl_setopt($ch, CURLOPT_POSTFIELDS,$x);
        }
      print_r("url=".$url."<br>");
      print_r("data=".$x."<br>");
      $headers[] = 'Accept: application/json';
      if(session('access_token'))
        $headers[] = 'Authorization: Bearer ' . session('access_token');
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      print_r("<br>curl<br>");
      $response = curl_exec($ch);
      print_r($response."<br>");
      return json_decode($response);
    }
    
    function session($key, $default=NULL) {
      return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
    }
    
        //make sure we are connected to shapeways
        print_r("logging in<br>");
        if (!isset($_SESSION['access_token'])) {
            $token=apiRequest(OAUTH2_URL_TOKEN, array(
                "grant_type"=>      "client_credentials",
                "client_id"=>       OAUTH2_CLIENT_ID,
                "client_secret"=>   OAUTH2_CLIENT_SECRET
            ));
            $_SESSION['access_token'] = $token->access_token;
        }
        print_r("logged in<br>");
        print_r($_SESSION);
    
        //try to upload file
        $filename = "Box.stl"; //does exist
        $file = file_get_contents($filename);
        $data = array(
          "fileName" => $filename,
          "uploadScale" => ".001",
          "hasRightsToModel" => 1,
          "acceptTermsAndConditions" => 1,
          "file" => base64_encode($file)//rawurlencode(),
        );
    
        print_r($data);
        print_r("sending<br>");
        $response = apiRequest(OAUTH2_URL_BASE."models/v1",$data,$array);
        print_r("sent<br>");
        print_r($response);
    
     
    Last edited: Jul 7, 2018
  7. if I use
    $x=json_encode($post);

    it returns back with no access token

    $x=http_build_query($post);

    i get an access token.

    with no access token I get a return of all possible commands in json format. with access token i get

    Code:
    curl
    {"result":"failure","reason":"Field  is required, but missing.\nField  is required, but missing.","rateLimit_OkToGo_InSeconds":0,"rateLimit_Window_InMinutes":5,"rateLimit_Limit":150,"rateLimit_Remaining":149,"rateLimit_History":{"201807071237":1},"rateLimit":{"retryInSeconds":0,"retryTimestamp":1530967049,"windowInSeconds":300,"limit":150,"remaining":149,"history":{"201807071237":1}}}
    sent
    stdClass Object
    (
        [result] => failure
        [reason] => Field  is required, but missing.
    Field  is required, but missing.
        [rateLimit_OkToGo_InSeconds] => 0
        [rateLimit_Window_InMinutes] => 5
        [rateLimit_Limit] => 150
        [rateLimit_Remaining] => 149
        [rateLimit_History] => stdClass Object
            (
                [201807071237] => 1
            )
    
        [rateLimit] => stdClass Object
            (
                [retryInSeconds] => 0
                [retryTimestamp] => 1530967049
                [windowInSeconds] => 300
                [limit] => 150
                [remaining] => 149
                [history] => stdClass Object
                    (
                        [201807071237] => 1
                    )
    
            )
    
    )
     
  8. ok got working now trying to set price while uploading. docs arent very good here. any idea what should be used in these sections

    PHP:
    <?php
      ini_set
    ("log_errors"1);
      
    ini_set("error_log""./php-error.log");
      
    error_log"Hello, errors!" );
      
    // session_start();
      
    require_once 'config.php';

    function 
    session($key$default=NULL) {
      return 
    array_key_exists($key$_SESSION) ? $_SESSION[$key] : $default;
    }
     
    function 
    apiGetToken() {
        if (!
    session('access_token')) {
            
    //initialize connection
            
    $ch curl_init(OAUTH2_URL_TOKEN);
            
    curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
            
    curl_setopt($chCURLOPT_POSTFIELDS,http_build_query(array(
                
    "grant_type"=>      "client_credentials",
                
    "client_id"=>       OAUTH2_CLIENT_ID,
                
    "client_secret"=>   OAUTH2_CLIENT_SECRET   
            
    )));
           
            
    curl_setopt($chCURLOPT_HTTPHEADER, array(
                
    'Accept: application/json'
            
    ));
            
    $response curl_exec($ch);
            
    $token=json_decode($response);
            
    $_SESSION['access_token'] = $token->access_token;
        }
    }

     
    function 
    apiRequest($url$post=FALSE$headers=array()) {
      
    $ch curl_init($url);
      
    curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
      if (
    $post) {
        
    $x=http_build_query($post);
        
    $x=json_encode($post);
        
    curl_setopt($chCURLOPT_POST,1);
        
    curl_setopt($chCURLOPT_POSTFIELDS,$x);
      }
      
    print_r("url=".$url."<br>");
      
    print_r("data=".$x."<br>");
      
    $headers[] = 'Accept: application/json';
      
    $headers[] = 'Content-Type: application/json';
      
    $headers[] = 'Content-Length: ' strlen($x);
      if(
    session('access_token'))
        
    $headers[] = 'Authorization: Bearer ' session('access_token');
      
    curl_setopt($chCURLOPT_HTTPHEADER$headers);
       
    print_r("<br>curl<br>");
      
    $response curl_exec($ch);
       
    var_dump($response."<br>");
      return 
    json_decode($response);
    }








        
    //make sure we are connected to shapeways
        
    apiGetToken();
        echo 
    session('access_token').'<br>';
       
        
    //try to upload file
        
    $filename "box.stl"//does exist
        
    $file file_get_contents($filename);
       
        
    $data = array(
          
    "file" => base64_encode($file),//rawurlencode(),
          
    "fileName" => $filename,
          
    "uploadScale" => 0.001,
          
    "hasRightsToModel" => 1,
          
    "acceptTermsAndConditions" => 1,
          
    "title" => "Test box",
          
    "description"=>"sandwallet.com generated box",
          
    "isPublic"=>0,
          
    "isClaimable"=>0,
          
    "isForSale"=>1,
          
    "isDownloadable"=>0,
          
    "tags"=>array(
            array(
                
    "type"=>"string",
                
    "description"=>"a"
            
    )     
          ),
          
    "materials"=>array(
            
    "26"=>array(
                
    "id"=>26,
                
    "type"=>"object",
                
    "description"=>"Material Object",
                
    "properties"=>array(
                
    /*
                    "markup"=>array(
                        "type"=>4,
                        "description"=>"Markup amount"
                    ),
                    */
                    
    "isActive"=>array(
                        
    "type"=>"boolean",
                        
    "description"=>true
                    
    ),
                    
    "price"=>array(
                        
    "type"=>"float",
                        
    "description"=>4
                    
    )
                )
            )
          ),
          
    "defaultMaterialId"=>26,
    /*     
          "categories"=>array(
              "type"=>5,
              "description"=>"Category Id"
          )
    */     
        
    );


        
    print_r("sending<br>");
        
    $response apiRequest(OAUTH2_URL_BASE."models/v1",$data);
        
    print_r($response);
        
    print_r("sent<br>");

        
    //verifying we uploaded the model
        
    print_r("get models<br>");
        
    $response apiRequest(OAUTH2_URL_BASE."models/v1?page=1");
        
    print_r($response);
        
    print_r("get done<br>");