Я создаю пользовательскую конечную точку PHP для сайта WordPress для отправки формы на странице продукта woocommerce, конкретную форму add to cart
.
Итак, у меня есть мобильное приложение, построенное на ionic 4 / angular8, который должен отправить запрос по почте в вышеуказанную конечную точку.
Проблема в том, что тело сообщения из angular не идентифицирует по $ _ POST в PHP-коде, поэтому $_POST return null и товар не добавляется в корзину !!
Но при проверке этого с помощью почтальона запрос успешно выполняется и добавление товара в корзину успешно.
Я пытался получить угловое тело JSON на стороне PHP, и получал ответ успешно, но продукт, не добавляемый в корзину, означает, что для формы требуется особый способ отправки, аналогичный запросу почтальона.
Код PHP довольно прост:
function yith_custom_add_item( WP_REST_Request $request ) {
$currentuserid_fromjwt = get_current_user_id();
$user = get_user_by( 'id', $currentuserid_fromjwt );
if( $user ) {
$product_id = $_GET['id'];
$url = get_permalink( $product_id );
$cookie = 'wordpress_logged_in_856ec7e7dd32c9b2fc11b366505cf40d' . '=' . wp_generate_auth_cookie($currentuserid_fromjwt, time() + (10 * 365 * 24 * 60 * 60), 'logged_in') . ';';
$cookie .='_icl_current_admin_language_d41d8cd98f00b204e9800998ecf8427e=en; wp_woocommerce_session_856ec7e7dd32c9b2fc11b366505cf40d=171%7C%7C1575326201%7C%7C1575322601%7C%7Cab91a0f0bbe0f3d5ae90dd5bdf7e396d; wfwaf-authcookie-5372c020d00bf5e1ea6c81123ff21ec1=171%7C%7C4574b4a9b1b62c8c7a1c1ae24cd4bd26d279bb5670fe87bcf7eb210835e43f22; _icl_current_language=en; PHPSESSID=5ed2009813f86633694a25e297d4ee06; wordpress_logged_in_856ec7e7dd32c9b2fc11b366505cf40d=deleted; woocommerce_items_in_cart=1; woocommerce_cart_hash=086ae7e00c53740163451a538fe8a9fc';
$angular_json = json_decode(file_get_contents("php://input"));
if ( !empty($_POST) ) {
$response = wp_remote_post( $url, array(
'headers' => array(
'Cookie' => $cookie,
'Authorization' => $request->get_header('Authorization'),
'Content-Type' => 'application/x-www-form-urlencoded',
),
'body' => $_POST,
));
return $response;
} elseif ( !empty($angular_json) ) {
$response = wp_remote_post( $url, array(
'headers' => array(
'Cookie' => $cookie,
'Authorization' => $request->get_header('Authorization'),
'Content-Type' => 'application/x-www-form-urlencoded',
),
'body' => $angular_json,
));
return $angular_json;
} else {
return "Nothing to show";
}
}
}
Угловой код: (услуга)
addYithCompositeToCart(id: any, data: any) {
const { token } = JSON.parse(localStorage.getItem('user'));
let headers = {
'Content-Type': 'x-www-form-urlencoded; charset=UTF-8',
"Authorization": `Bearer ${token}`,
};
// let headers = new HttpHeaders();
// headers
// .set('Content-type', 'x-www-form-urlencoded;')
// .set('Authorization', `Bearer ${token}`);
this.http.post(`${environment.host}yith-composite/add-item?id=${id}`, data, {
headers
})
.toPromise()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
}
Компонент (запуск по нажатию):
addToCart() {
const data = {
ywcp_selection: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: -1 }))),
ywcp_variation_id: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: object.variation.variation_id }))),
ywcp_quantity: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: 1 }))),
ywcp_selected_product_value: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: object.productId }))),
quantity: 1,
'add-to-cart': this.product.id
};
this.cartService.addYithCompositeToCart(this.product.id, data);
}
Почтальон запрос ![enter image description here](https://i.stack.imgur.com/7qoVj.png)