yaxu
(Alex McLean)
1
大家好,
我在寻找一个 API 功能,该功能可以根据给定的电子邮件地址将用户添加到一个或两个群组中,并在他们尚无账户时邀请他们加入论坛。我没能找到这个功能,但注意到“批量上传”邀请功能正是这样做的。虽然 API 文档中未记录此功能,但浏览器确实是这么操作的。
因此,我采用了相同的方法,使用以下 PHP 代码 POST 一个 CSV 文件:
$body = "--ossifrage\r
Content-Disposition: form-data; name=\"type\"\r
\r
csv\r
--ossifrage\r
Content-Disposition: form-data; name=\"files[]\"; filename=\"test.csv\"\r
Content-Type: text/csv\r
\r
$order_email,$group_names\r
\r
\r
--ossifrage--\r
";
$r=wp_remote_post( 'https://club.tidalcycles.org/invites/upload_csv.json', array(
'method' => 'POST',
'headers' => array('Content-Type' => 'multipart/form-data; boundary=ossifrage',
'Api-key' => '(redacted)',
'Api-Username' => 'yaxu'),
'body' => $body
)
);
这在几个月里运行良好,但最近突然失效了,Discourse 日志中显示的错误是:Can't verify CSRF token authenticity.(无法验证 CSRF 令牌真实性)。
这是一个 bug 吗?毕竟我应该已通过 API 密钥进行了身份验证?还是说我在试图利用 API 中未公开的部分,注定会失败?
yaxu
(Alex McLean)
2
只是想确认一下,这是否是一个可能会被修复的 bug?无论如何,我都会开始寻找替代方案。
yaxu
(Alex McLean)
4
嗨,感谢查看。我利用文档化的 API 拼凑了一个脚本(重点在于“拼凑”,但也许对其他人有用):
function tidal_process_order( $order_id ){
$order = new WC_Order($order_id);
$order_email = $order->get_billing_email();
$group_names_arr = [];
// 将 SKU 作为组名获取
foreach ( $order->get_items() as $item ) {
if ( $item['product_id'] > 0 ) {
$_product = $item->get_product();
$sku = $_product->get_sku();
array_push($group_names_arr, $sku);
}
}
$group_names = join(",",$group_names_arr);
// 检查该邮箱是否已存在 Discourse 用户
$r=wp_remote_get( "https://club.tidalcycles.org/admin/users/list/all.json?email=$order_email", array(
'headers' => array('Api-key' => 'redacted',
'Api-Username' => 'redacted')
)
);
$matches = json_decode($r['body']);
if (count($matches) > 0) {
// 用户已存在,将其添加到组中
$user_id = $matches[0]->id;
foreach($group_names_arr as $group) {
// 根据组名获取组 ID
$r=wp_remote_get( "https://club.tidalcycles.org/groups/$group.json", array(
'headers' => array('Api-key' => 'redacted',
'Api-Username' => 'redacted')
)
);
$group = json_decode($r['body']);
$body = json_encode(array('group_id' => $group->group->id));
// 将用户添加到组
$r=wp_remote_post( "https://club.tidalcycles.org/admin/users/$user_id/groups", array(
'headers' => array('Api-key' => 'redacted',
'Api-Username' => 'redacted',
'Content-Type' => 'application/json',
),
'body' => $body
));
}
}
else {
// 用户不存在,使用组名邀请他们
$body = json_encode(array('email' => $order_email, 'group_names' => $group_names, "custom_message" => "欢迎!"));
$r=wp_remote_post( "https://club.tidalcycles.org/invites", array(
'headers' => array('Api-key' => 'redacted',
'Api-Username' => 'redacted',
'Content-Type' => 'application/json',
),
'body' => $body
));
};
}
add_action( 'woocommerce_order_status_processing', 'tidal_process_order' );