Catchable fatal error: Object of class stdClass could not be converted to string after WP 4.7

Not sure if there was a change in 4.7, but wp_get_post_categories returns an array of category objects, not IDs, so when you loop over the $terms, $term_id is actually an object.

Add the argument 'fields' => 'ids' to the wp_get_post_categories-call and you should be good to go – it’ll return an array of category IDs instead.

$terms = wp_get_post_categories($post->ID, ['fields' => 'ids']);