Skip to content

Commit

Permalink
Corrige data de próximo pagamento e desabilita renovação automática d…
Browse files Browse the repository at this point in the history
…e pedido do WC Subscriptions (#102)

* Desabilita o handling de renewal orders pelo WC_Subscriptions
para assinaturas do Vindi

* - Criada função na API para buscar assinatura
- Corrigida função de atualizar próximo pagamento para buscar a subscription
do Vindi e usar a data correta

* Refatora métodos isCanceledSubscription e getSubscription

* Altera validação da consulta de status de assinatura (pré-cancelamento)

* Ajusta parâmetro 'data do próximo pagamento'

* Ajusta validação de certificado para métodos de pagamento
  • Loading branch information
cristian-rossi authored and laerte-guimaraes committed Oct 8, 2018
1 parent e39b943 commit e14680f
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 26 deletions.
27 changes: 22 additions & 5 deletions includes/class-vindi-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,20 @@ public function activate_subscription($subscription_id)
return false;
}


/**
* @param int $subscription_id
*
* @return array|bool|mixed
*/
public function get_subscription($subscription_id)
{
if ($response = $this->request(sprintf('subscriptions/%s', $subscription_id),'GET')['subscription'])
return $response;

return false;
}

/**
* @param int $bill_id
*
Expand All @@ -264,19 +278,22 @@ public function delete_bill($bill_id)
*/
public function is_subscription_active($subscription_id)
{
if (isset($this->recentRequest)) {
unset($this->recentRequest);
if (isset($this->recentRequest)
&& $this->recentRequest['id'] == $subscription_id) {
if ($this->recentRequest['status'] != 'canceled')
return true;
return false;
}

$response = $this->request(sprintf('subscriptions/%s', $subscription_id),'GET')['subscription'];
$response = $this->get_subscription($subscription_id);

if (array_key_exists('status', $response)) {
if ($response && array_key_exists('status', $response)) {
if ($response['status'] != 'canceled') {
$this->recentRequest = $subscription_id;
$this->recentRequest = $response;
return true;
}
}
return false;
}

public function find_customer_by_code($code)
Expand Down
2 changes: 1 addition & 1 deletion includes/class-vindi-bank-slip-gateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function payment_fields()

$is_single_order = $this->is_single_order();

if (!($is_trial = $this->container->get_is_active_sandbox()))
if ($is_trial = $this->container->get_is_active_sandbox())
$is_trial = $this->container->api->is_merchant_status_trial_or_sandbox();

$this->container->get_template('bankslip-checkout.html.php', compact('is_trial', 'is_single_order'));
Expand Down
2 changes: 1 addition & 1 deletion includes/class-vindi-creditcard-gateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ public function payment_fields()
for ($i = date('Y') ; $i <= date('Y') + 15 ; $i++)
$years[] = $i;

if (!($is_trial = $this->container->get_is_active_sandbox()))
if ($is_trial = $this->container->get_is_active_sandbox())
$is_trial = $this->container->api->is_merchant_status_trial_or_sandbox();

$this->container->get_template('creditcard-checkout.html.php', compact(
Expand Down
37 changes: 37 additions & 0 deletions includes/class-vindi-wcs-disable-renewal.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
if (!defined('ABSPATH')) {
die('not allowed');
}

new Vindi_WCS_Disable_Renewal;

class Vindi_WCS_Disable_Renewal
{
public function __construct() {
//hook as early as possible to try disabling WC_Subcriptions_Manager handling
add_action( 'wp_loaded', array( __CLASS__, 'hook_before_prepare_renewal' ), 1 );
}

static function hook_before_prepare_renewal() {
//check if subscription manager exists
if (class_exists( 'WC_Subscriptions_Manager', false )) {
//prepare_renewal runs on 1 priority, so we hook in first
add_action('woocommerce_scheduled_subscription_payment', array(
__CLASS__,
'maybe_deactivate_prepare_renewal'
), 0, 1);
}
}

static function maybe_deactivate_prepare_renewal($subscription_id) {

$subscription = wcs_get_subscription($subscription_id);

//easy check to see if this subscriptions is a Vindi Subscription
if (!empty($subscription->get_meta('vindi_wc_subscription_id'))) {
//if it is we disable Woocommerce Subscriptions Renewal order and let Vindi handle it via webhooks
remove_action('woocommerce_scheduled_subscription_payment',
'WC_Subscriptions_Manager::prepare_renewal', 1);
}
}
}
51 changes: 32 additions & 19 deletions includes/class-vindi-webhook-handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,20 +111,20 @@ private function subscription_renew($renew_infos)
**/
private function bill_created($data)
{
if(empty($data->bill->subscription)) {
if (empty($data->bill->subscription)) {
return;
}

$renew_infos = [
'wc_subscription_id' => $data->bill->subscription->code,
'vindi_subscription_id' => $data->bill->subscription->id,
'cycle' => $data->bill->period->cycle,
'bill_id' => $data->bill->id
];

if(!$this->subscription_has_order_in_cycle($renew_infos['vindi_subscription_id'], $renew_infos['cycle'])) {
if (!$this->subscription_has_order_in_cycle($renew_infos['vindi_subscription_id']
, $renew_infos['cycle'])) {
$this->subscription_renew($renew_infos);
$this->update_next_payment($data);
}
}

Expand All @@ -139,12 +139,13 @@ private function bill_paid($data)
} else {
$vindi_subscription_id = $data->bill->subscription->id;
$cycle = $data->bill->period->cycle;

$order = $this->find_order_by_subscription_and_cycle($vindi_subscription_id, $cycle);
}

$new_status = $this->container->get_return_status();
$order->update_status($new_status, __('O Pagamento foi realizado com sucesso pela Vindi.', 'woocommerce-vindi'));
$order->update_status($new_status, __('O Pagamento foi realizado com sucesso pela Vindi.',
'woocommerce-vindi'));
$this->update_next_payment($data);
}

/**
Expand Down Expand Up @@ -190,7 +191,8 @@ private function charge_rejected($data)
if($order->get_status() == 'pending'){
$order->update_status('failed', 'Pagamento rejeitado!');
}else{
throw new Exception('Erro ao trocar status da fatura para "failed" pois a fatura #' . $data->charge->bill->id . ' não está mais pendente!');
throw new Exception('Erro ao trocar status da fatura para "failed" pois a fatura #' .
$data->charge->bill->id . ' não está mais pendente!');
}
}

Expand All @@ -201,7 +203,7 @@ private function charge_rejected($data)
private function subscription_canceled($data)
{
$subscription = $this->find_subscription_by_id($data->subscription->code);

if ($this->container->get_synchronism_status()
&& ($subscription->has_status('cancelled')
|| $subscription->has_status('pending-cancel')
Expand Down Expand Up @@ -364,16 +366,27 @@ private function query_order_by_metas(array $metas)
return new WP_Query($args);
}

/**
* Update next payment schedule of subscription
* @param $next_payment string
* @param $subscription_id int wc subscription id
**/
private function update_next_payment($data)
{
$subscription = $this->find_subscription_by_id($data->bill->subscription->code);
$next_payment = date('Y-m-d H:i:s', strtotime($data->bill->period->end_at . ' + 3 days'));
/**
* Update next payment schedule of subscription
*
* @param $data object
**/
private function update_next_payment($data) {

$subscription->update_dates(array('next_payment' => $next_payment));
}
// let's find the subscription in the API
// we need this step because the actual next billing date does not come from the /bill webhook
$vindi_subscription = $this->container->api->get_subscription($data->bill->subscription->id);

if ($vindi_subscription && isset($vindi_subscription['next_billing_at'])) {

// format next payment date
$next_payment = date('Y-m-d H:i:s', strtotime($vindi_subscription['next_billing_at']));

// find our wc_subscription
$subscription = $this->find_subscription_by_id($data->bill->subscription->code);

// update the date to show the user when will be his next payment
$subscription->update_dates(array('next_payment' => $next_payment));
}
}
}
1 change: 1 addition & 0 deletions vindi-woocommerce-subscriptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public function __construct()
'class-vindi-payment.php',
'class-vindi-webhook-handler.php',
'class-vindi-subscription-status-handler.php',
'class-vindi-wcs-disable-renewal.php',
));

$this->settings = new Vindi_Settings();
Expand Down

0 comments on commit e14680f

Please sign in to comment.