Secure API calls with AJAX and PHP to 3rd party API

前端 未结 6 459
小鲜肉
小鲜肉 2021-01-11 18:02

I want to make GET, POST & PUT calls to a 3rd party API and display the response on the client side via AJAX. The API calls require a token, but I need to keep that toke

6条回答
  •  -上瘾入骨i
    2021-01-11 18:54

    It is bit hard without sample code. But As per I understood you can follow this,

    AJAX CALL

    $.ajax({
            type: "POST",
            data: {YOU DATA},
            url: "yourUrl/anyFile.php",
            success: function(data){
               // do what you need to 
    
                }
            });
    

    In PHP

    Collect your posted data and handle API, Something like this

    $data = $_POST['data']; 
    // lets say your data something like this
    $data =array("line1" => "line1", "line2"=>"line1", "line3" =>"line1");
    
    
     $api = new Api();
     $api->PostMyData($data );
    

    Example API Class

    class Api
    {
    const apiUrl         = "https://YourURL/ ";
    const targetEndPoint = self::apiUrl. "someOtherPartOFurl/";
    
    const key       = "someKey819f053bb08b795343e0b2ebc75fb66f";
    const secret    ="someSecretef8725578667351c9048162810c65d17";
    
    private $autho="";
    
    
    
    public function PostMyData($data){      
      $createOrder = $this->callApi("POST", self::targetEndPoint, $data, true);
      return $createOrder;
     }
    
    private function callApi($method, $url, $data=null, $authoRequire = false){
        $curl = curl_init();
    
        switch ($method)
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
    
                if ($data)               
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;
            default:
                if ($data)
                    $url = sprintf("%s?%s", $url, http_build_query($data));
        }
    
        if($authoRequire){
            $this->autho = self::key.":".self::secret;
            // Optional Authentication:
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($curl, CURLOPT_USERPWD, $this->autho);
        }
    
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
        $result = curl_exec($curl);
    
        curl_close($curl);
    
    
        return $result;
    
     }
    }
    

提交回复
热议问题