我正在尝试设置一个Stripe webhook,一旦发生"charge.successed"事件,它就会发送电子邮件。当我在Stripe上测试webhook时,我一直得到一个普遍的"错误500"。我对Stripe很陌生,我真的被困在这里了。
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
require_once('stripe/lib/Stripe.php');
Stripe::setApiKey("XXXYYYZZZ");
// retrieve the request's body and parse it as JSON
$body = @file_get_contents('php://input');
$event_json = json_decode($body);
// for extra security, retrieve from the Stripe API
$event_id = $event_json->id;
$event = Stripe_Event::retrieve($event_id);
// This will send receipts on successful charges
if ($event_json->type == 'charge.succeeded') {
// This is where we e-mail the invoice.
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'abc@gmail.com'; // SMTP username
$mail->Password = 'password!'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'abc@gmail.com';
$mail->FromName = 'John Doe';
$mail->addAddress('email@stanford.edu, John Doe'); // Add a recipient
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Your webhook works!!!!!';
$mail->Body = "The message sent!";
if(!$mail->send()) {
echo 'Message could not be sent. Contact us at hello@beerboy.co.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
}
?>
检查此代码:
// retrieve the request's body and parse it as JSON
$body = @file_get_contents('php://input');
$event_json = json_decode($body);
// for extra security, retrieve from the Stripe API
$event_id = $event_json->id;
$event = Stripe_Event::retrieve($event_id);
$body
是使用php://input
定义的,它希望从POST或GET中读取提交到您的页面的信息,而不是Stripe。请参见此处。POST或GET中的内容显然是无效的JSON或包含无效的id
。
因此,当您尝试json_decode($body)
时,您试图对POST或GET中的内容进行json_decode,而不是从Stripe中获得的内容。$event_json->id
不存在或无效,所以$event_id
不存在或有效,所以当您调用Stripe_Event::retrieve($event_id);
时Stripe会翻转。
请先尝试var_dump($event_json); die();
,然后再拨打Stripe_Event
,看看您的请求中有什么内容。
EDIT:确保张贴(或包括查询字符串)语法有效的JSON。换句话说,您的用户将如何访问此页面?确保无论它们来自何处,输入都包含有效的JSON并符合您的期望(即,具有id
参数等)。
对于那些仍在寻找答案的人,请从file_get_contents()
函数中删除"@"符号:
`Stripe::setApiKey("sk_test_5cgfJ8yqBHE8L6radSAUhoo7");
$input = file_get_contents("php://input");
$event_json = json_decode($input);
var_dump($event_json);
http_response_code(200); // PHP 5.4 or greater`
从stripe-webhooks部分为stripe-admin发送一个测试。您将收到一条消息"Test-webhook sended successfully",单击此消息可以查看响应,该响应应该是请求对象的数组。
您应该在末尾添加此行:
http_response_code(200);//PHP 5.4或更高版本
并且在所有exit;
s 之前