WordPress Curl vs wp_remote_request()

Viewed 203

The function here works fine, but I can't get my head around native WP request functions. What are the cons/pros and proper way to do this with WP native request functions?

    private function sync_api_data( $endpoint, $syncData, $operation ='PUT' ) {

    $ch = curl_init();

    if( array_key_exists( 'Id', $syncData ) ) {
        curl_setopt( $ch, CURLOPT_URL, $this->api.$endpoint.'/'.$syncData['Id'] );
    } else {
        curl_setopt( $ch, CURLOPT_URL, $this->api.$endpoint );
    }
    
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $operation );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $syncData ) );
    curl_setopt( $ch, CURLOPT_USERPWD, $this->systemId . ':' . $this->apikey );

    $headers = array();
    $headers[] = 'Content-Type: application/x-www-form-urlencoded';

    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

    $result = curl_exec( $ch );
    if ( curl_errno( $ch ) ) {
        echo 'Error:' . curl_error( $ch );
        return array();
    }
    curl_close( $ch );

    return json_decode( $result, true );

}

Example:

$syncData= array(
    'Id'        => $user_id,
    'FirstName' => 'fname',
    'LastName'  => 'lname',
    'Type'      => 'whatever',
);

$resultContact = $this->sync_api_data( 'Contact', $syncData );
0 Answers
Related