MailChimp Campaign Content Update
Asked Answered
Y

2

8

MailChimp campaign content docs - https://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/content

I'm trying to replace some placeholders in a campaign content with actual values via the API. At first, I thought there might be some syntax errors or internal logic errors like non-unique mc:edits into a mc:repeatable that would get the HTML refused/declined by MailChimp, hence the update not taking place, however, that was not the case.

Tried replacing html with a simple <p>test</p> and it was still not working.

Here are a couple of local logs, I'll use xyz as my campaign id:

2018-02-26 16:26:13 [::1][9804][-][warning][application] calling GET /campaigns/xyz/content []

2018-02-26 16:26:13 [::1][9804][-][warning][application] got both plain_text and html versions of content

2018-02-26 16:26:13 [::1][9804][-][warning][application] calling PUT /campaigns/xyz/content {"html":"<p>test</p>"}

2018-02-26 16:26:14 [::1][9804][-][warning][application] got response [ 'plain_text' => 'test' + other MailChimp stuff such as footer, that were appended automatically by MailChimp, 'html' => '<p>test</p>' ]

// calling GET immediately after PUT in order to see if any update occurred

2018-02-26 16:26:14 [::1][9804][-][warning][application] calling GET /campaigns/xyz/content []

2018-02-26 16:26:14 [::1][9804][-][warning][application] got updated html (my "test" paragraph + auto footer from MailChimp) and proper plain_text

Everything looks fine according to these, that means both versions updated as they were supposed to. However, on the next API/MailChimp dashboard request, it displays the old HTML content, preserving the update I've just made in the plain text version only.

No errors, nothing to look into. It could be any internal MailChimp behaviour.

PS: I know about Setting Mailchimp campaign content html not working or MailChimp API v3 campaign content template sections, but none of the answers provided to those are helpful.

PS2: I know I should contact MailChimp, but according to

Our MailChimp Support Team isn't trained at in-depth API troubleshooting. If you need a developer to help you configure something using the API, check out our great Experts Directory, which lists third-party MailChimp experts who can be hired to help out.

they don't provide support for API troubleshooting.

