WordPress SMS API integration without plugin error

I have created a code for WordPress to integrate my custom SMS API. The API URL works fine when I type it on the URL bar; but when it in the code, the API URL will not call. So this code not working when the customer places an order:

add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );
function mysite_woocommerce_order_status_processing( $order_id ) {

    $billing_phone="0729424391";
    $message="yep";

    $url="http://realcam.club:9710/http/send-message?username=adminpassword=adminto=".$billing_phone."messagetype=sms.automaticmessage=".$message."'";

  $response = file_get_contents( $url );

  //print_r($response);

}

Topic woocommerce-offtopic sms api Wordpress

Category Web


I would suggest using the HTTP API that WordPress provides for this purpose. Take a look at the GETting data from an API section for more details on how to get the data from your URL.

To get started, try:

  • Navigate to your wp-config.php file, and set the WP_DEBUG and WP_DEBUG_LOG constants to true (do NOT do this on the production server of your site).

  • Next, replace your code with the following:

    function mysite_woocommerce_order_status_processing( $order_id ) {
    
        $billing_phone = "0729424391"; // TODO Sanitize this input
        $message = "yep"; // TODO Sanitize this input
        $url = sprintf( "http://realcam.club:9710/http/send-message?username=admin&password=admin&to=%1$s&messagetype=sms.automatic&message=%2$s", $billing_phone, $message );
    
        try {
    
            // GET the response.
            $response = wp_remote_get( esc_url( $url ) );
    
            // If the response is a WP_Error object, jump to the catch clause.
            if ( is_wp_error( $response ) ) {
                throw new UnexpectedValueException( $response->get_error_message() );
            }
    
            // Log the successful response to the debug log.
            error_log( print_r( $response, true ) );
    
        } catch ( UnexpectedValueException $e ) {
    
            // Log the error to the debug log.
            error_log( $e );
    
        }
    
    
    }
    add_action( "woocommerce_order_status_processing", "mysite_woocommerce_order_status_processing" );
    

    and check what's in the debug.log file in the wp-content directory of your WordPress installation.

This code will log the response or, if the request was unsuccessful, an error message to that file. I think it is straightforward enough for you to understand, but if you do have any questions or if anything goes wrong, please let me know.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.