How to send data from Shopify store to external API/Service

I have been working with a Shopify development store for the past year, and noticed that the protocol for making successful POST requests, via Ajax calls, have definitely changed. I have been only able to make successful GET requests, however every POST request results in a 400 Bad Request error.

Interestingly enough, these post requests work on my local host and on my ngrok url. It is only when I’m sending the post request to my store domain where specifically POST requests result in the 400 error.

I am leveraging .NET razor pages and treat each page as the front and back end of an app proxy. I am willing to leverage webhooks or theme extensions but after am month of looking at the docs and other forums, I’m primarily looking for a certain solution to make HTTP POST calls in shopify (not using the shopify API but sending the data to an external API)

So the following ajax call works only on my localhost and ngrok url. I extract inputted data from a form when a user hits the submit button:

    var formData = {
        CollectorId: $('#CollectorId').val(),
        FirstName: $('#FirstName').val(),
        LastName: $('#LastName').val(),
        EmailAddress: $('#EmailAddress').val(),
        PhoneNumber: $('#PhoneNumber').val(),
        Address1: $('#address1').val(),
        Address2: $('#Address2').val(),
        City: $('#city').val(),
        StateRegionProvince: $('#stateRegionProvince').val(),
        PostalCode: $('#postalCode').val()
    };

and attempt the following ajax setup to my app proxy’s url and specifying the handler method in my razor backend file:

 $.ajax({
     type: 'POST',
     url: '/apps/member?handler=HandlerMethodName',
     contentType: 'application/json',
     data: JSON.stringify(formData),
     headers: {
    
        
         'Content-Type': 'application/json'
         

             },
     dataType: 'json',
     beforeSend: function (jqXHR, settings) {
         console.log('Request URL:', settings.url);
         console.log('Request Type:', settings.type);
  
     },
     xhrFields: {
         withCredentials: true
     },
     success: function (response) {
         if (response.success) {
             $('#UserFeedbackMessage').text(response.message).css('color', 'green').show();
         } else {
             $('#UserFeedbackMessage').text(response.message).css('color', 'red').show();
         }
     },
     error: function (xhr, status, error) {
         console.error("Error updating collector info:", error);
         console.log("XHR:", xhr);
         console.log("Status:", status);
         console.log("Response Text:", xhr.responseText);
         $('#UserFeedbackMessage').text("An error occurred while updating your profile.").css('color', 'red').show();
     },
     complete: function (jqXHR, status) {
         console.log('Complete Response Headers:', jqXHR.getAllResponseHeaders());
     }
 });

'd be glad to assist you with making successful POST requests in your Shopify development store. Here’s a breakdown of the potential issues and solutions:

1. CORS Restrictions:

  • Enable CORS: Ensure that your Shopify development store allows cross-origin requests from your app proxy. You can do this by adding the following header to your Shopify store’s theme:

HTML

<meta http-equiv="Access-Control-Allow-Origin" content="https://your-app-proxy-domain.com">
  • Replace https://your-app-proxy-domain.com with the actual domain of your app proxy.

2. Shopify App Authentication:

  • Authentication Token: If your app proxy requires authentication, make sure you’re including the necessary authentication token in your request headers. Refer to Shopify’s documentation for specific authentication methods.

3. Request Body Formatting:

  • JSON Formatting: Verify that your request body is properly formatted as JSON. Use a JSON formatter to check for any errors.

4. Server-Side Validation:

  • Server-Side Checks: Ensure that your server-side code is correctly validating the request body and handling any potential errors.

5. Network Issues:

  • Network Troubleshooting: Check for any network issues between your app proxy and Shopify’s servers. Use browser developer tools or network monitoring tools to inspect the request and response headers.

6. Shopify API Rate Limits:

  • Rate Limits: If you’re making frequent requests to the Shopify API, be aware of the API rate limits. Exceeding these limits can result in errors.

7. Shopify App Proxy Configuration:

  • App Proxy Setup: Verify that your app proxy is configured correctly to handle POST requests and process the data from your form.

Revised AJAX Code:

JavaScript

$.ajax({
    type: 'POST',
    url: '/apps/member?handler=HandlerMethodName',
    contentType: 'application/json',
    data: JSON.stringify(formData),
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your_authentication_token' // Replace with your authentication token if needed
    },
    // ... (rest of your AJAX options)
});

Additional Tips:

  • Debugging: Use browser developer tools to inspect the request and response headers, and identify any errors or warnings.
  • Logging: Implement logging in your app proxy to track the flow of requests and responses.
  • Testing: Test your POST requests on different browsers and devices to ensure compatibility.

By following these guidelines and carefully addressing the potential issues, you should be able to successfully make POST requests in your Shopify development store.