Hi all,
I was looking for an API feature that, for a given email address, added a user to a group or two, inviting them to the forum if they didn’t already have an account. I couldn’t find that feature, but noticed that this is exactly what the ‘bulk upload’ invite feature does. This isn’t documented in the API, but is what the browser does.
So I did the same, using the following php code to POST a csv file:
This worked great for a couple of months, but has recently stopped working, with the following error in the discourse logs: Can't verify CSRF token authenticity.
Is this an bug, as I should be authenticated via the API key? Or am I on to a loser trying to use undocumented parts of the API?
Just wondering if someone could confirm whether this is a bug that’s likely to be fixed or not? I’ll start looking for an alternative solution, anyway.
Hi thanks for looking, I managed to hack together something with the documented API (with emphasis on hack, but maybe this is useful for someone else):
function tidal_process_order( $order_id ){
$order = new WC_Order($order_id);
$order_email = $order->get_billing_email();
$group_names_arr = [];
// get skus as group names
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);
// check if discourse user already exists with email
$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 exists, add them to groups
$user_id = $matches[0]->id;
foreach($group_names_arr as $group) {
// get group id from group name
$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));
// add user to group
$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 {
// user doesn't exist, invite them with group names
$body = json_encode(array('email' => $order_email, 'group_names' => $group_names, "custom_message" => "Welcome!"));
$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' );