Ravinder Kumar
Ravinder Kumar

Reputation: 944

Mailchimp Insert custom form fields to list

I'm trying to insert data to mailchip using below code but its not working, Problem with my new field 'Q1' => "50000", when I'll remove this then able to add successfully but I need to insert extra fields. I need to insert Email, Name, Q1, Q2, Q3, Q4 and Q5.

Here is Q1 field setting in mailchimp form

enter image description here

And My PHP code is:

 $data = [
            'email'     => '[email protected]',
            'status'    => 'subscribed',
            'firstname' => 'john',
            'lastname'  => 'doe'
        ];

        Mailchimp($data);


    function Mailchimp($data) {
        $apiKey = 'XXXXXXXXXXXXXXXXX';
        $listId = 'XXXXXXXX';
        $memberId = md5(strtolower($data['email']));
        $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
        $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
        $json = json_encode([
            'email_address' => $data['email'],
            'status'        => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
            'merge_fields'  => [
                'FNAME'     => $data['firstname'],
                'LNAME'     => $data['lastname'],
                'Q1'     => "50000",
            ],

        ]);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                                                                                                             
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $httpCode;
    }

Any Help will be appreciated

Upvotes: 0

Views: 1057

Answers (1)

Minar_Mnr
Minar_Mnr

Reputation: 1405

Add your Q1 fields at "List fields and |MERGE| tags" & remove "," after "50000".

You can not dynamically create fields like Q1, Q2 , Q3 .... First you have to create those fields in your "List fields and |MERGE| tags" .Then you can call api and insert values. Below image for better understanding .

enter image description here

Upvotes: 1

Related Questions