我设法通过PHP通过CURL请求解决问题,代码如下。
功能。站点A的php:
add_action( \'woocommerce_order_status_completed\', \'change_role_on_purchase\' );
function change_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item_id => $item ) {
$product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
if ( $product_id === 3960 ) { // Check product
$order_data = $order->get_data();
$order_billing_first_name = $order_data[\'billing\'][\'first_name\'];
$order_billing_last_name = $order_data[\'billing\'][\'last_name\'];
$order_billing_email = $order_data[\'billing\'][\'email\'];
// API url
$url = \'https://example.com/register-user\';
// set post fields
$data = array(
\'name\' => $order_billing_first_name,
\'lastname\' => $order_billing_last_name,
\'email\' => $order_billing_email,
);
$str = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
}
}
}
注册用户页面上的代码。站点B中的php:
<?php
wp_head();
if(isset($_POST[\'name\'])){
$name = $_POST[\'name\'];
$lastname = $_POST[\'lastname\'];
$username = strtolower($name . $lastname);
$email = $_POST[\'email\'];
//$user_id = username_exists( $username );
if ( !email_exists( $email ) ) {
$i = 1;
while(username_exists($username)){
$i++;
}
$username = $username . $i;
$password = wp_hash_password(wp_generate_password());
$user_id = wp_create_user( $username, $password, $email );
$user = get_user_by( \'ID\', $user_id );
// Remove role
$user->remove_role( \'subscriber\' );
// Add role
$user->add_role( \'new_role\' );
} else {
$user = get_user_by( \'email\', $email );
// Remove role
$user->remove_role( \'subscriber\' );
// Add role
$user->add_role( \'new_role\' );
}
}
wp_footer();
?>