Automatically sending newsletter subscribers from InstaWP to Mailchimp

This GraphQL query captures the email from the visitors who ticked the "Subscribe to mailing list" checkbox from InstaWP (when creating a new sandbox site), and subscribes this email to a Mailchimp list:

query HasSubscribedToNewsletter {
hasSubscriberOptin: _httpRequestHasParam(name: "marketing_optin")
subscriberOptin: _httpRequestStringParam(name: "marketing_optin")
isNotSubscriberOptinNAValue: _notEquals(value1: $__subscriberOptin, value2: "NA")
subscribedToNewsletter: _and(values: [$__hasSubscriberOptin, $__isNotSubscriberOptinNAValue])
@export(as: "subscribedToNewsletter")
}

query MaybeCreateContactOnMailchimp
@depends(on: "HasSubscribedToNewsletter")
@include(if: $subscribedToNewsletter)
{
subscriberEmail: _httpRequestStringParam(name: "email")

mailchimpUsername: _env(name: "MAILCHIMP_API_CREDENTIALS_USERNAME")
@remove
mailchimpPassword: _env(name: "MAILCHIMP_API_CREDENTIALS_PASSWORD")
@remove

mailchimpListMembersJSONObject: _sendJSONObjectItemHTTPRequest(input: {
url: "https://us7.api.mailchimp.com/3.0/lists/{listCode}/members",
method: POST,
options: {
auth: {
username: $__mailchimpUsername,
password: $__mailchimpPassword
},
json: {
email_address: $__subscriberEmail,
status: "subscribed"
}
}
})
}

And define in wp-config.php:

define( 'MAILCHIMP_API_CREDENTIALS_USERNAME', '{ username }' );
define( 'MAILCHIMP_API_CREDENTIALS_PASSWORD', '{ password }' );

Step by step analysis of the GraphQL query permalink

Read blog posts:

Extensions referenced in this tutorial permalink

  1. Field Response Removal permalink

    Remove the output of a field from the response.

  2. Field To Input permalink

    Retrieve the value of a field, manipulate it, and input it into another field or directive, all within the same operation.

  3. HTTP Client permalink

    Addition of fields to execute HTTP requests against a webserver and fetch their response.

  4. HTTP Request via Schema permalink

    Addition of fields to retrieve the current HTTP request data.

  5. Multiple Query Execution permalink

    Combine multiple queries into a single query, sharing state across them and executing them in the requested order.

  6. PHP Constants and Environment Variables via Schema permalink

    Query the value from an environment variable or PHP constant.

  7. PHP Functions via Schema permalink

    Manipulate the field output using standard programming language functions available in PHP.