I’m trying to do a simple Mailchimp subscription in my custom module. I didn’t want to use a contributed module, just because I have one existing form, and I want to also subscribe users on form submit.
That said, I can get this to work using curl.
$merge_vars = array(
'FNAME' => $form_state->getValue('fname'),
'LNAME' => $form_state->getValue('lname'),
'MERGE3' => $address,
'MERGE5' => $form_state->getValue('phone'),
'MERGE6' => $form_state->getValue('birthday'),
);
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => $status,
'merge_fields' => $merge_fields
);
$options = array(
'method' => 'PUT',
'data' => json_encode($data),
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Basic '.base64_encode( 'user:'.$api_key ), // maybe need this? formatted differently?
),
);
$base_url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($data['email_address']));
$mch_api = curl_init(); // initialize cURL connection
curl_setopt($mch_api, CURLOPT_URL, $base_url);
curl_setopt($mch_api, CURLOPT_HTTPHEADER, $headers);
curl_setopt($mch_api, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($mch_api, CURLOPT_RETURNTRANSFER, true); // return the API response
curl_setopt($mch_api, CURLOPT_CUSTOMREQUEST, 'PUT'); // method PUT
curl_setopt($mch_api, CURLOPT_TIMEOUT, 10);
curl_setopt($mch_api, CURLOPT_POST, true);
curl_setopt($mch_api, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($mch_api, CURLOPT_POSTFIELDS, json_encode($data) ); // send data in json
$result = curl_exec($mch_api);
But for some reason, I can’t figure out the right combination of code that does the same thing with Guzzle. Here’s what I have that doesn’t seem to actually trigger a subscription…
$client = Drupal::httpClient();
$response = $client->get($base_url, [
'auth' => ['apikey', $api_key],
'headers' => [
'content-type' => 'application/json',
'authorization' => 'Basic '.base64_encode( 'user:'.$api_key ),
],
'form_params' => json_encode($data)
]);
$data = $response->getBody();
return $data;
Anyone have a little time to help me out? I’ve never used Guzzle before, so perhaps there’s a fair amount of ignorance here.
Drupal version:
Source: https://www.drupal.org/taxonomy/term/4/feed