Wp_remote is on the right path. Here's a portion of a plugin I wrote for newsletter signups to a third party. Basically you're taking advantage of THAT company's api, not using wordpress'. The main problem is that many companies have api's that are not similar, so without knowing more about the company you're interacting with you'll have to do a little testing or see if you can get an exposed result from them.
function html_form_code() { // THIS IS THE FORM TO SEND COLLECT USER DATA TO SEND TO 3rd party.
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<p>';
echo 'Your Name (required) <br />';
echo '<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />';
echo '</p>';
echo '<p>';
echo 'Your Email (required) <br />';
echo '<input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />';
echo '</p>';
echo '<p><input type="submit" name="cf-submitted" value="Send"/></p>';
echo '</form>';
}
function newsletter_signup() { //THIS IS THE API INTERACTION.
// if the submit button is clicked, send the POST
if ( isset( $_POST['cf-submitted'] ) ) {
// sanitize form values
$name = sanitize_text_field( $_POST["cf-name"] );
$email = sanitize_email( $_POST["cf-email"] );
$url='YOUR API URL WILL GO HERE'; //THIS is the actual interaction so this is where you are going to have to do some testing.
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array('Authorization' => 'Basic ' . base64_encode(MY REMOVED PW)),
'body' => array( ), // YOU'll NEED TO ADD YOUR CONTENT YOU'RE sending here... //$name and $email in my example but formatting will be up to API
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
// echo 'Response:<pre>';
// print_r( $response );
// echo '</pre>';
$responseBody = json_decode($response['body'],true);
echo $responseBody['message'];
}
}
}
function cf_shortcode() { //FUNCTION to combine and submit the data in a fell swoop
ob_start();
newsletter_signup();
html_form_code();
return ob_get_clean();
}
add_shortcode( 'newsletter_contact_form', 'cf_shortcode' ); //SHORTCODE TO PRESENT ON FRONTEND.