You are here

function commerce_paypal_wpp_submit_form_submit in Commerce PayPal 7

Same name and namespace in other branches
  1. 7.2 modules/wpp/commerce_paypal_wpp.module \commerce_paypal_wpp_submit_form_submit()

Payment method callback: checkout form submission.

File

modules/wpp/commerce_paypal_wpp.module, line 231
Implements PayPal Website Payments Pro in Drupal Commerce checkout.

Code

function commerce_paypal_wpp_submit_form_submit($payment_method, $pane_form, $pane_values, $order, $charge) {

  // Display an error and prevent the payment attempt if PayPal WPP has not been
  // configured yet.
  if (empty($payment_method['settings'])) {
    drupal_set_message(t('This payment method must be configured by an administrator before it can be used.'), 'error');
    return FALSE;
  }

  // Ensure we can determine a valid IPv4 IP address as required by PayPal WPP.
  $ip_address = ip_address();

  // Go ahead and convert localhost from IPv6 to IPv4.
  if ($ip_address == '::1') {
    $ip_address = '127.0.0.1';
    watchdog('commerce_paypal_wpp', 'PayPal WPP must be able to retrieve an IPv4 IP address from the ip_address() function when not testing payments from localhost. While testing from localhost, your IPv6 address ::1 was automatically converted to 127.0.0.1.', array(), WATCHDOG_WARNING);
  }
  if (!filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
    drupal_set_message(t('This payment method is not supported by the current web server configuration.'), 'error');
    watchdog('commerce_paypal_wpp', 'PayPal WPP must be able to retrieve an IPv4 IP address from the ip_address() function when not testing payments from localhost.', array(), WATCHDOG_ERROR);
    return FALSE;
  }

  // Determine the currency code to use to actually process the transaction,
  // which will either be the default currency code or the currency code of the
  // charge if it's supported by PayPal if that option is enabled.
  $currency_code = $payment_method['settings']['currency_code'];
  if (!empty($payment_method['settings']['allow_supported_currencies']) && in_array($charge['currency_code'], array_keys(commerce_paypal_wpp_currencies()))) {
    $currency_code = $charge['currency_code'];
  }

  // Convert the charge amount to the specified currency.
  $amount = commerce_currency_convert($charge['amount'], $charge['currency_code'], $currency_code);

  // PayPal WPP requires a billing address, so ensure one has been added to the
  // order before building the name-value pair array.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $valid_billing_address = TRUE;
  if (empty($order->commerce_customer_billing) || empty($order_wrapper->commerce_customer_billing
    ->value()->commerce_customer_address)) {
    $valid_billing_address = FALSE;
  }
  else {

    // Check the values in the billing address array required by PayPal.
    $address_value = $order_wrapper->commerce_customer_billing->commerce_customer_address
      ->value();
    if (empty($address_value['name_line']) && empty($address_value['first_name'])) {
      $valid_billing_address = FALSE;
    }
    foreach (array(
      'thoroughfare',
      'locality',
      'postal_code',
      'country',
    ) as $address_key) {
      if (empty($address_value[$address_key])) {
        $valid_billing_address = FALSE;
      }
    }
  }

  // Without a valid villing address, display and log the error messages and
  // prevent the payment attempt.
  if (!$valid_billing_address) {

    // Display a general error to the customer if we can't find the address.
    drupal_set_message(t('We cannot process your credit card payment without a valid billing address.'), 'error');

    // Provide a more descriptive error message in the failed transaction and
    // the watchdog.
    $transaction = commerce_payment_transaction_new('paypal_wpp', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $amount;
    $transaction->currency_code = $currency_code;
    $transaction->payload[REQUEST_TIME] = array();
    $transaction->status = COMMERCE_PAYMENT_STATUS_FAILURE;
    $transaction->message = t('The customer must be able to supply a billing address through the default address field of the core billing information customer profile to pay via PayPal WPP.');
    commerce_payment_transaction_save($transaction);
    watchdog('commerce_paypal_wpp', 'A PayPal WPP transaction failed because the order did not have a value for the default billing address field. Your order or checkout configuration may need to be adjusted to support credit card payment via PayPal WPP.', NULL, WATCHDOG_ERROR);
    return FALSE;
  }

  // Build a name-value pair array for this transaction.
  $nvp = array(
    'METHOD' => 'DoDirectPayment',
    'PAYMENTACTION' => commerce_paypal_wpp_payment_action($payment_method['settings']['txn_type']),
    'NOTIFYURL' => commerce_paypal_ipn_url($payment_method['instance_id']),
    'CREDITCARDTYPE' => commerce_paypal_wpp_card_type($pane_values['credit_card']['type']),
    'ACCT' => $pane_values['credit_card']['number'],
    'EXPDATE' => $pane_values['credit_card']['exp_month'] . $pane_values['credit_card']['exp_year'],
    'AMT' => commerce_currency_amount_to_decimal($amount, $currency_code),
    'CURRENCYCODE' => $currency_code,
  );

  // Add the start date and issue number if processing a Maestro or Solo card.
  if (in_array($pane_values['credit_card']['type'], array(
    'maestro',
    'solo',
  ))) {
    if (!empty($pane_values['credit_card']['start_month']) && !empty($pane_values['credit_card']['start_year'])) {
      $nvp['STARTDATE'] = $pane_values['credit_card']['start_month'] . $pane_values['credit_card']['start_year'];
    }
    if (!empty($pane_values['credit_card']['issue'])) {
      $nvp['ISSUENUMBER'] = $pane_values['credit_card']['issue'];
    }
  }

  // Add the CVV if entered on the form.
  if (isset($pane_values['credit_card']['code'])) {
    $nvp['CVV2'] = $pane_values['credit_card']['code'];
  }

  // Build a description for the order.
  $description = array();
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if (in_array($line_item_wrapper->type
      ->value(), commerce_product_line_item_types())) {
      $description[] = round($line_item_wrapper->quantity
        ->value(), 2) . 'x ' . $line_item_wrapper->line_item_label
        ->value();
    }
  }

  // Prepare the billing address for use in the request.
  $billing_address = $order_wrapper->commerce_customer_billing->commerce_customer_address
    ->value();
  if (empty($billing_address['first_name'])) {
    $name_parts = explode(' ', $billing_address['name_line']);
    $billing_address['first_name'] = array_shift($name_parts);
    $billing_address['last_name'] = implode(' ', $name_parts);
  }

  // Add additional transaction invormation to the request array.
  $nvp += array(
    // Order Information; we append the timestamp to the order number to allow
    // for multiple transactions against the same order.
    'INVNUM' => substr($order->order_number, 0, 127) . '-' . REQUEST_TIME,
    'CUSTOM' => substr(t('Order @number', array(
      '@number' => $order->order_number,
    )), 0, 256),
    'DESC' => substr(implode(', ', $description), 0, 127),
    // Customer Information
    'EMAIL' => substr($order->mail, 0, 127),
    'IPADDRESS' => substr($ip_address, 0, 15),
    'FIRSTNAME' => substr($billing_address['first_name'], 0, 25),
    'LASTNAME' => substr($billing_address['last_name'], 0, 25),
    'STREET' => substr($billing_address['thoroughfare'], 0, 100),
    'STREET2' => substr($billing_address['premise'], 0, 100),
    'CITY' => substr($billing_address['locality'], 0, 40),
    'STATE' => substr($billing_address['administrative_area'], 0, 40),
    'COUNTRYCODE' => $billing_address['country'],
    'ZIP' => substr($billing_address['postal_code'], 0, 20),
  );

  // Submit the request to PayPal.
  $response = commerce_paypal_wpp_request($payment_method, $nvp, $order);

  // Prepare a transaction object to log the API response.
  $transaction = commerce_payment_transaction_new('paypal_wpp', $order->order_id);
  $transaction->instance_id = $payment_method['instance_id'];
  $transaction->amount = $amount;
  $transaction->currency_code = $currency_code;
  $transaction->payload[REQUEST_TIME] = $response;

  // Build a meaningful response message.
  $message = array();
  $action = commerce_paypal_wpp_reverse_payment_action($nvp['PAYMENTACTION']);

  // Set the remote ID and transaction status based on the acknowledgment code.
  switch ($response['ACK']) {
    case 'SuccessWithWarning':
    case 'Success':
      $transaction->remote_id = $response['TRANSACTIONID'];

      // Set the transaction status based on the type of transaction this was.
      switch ($payment_method['settings']['txn_type']) {
        case COMMERCE_CREDIT_AUTH_ONLY:
          $transaction->status = COMMERCE_PAYMENT_STATUS_PENDING;
          break;
        case COMMERCE_CREDIT_AUTH_CAPTURE:
          $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
          break;
      }
      if ($response['ACK'] == 'SuccessWithWarning') {
        $message[0] = '<b>' . t('@action - Success (with warning)', array(
          '@action' => $action,
        )) . '</b>';
        $message[] = t('@severity @code: @message', array(
          '@severity' => $response['L_SEVERITYCODE0'],
          '@code' => $response['L_ERRORCODE0'],
          '@message' => $response['L_LONGMESSAGE0'],
        ));
      }
      else {
        $message[] = '<b>' . t('@action - Success', array(
          '@action' => $action,
        )) . '</b>';
      }

      // Add the AVS response if present.
      if (!empty($response['AVSCODE'])) {
        $message[] = t('AVS response: @avs', array(
          '@avs' => commerce_paypal_avs_code_message($response['AVSCODE']),
        ));
      }

      // Add the CVV response if present.
      if ($payment_method['settings']['code'] && !empty($response['CVV2MATCH'])) {
        $message[] = t('CVV2 match: @cvv', array(
          '@cvv' => commerce_paypal_cvv_match_message($response['CVV2MATCH']),
        ));
      }
      break;
    case 'FailureWithWarning':
    case 'Failure':
    default:

      // Create a failed transaction with the error message.
      $transaction->status = COMMERCE_PAYMENT_STATUS_FAILURE;
      $message[] = '<b>' . t('@action - Failure', array(
        '@action' => $action,
      )) . '</b>';
      $message[] = t('@severity @code: @message', array(
        '@severity' => $response['L_SEVERITYCODE0'],
        '@code' => $response['L_ERRORCODE0'],
        '@message' => $response['L_LONGMESSAGE0'],
      ));
  }

  // Store the type of transaction in the remote status.
  $transaction->remote_status = $nvp['PAYMENTACTION'];

  // Set the final message.
  $transaction->message = implode('<br />', $message);

  // Save the transaction information.
  commerce_payment_transaction_save($transaction);

  // If the payment failed, display an error and rebuild the form.
  if (!in_array($response['ACK'], array(
    'SuccessWithWarning',
    'Success',
  ))) {
    drupal_set_message(t('We encountered an error processing your payment. Please verify your credit card details or try a different card.'), 'error');
    return FALSE;
  }
}