如何通过php中的Curl正确使用Mailgun Api

时间:2019-05-17 04:47:01

标签: php mailgun

我下面有来自mailgun的curl请求,我想用它来为我的网站上的新闻通讯创建一个电子邮件列表。

 curl -s --user 'api:YOUR_API_KEY' \
       https://api.mailgun.net/v3/lists \
       -F address='LIST@YOUR_DOMAIN_NAME' \
       -F description='Mailgun developers list'

我的问题是,当我运行以下代码时,它显示无效的私钥401 似乎在curl请求中未正确设置api密钥。下面是我到目前为止的编码

<?php

$email = 'tmack@gmail.com';
$api_key = 'my key here';
$api = 'api:';
$api_k = $api.$api_key;
$url = 'https://api.mailgun.net/v3/lists';

$json = json_encode([
    'address' => $email,
    'description'        => 'Tmack group Mailing List'
]);


$ch = curl_init($url);
//curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);

curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_k);
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_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $result;
curl_close($ch);
echo $status_code;

1 个答案:

答案 0 :(得分:0)

下面的代码对我有用。我刚刚在下面添加了代码行

curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $api_k); 

因此,下面是最终代码

$email = 'tmack@gmail.com';
$api_key = 'my key here';
$api = 'api:';
$api_k = $api.$api_key;
$url = 'https://api.mailgun.net/v3/lists';

$json = json_encode([
    'address' => $email,
    'description'        => 'Tmack group Mailing List'
]);


$ch = curl_init($url);

curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $api_k);
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_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $result;
curl_close($ch);
echo $status_code;