0
http请求我有2个HTTP请求如何链两个狂饮
创建通过mailchimp API(列表ID将被创建)
一个新的列表中添加新成员新创建列表。
我对将它们链接在一起的语法有点困惑。 下面的完整代码。这是正确的做法吗?
<?php
// auto load
require 'vendor/autoload.php';
use GuzzleHttp\Psr7\Request;
// opt
$option = array(
'base_uri' => "https://us12.api.mailchimp.com/3.0/",
'auth' => ['apikey', '292bae37c631ac3ba03ed0640b44e6c3'],
);
// client
$client = new \GuzzleHttp\Client($option);
// data for a new list
$data_list = array(
"name" => "test_mailchimp",
"contact" => array(
"company" => "MailChimp",
"address1" => "675 Ponce De Leon Ave NE",
"address2" => "Suite 5000",
"city" => "Atlanta",
"state" => "GA",
"zip" => "30308",
"country" => "US",
"phone" => "12345678",
),
"permission_reminder" => "You're receiving this email because you signed up for updates.",
"use_archive_bar" => true,
"campaign_defaults" => array(
"from_name" => "test",
"from_email" => "[email protected]",
"subject" => "test_subject",
"language" => "en",
),
"notify_on_subscribe" => "",
"notify_on_unsubscribe" => "",
"email_type_option" => true,
"visibility" => "pub",
);
// member data
$data_member = array(
'email_address' => '[email protected]',
"status" => "subscribed"
);
// common
$headers = array(
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json'
);
// ------------- create a list -------------------
// $data should match up the field, no json =>
$url_display_list = 'lists';
$req_create_list = new Request('POST', $url_display_list, $headers, json_encode($data_list));
// promise
$promise_create_list = $client
->sendAsync($req_create_list)
->then(function ($res) use ($headers, $data_member, $client) {
$obj = json_decode($res->getBody());
$list_id = $obj->id;
// --------- add a member to list ---------
$url_create_member = 'lists/'. $list_id. '/members';
$req_create_member = new Request('POST', $url_create_member, $headers, json_encode($data_member));
$promise_create_member = $client
->sendAsync($req_create_member)
->then(function ($res) use ($list_id) {
$obj = json_decode($res->getBody());
$member_id = $obj->id;
echo "\n--- list id ----\n";
echo "\n". $list_id. "\n";
echo "\n--- member id ----\n";
echo "\n". $member_id. "\n";
// ------------ update a member ---------
});
});
$promise_create_list->wait();
$promise_create_member->wait();
我使用PHP 7.0.15 CLI,似乎没有协同程序。我需要安装任何东西吗? – kenpeter
不,协程是Guzzle库的一部分(这是一个通常的功能)。只需使用它作为'\ GuzzleHttp \ Promise \ coroutine()'或者导入它('使用函数GuzzleHttp \ Promise \ coroutine')。 –