<?php

$service = new Crucial_Service_ChargifyV2(array('api_id' => '{{API_ID}}', 'api_password' => '{{API_PASSWORD}}', 'api_secret' => '{{API_SECRET}}', 'format' => 'json'));
$direct = $service->direct();
// The redirect  URL
$direct->setRedirect('http://' . $_SERVER['HTTP_HOST'] . '/success');
// get the <form> action attribute for your form.
$formAction = $this->direct->getSignupAction();
// set tamper-proof data. https://docs.chargify.com/chargify-direct-introduction#secure-data
$direct->setData(array('signup' => array('product' => array('handle' => 'pro')), 'address' => array('city' => 'Raleigh')));
// get hidden fields for your form
$fields = $direct->getHiddenFields();
// After Chargify redirect back to your app, test if response signature is correct
if (!$direct->isValidResponseSignature()) {
    // we should throw a hard exception here because there is a good chance we are being attacked
    throw new Crucial_Service_ChargifyV2_Exception('Invalid response signature after redirect from Chargify');
}
 /**
  * Handle the redirection from Chargify after card update
  *
  * The GET part of POST/REDIRECT/GET
  *
  * @param Crucial_Service_ChargifyV2 $service
  *
  * @throws Crucial_Service_ChargifyV2_Exception
  */
 protected function _handleCardUpdateRedirect(Crucial_Service_ChargifyV2 $service)
 {
     $direct = $service->direct();
     /**
      * Example query string after redirect
      *
      * api_id=643c0f40-2d26-0130-27f0-026566abd2f9
      * call_id=aede0389cc7fc3d344e5f07907e49d2c3c3875ea
      * nonce=831398958abe9bccca1aebb2e506ad0c452d2bc1
      * result_code=4000
      * signature=c813313869f92aeb8dfe9ed6280922fa62465777
      * status_code=422
      * timestamp=1356143461
      */
     // Test for a valid response signature.
     if (!$direct->isValidResponseSignature()) {
         // we should throw a hard exception here because there is a good chance we are being attacked
         throw new Crucial_Service_ChargifyV2_Exception('Invalid response signature after redirect from Chargify');
     }
     // Get the original call from Chargify
     $call = $service->call();
     $theCall = $call->readByChargifyId($_GET['call_id']);
     $this->log($theCall);
     // For some reason $theCall['status'] is always NULL for a credit card update.
     // This is different from signups where we can expect TRUE/FALSE.
     // @todo - ask Chargify about this inconsistent behavior
     if (200 != $theCall['response']['result']['status_code']) {
         // Tell the view there was an error so we can alert the user.
         $this->view->isError = TRUE;
         // repopulate the form with original request data
         $this->view->request = $theCall['request'];
     } else {
         $this->view->isSuccess = TRUE;
     }
 }