| caseyryan |
31.03.2015 07:09 |
На клиенте этот код не нужен. Лучше пользоваться библиотекой APIConnection и не изобретать самому себе лишние трудности.
У меня вот такой код на сервере:
(добавил там комменты)
PHP код:
<?php require_once 'functions.php'; require_once 'constants.php'; header("Content-Type: application/json; encoding=utf-8"); $input = $_POST; $sig = $input['sig']; unset($input['sig']); ksort($input); $str = ''; foreach ($input as $k => $v) { $str .= $k.'='.$v; } // проверяем подпись if ($sig != md5($str.SECRET_KEY)) { $response['error'] = array( 'error_code' => 10, 'error_msg' => 'Несовпадение вычисленной и переданной подписи запроса.', 'critical' => true ); } else { $notification_type = $input['notification_type']; if ($notification_type == 'get_item' || $notification_type == 'get_item_test') { // указано в itemCode на клиенте $item_code = intval($input['item']); $order_id = intval($input['order_id']); $user_id = $input['user_id']; openConnection(); // тут находим товар, соответствующий коду, пришедшему с клиента $needed_item = getItemByCode($item_code); closeConnection(); if ($needed_item) { $rubies_to_buy = $needed_item->level; $golds_to_buy = $needed_item->friends; $price_in_votes = $needed_item->price; $order = array( 'golds' => $golds_to_buy, 'rubies' => $rubies_to_buy, 'user_id' => $user_id, 'code' => $item_code, 'price' => $price_in_votes ); // добавляем заказ в базу данных, чтобы после ответа сервера знать о чем речь $order_set = setOrder($order_id, $order); if ($order_set == true) { $response['response'] = array( 'item_id' => $needed_item->code, 'title' => $needed_item->title, // тут передается картинка товара. Слово new здесь дописано только для того, чтобы закэшировать новую картинку, при изменении картинки его тоже нужно поменять 'photo_url' => "http://" . $_SERVER['SERVER_ADDR'] . "/store/rubies/" . $needed_item->img . "?new", 'price' => $needed_item->price ); } else { $response['error'] = array( 'error_code' => 20, 'error_msg' => 'Ошибка. Повтор запроса.', 'critical' => true ); } } else { $response['error'] = array( 'error_code' => 20, 'error_msg' => 'Товара не существует.', 'critical' => true ); } } elseif ($notification_type == 'order_status_change' || $notification_type == 'order_status_change_test') { $status = $input['status']; $order_id = intval($input['order_id']); $app_order_id = 1; // здесь берутся данные о заказе, которые при запросе записались базу. Можно сделать и по-другому, просто у меня так $order = getOrder($order_id); if ($status == 'chargeable' || !$order) { // Код проверки товара, включая его стоимость $user_id = $order['user_id']; $golds = intval($order['golds']); $rubies = intval($order['rubies']); openConnection(); // проверяем что уже есть у игрока $cur_values = getValues($user_id, false, true); $cur_golds = intval($cur_values['golds']); $cur_rubies = intval($cur_values['rubies']); // вычисляем новые значения после после покупки $golds += $cur_golds; $rubies += $cur_rubies; // обновляем значения в базе $to_values = array( 'golds' => $golds, 'rubies' => $rubies ); updateValuesTable($to_values, $user_id); closeConnection(); $response['response'] = array( 'order_id' => $order_id, 'app_order_id' => $app_order_id, ); } else { $response['error'] = array( 'error_code' => 100, 'error_msg' => 'Передано непонятно что вместо chargeable.', 'critical' => true ); } } } // отдаем готовый ответ echo json_encode($response);
?>
А на клиенте всего лишь:
Код AS3:
_vk.addEventListener('onOrderSuccess', onOrderSuccess);
// дальше в методе showPaymentBox() ->
_vk.callMethod("showOrderBox", { type: "item", votes: votes, item: itemCode } );
// и обработчик ->
var orderID:String = String(e.params[0]);
if (orderID && orderID.length > 1) {
// ну а тут уже спрашиваю у своего сервера, сколько денег у игрока сейчас
var packet:Packet = new Packet("getMoneyState", onMoneyState);
}
Все это работает безотказно. Запросы всегда приходят и обрабатываются
|