Drupal 8 commerce paypal gateway checkout programmatically example

Submitted by august on Tue, 07/25/2017 - 09:26
class OrderController extends ControllerBase implements ContainerInjectionInterface {
  
 ...

 /**
   * Checkout an order.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response which contains the ID.
   */
  public function checkoutOrder(Request $request) {
    $format = $this->getRequestFormat($request);

    $content = $request->getContent();
    $data = $this->serializer->decode($content, $format);

    if (!isset($data['order_id']) || !is_numeric($data['order_id'])) {
      throw new BadRequestHttpException('Missing order id.');
    }

    $address_required_fields = [
      'country_code',
      'administrative_area',
      'locality',
      'address_line1',
      'given_name',
      'family_name',
    ];

    if (!isset($data['billing_address']) || !is_array($data['billing_address'])){
      throw new BadRequestHttpException('Missing billing address infomation.');
    }

    foreach ($address_required_fields as $field) {
      if (!isset($data['billing_address'][$field])) {
        throw new BadRequestHttpException('Missing billing address field: ' . $field . '.');
      }
    }

    $order = Order::load(intval($data['order_id']));
    if ($order->getCustomerId() != $this->currentUser->id()) {
      throw new UnprocessableEntityHttpException('This order is not owned by current user.');
    }

    $order_state = $order->getState();
    if ($order_state->value != 'draft') {
      throw new UnprocessableEntityHttpException('This order state is not draft.');
    }

    $card_type = CreditCard::detectType($data['credit_card']['number']);
    if (!$card_type) {
      throw new NotAcceptableHttpException('You have entered a credit card number of an unsupported card type.');
    }
    if (!CreditCard::validateNumber($data['credit_card']['number'], $card_type)) {
      throw new NotAcceptableHttpException('You have entered an invalid credit card number.');
    }
    if (!CreditCard::validateExpirationDate($data['credit_card']['expire_month'], $data['credit_card']['expire_year'])) {
      throw new NotAcceptableHttpException('You have entered an expired credit card.');
    }
    if (!CreditCard::validateSecurityCode($data['credit_card']['security_code'], $card_type)) {
      throw new NotAcceptableHttpException('You have entered an invalid CVV.');
    }

    $payment_gateway = 'paypal_paymentspro';
    // The caller passed tha payment gateway ID, load the full entity.
    $payment_gateway_storage = $this->entityManager->getStorage('commerce_payment_gateway');
    /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */
    $payment_gateway = $payment_gateway_storage->load($payment_gateway);

    $payment_gateway_storage = $this->entityManager->getStorage('commerce_payment_gateway');
    /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */
    $payment_gateway = $payment_gateway_storage->loadForUser(user_load( $this->currentUser->id()));

    // @todo Move this check to the access handler.
    if (!$payment_gateway) {
      throw new AccessDeniedHttpException('Not allow access payment gateway.');
    }

    $payment_gateway_plugin = $payment_gateway->getPlugin();

    $payment_method_types = $payment_gateway_plugin->getPaymentMethodTypes();

    /** @var \Drupal\commerce_payment\Plugin\Commerce\PaymentMethodType\PaymentMethodTypeInterface $payment_method_type */
    $payment_method_type = reset($payment_method_types);

    $payment_method_storage = $this->entityManager->getStorage('commerce_payment_method');
    $payment_method = $payment_method_storage->create([
      'type' => $payment_method_type->getPluginId(),
      'payment_gateway' => $payment_gateway,
      'uid' => $this->currentUser->id()
    ]);

    // Create the billing profile.
    $profile = Profile::create([
      'type' => 'customer',
      'uid' => $this->currentUser->id(),
    ]);

    $address = [
      'country_code' => $data['billing_address']['country_code'],
      'administrative_area' => $data['billing_address']['administrative_area'],
      'locality' => $data['billing_address']['locality'],
      'address_line1' => $data['billing_address']['address_line1'],
      'given_name' => $data['billing_address']['given_name'],
      'family_name' => $data['billing_address']['family_name'],
    ];

    if (isset($data['billing_address']['dependent_locality'])) {
      $address['dependent_locality'] = $data['billing_address']['dependent_locality'];
    }
    if (isset($data['billing_address']['postal_code'])) {
      $address['postal_code'] = $data['billing_address']['postal_code'];
    }
    if (isset($data['billing_address']['sorting_code'])) {
      $address['sorting_code'] = $data['billing_address']['sorting_code'];
    }
    if (isset($data['billing_address']['address_line2'])) {
      $address['address_line2'] = $data['billing_address']['address_line2'];
    }
    if (isset($data['billing_address']['organization'])) {
      $address['organization'] = $data['billing_address']['organization'];
    }
    if (isset($data['billing_address']['additional_name'])) {
      $address['additional_name'] = $data['billing_address']['additional_name'];
    }

    $profile->address->setValue([0 => $address]);

    $profile->save();
    $payment_method->setBillingProfile($profile);
    // $payment_method->setReusable(FALSE);

    $payment_details = [
      'number' => $data['credit_card']['number'],
      'type' => $card_type->getId(),
      'expiration' => [
        'month' => $data['credit_card']['expire_month'],
        'year' => $data['credit_card']['expire_year'],
      ],
      'cvv2' => $data['credit_card']['security_code'],
    ];

    $payment_gateway_plugin->createPaymentMethod($payment_method, $payment_details);

    $payment_storage = $this->entityManager->getStorage('commerce_payment');
    $payment = $payment_storage->create([
      'state' => 'new',
      'amount' => $order->getTotalPrice(),
      'payment_gateway' => $payment_gateway->id(),
      'payment_method' => $payment_method->id(),
      'order_id' => $order->id(),
    ]);

    try {
      // $payment->payment_method = $payment_method;
      $payment_gateway_plugin->createPayment($payment, TRUE);
    }
    catch (DeclineException $e) {
      throw new UnprocessableEntityHttpException('We encountered an error processing your payment method. Please verify your details and try again.' . $message);
    }
    catch (PaymentGatewayException $e) {
      \Drupal::logger('commerce_payment')->error($e->getMessage());
      throw new UnprocessableEntityHttpException('We encountered an unexpected error processing your payment method. Please try again later.');
    }

    $transitions = $order_state->getTransitions();
    $order_state->applyTransition($transitions['place']);
    $order->set('state', $order_state->value);
    $order->save();

    $encoded_response_data = $this->serializer->serialize($order, $format);
    return new Response($encoded_response_data);

  }
}

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.