Yelena answered 26/2, 2018 at 16:15 Comment(5)
Sounds like it could be a caching issue on the Dashboard? If you shift-refresh, or try again later does it show the updated content? If you send mail using that template does it send the old or new content?Typecast
It's not only the dashboard, API calls too, calling GET right after PUT displays the correct content, but calling GET one more time will bring up outdated content. It can be caching on MailChimp side, but they state that they forcefully update stuff on GET, moreover, it does not appear to be caching as after 1 week I still have correct plain-text version and outdated HTML (just checked). The updated content needs to be manually reviewed by someone in charge of this sort of stuff. No one will blindly push campaigns to thousands of users, even if that would work.Yelena
Guess my only current option is MailChimp support or a fully API-powered campaign creation interface which is some hours of work and more hours of work if I want to allow pretty/user-friendly editable blocks like MailChimp does. :(Yelena
I am stuck with the exact same problem. The response gives the appearance that the change was collected but nothing actually changes.Immateriality
Does the text version change (at least)? Had an open bounty too, but no one answered. :(Yelena
V
6

MailChimp doesn't allow updating the campaign's HTML content because the campaign type is based on a template.

In order to update the HTML content, the campaign has to be set to custom HTML instead of a template. You can check the type by sending a GET API request to /campaigns or /campaigns/{campaign_id} and finding the content_type attribute in the response (documentation).

Alternatively, in the dashboard, the type can be determined by editing the design of the email. Anything under 'Code your own' is HTML and templates are of course templates.

I'm not entirely sure why the first response to a PUT request on a template campaign shows the updated content, but changing the content type should let you update as you want to.

Hope this helps!

Verwoerd answered 21/3, 2018 at 4:18 Comment(4)
A template in its nature is HTML formatted around MailChimp syntax (and from then on, it stores key & value in DB for each editable area), what you are saying kind of makes sense, but why would they limit us to that / not even respond with an error message like "html can only be modified for raw HTML templates"... :( You might be right, will check in a couple of hours.Yelena
And why would they update the text version if they reject the HTML? If this is the case, they should not touch the text version either, I call bad API design for this particular bit.Yelena
@Yelena It seems to me that if they intended template campaigns to be updated through the API, they would have added a way to set the mc:edit content areas as an alternative to the html parameter. Or perhaps it was simply an oversight in the API design. The HTML can be generated programmatically though, so they also could have determined it wasn't a necessary feature.Verwoerd
@Yelena also. The whole PUT html api route is somewhat bizarre. I ended up making a template on the mailchimp editor and then exporting the HTML of it. I have that html on my server, and then when I create a new campaign via my app i just send it with this html updated in regards of spaceholders and data inputted by the user. That way the campaign is made with the data i want. I will look into just changing the type from template to custom html later as well though.Immateriality
Y
0

If anyone's still looking for an answer to this.

I managed to solve the issue several weeks ago without creating the campaign via API, but actually updating it.

I used placeholders like [product_card id=123], 3 cards per block/row, all repeatable, which are wrapped in a class that I named product-card. In the MailChimp dashboard, you may still see the placeholders, but on preview and any form of preview like thumbnail, it will display correctly.

On the server, I crawl through the campaign's content, "detect" section names based on how they seemed to me in MailChimp and update each section with the content that I want.

PHP snippet below, some Yii2 stuff, but mostly plain PHP. I use $preview to display a preview of how the template would look, I know it's not visible in the function.

/**
 * @param $id - Id of the campaign
 * @param $s  - Whether to save or just preview
 *
 * @return bool
 */
function changeContent($id, $s = false)
{
    $mcCampaign          = new McCampaign();
    $mcCampaign::$itemId = $id;

    $content = $this->api->get("/campaigns/{$id}/content");

    if (!isset($content['html'])) return false;

    $template = $content['html'];

    $forgedDom = new \DOMDocument();
    $forgedDom->loadHTML($template);

    $mcSections = [];

    $finder = new \DOMXPath($forgedDom);

    $nodes = $finder->query('//td[contains(@class, "product-card")]');

    // disabling this shit in order to avoid strict errors
    libxml_use_internal_errors(true);

    $mcEditId    = 1;
    $mcEditIndex = 0;
    foreach ($nodes as $key => $node) {
        /** @var \DOMElement $node */
        $textContent = $node->textContent;
        if (!preg_match("#\[product_card id=\d+\]#", $textContent)) continue;

        $productId         = filter_var($textContent, FILTER_SANITIZE_NUMBER_INT);
        $node->textContent = false;

        $product = Product::findOne($productId);

        $productDetails = $product ? $this->renderPartial('/partials/_mc-product', [
            'product' => $product
        ]) : 'Product not found.';

        if ($key != 0) {
            if ($key % 3 == 0) {
                $mcEditId = 1;
                $mcEditIndex++;
            } else {
                $mcEditId++;
            }
        }

        $mcSections["repeat_1:{$mcEditIndex}:product_card_{$mcEditId}"] = $productDetails;


        $fragment = $forgedDom->createDocumentFragment();
        $fragment->appendXML($productDetails);

        $node->appendChild($fragment);
    }
    libxml_use_internal_errors(false);

    $preview = $forgedDom->saveHTML();

    // just in case
    /* $preview = str_replace(["\n", "\t", "\r"], "", $preview); */

    if ($s) {
        if (!empty($mcSections)) {
            $res = $this->api->put("/campaigns/{$id}/content", [
                'template' => [
                    'id'       => *template_id_here*,
                    'sections' => $mcSections
                ],
            ]);

            // forcing Mc to rebuild cache
            $this->api->get("/campaigns/{$id}/content");

            Yii::$app->session->setFlash('success', 'Done.');

            return $this->redirect(['campaign/index']);
        } else {
            Yii::$app->session->setFlash('error', 'Something went wrong.');
        }
    }
}
Yelena answered 11/5, 2018 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.