Process payment OK

@param Request $request

@return stdClass
325686
public function process(Request $request, Transaction $transaction, Delivery $delivery)
    {
        //UPDATE TRANSACTION
        $em = $this->container->get('doctrine')->getManager();
        $pm = $em->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('bank-transfer-test');
        $transaction->setStatus(Transaction::STATUS_PAID);
        $transaction->setPaymentMethod($pm);
        $em->persist($transaction);
        $em->flush();
        //confirmation payment
        $answer = new stdClass();
        $answer->redirectUrl = $this->container->get('router')->generate('ecommerce_checkout_confirmationpayment');

        return $answer;
    }
784719
public function createAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_ADMIN');

        $locale = new Locale();

        $form = $this->createForm(new LocaleType(), $locale);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($locale);
            $em->flush();

            $this->addFlash('success', 'Locale has been created successfully');

            return $this->redirectToRoute('opifer_cms_locale_edit', ['id' => $locale->getId()]);
        }

        return $this->render('OpiferCmsBundle:Backend/Locale:create.html.twig', [
            'locale' => $locale,
            'form' => $form->createView()
        ]);
    }
1309750
protected function getRequestClass($request)
    {
        $parts = explode('\\', $request);
        $lastIndex = count($parts) - 1;

        switch ($parts[$lastIndex]) {
            case 'Void':
                $parts[$lastIndex] = 'Cancel';
                break;
            case 'AVS':
            case 'INPay':
            case 'ABNiDEAL':
                $this->throwDeprecatedTransactionType();
                break;
            case 'Payin':
            case 'Payout':
                if ($this->getParentClass($parts, $lastIndex) === 'Citadel') {
                    $this->throwDeprecatedTransactionType();
                }
                break;
            case 'oBeP':
                if ($this->getParentClass($parts, $lastIndex) === 'PayByVouchers') {
                    $this->throwDeprecatedTransactionType();
                }
                break;
        }

        return sprintf(
            '\Genesis\API\Request\%s',
            implode('\\', $parts)
        );
    }
754846
public static function process(Request $request)
    {
        $uri = "/" . trim($request->pathInfo(), '/');

        // Check if this is root page
        if (isset(static::$routes['root']) and $request->pathInfo() == '/') {
            return static::setRoute(static::$routes['root']);
        }

        // The fun begins
        foreach (static::$routes as $route) {
            // Replace tokens
            $route->route = str_replace(array_keys(static::$tokens), array_values(static::$tokens), $route->route);

            // Does the route match the request?
            $pattern = "#^{$route->route}" . '(?<extension>' . implode('|', static::$extensions) . ")?$#";
            if (preg_match($pattern, $uri, $params)) {
                unset($params[0]);
                $route->params = array_merge($route->params, $params);
                $route->destination = preg_replace($pattern, $route->destination, $uri);

                // Merge params with defaults
                $route->params = array_merge($route->defaults, $route->params);

                if (in_array(strtolower($request->method()), $route->method)) {
                    return static::setRoute($route);
                }
            }
        }

        // No matches, try 404 route
        if (isset(static::$routes['404'])) {
            return static::set404();
        }
        // No 404 route, Exception time! FUN :D
        else {
            throw new Exception("No routes found for '{$uri}'");
        }
    }
561389
protected function createTransaction(Request $request)
    {
        $payment = $this->getPayment($request->get('bank'));

        $transaction = $this->transactionManager->create();
        $transaction->setPaymentCode($payment->getCode());
        $transaction->setParameters(array_replace($request->query->all(), $request->request->all()));

        return $transaction;
    }
291419
private function processRequest($request)
    {
        if (!is_array($request)) {
            return self::requestError();
        }

        // The presence of the 'id' key indicates that a response is expected
        $isQuery = array_key_exists('id', $request);

        $id = &$request['id'];

        if (($id !== null) && !is_int($id) && !is_float($id) && !is_string($id)) {
            return self::requestError();
        }

        $version = &$request['jsonrpc'];

        if ($version !== self::VERSION) {
            return self::requestError($id);
        }

        $method = &$request['method'];

        if (!is_string($method)) {
            return self::requestError($id);
        }

        // The 'params' key is optional, but must be non-null when provided
        if (array_key_exists('params', $request)) {
            $arguments = $request['params'];

            if (!is_array($arguments)) {
                return self::requestError($id);
            }
        } else {
            $arguments = array();
        }

        if ($isQuery) {
            return $this->processQuery($id, $method, $arguments);
        }

        $this->processNotification($method, $arguments);
        return null;
    }
1300313
public function process(Request $request, Transaction $transaction, Delivery $delivery)
    {
        
        if($request->request->has('pay_pal_direct_payment')){
            $data = $request->get('pay_pal_direct_payment');
            $creditCard = array(
                "number" => $data['cardNo'],
                "type" => $data['cardType'],
                "expire_month" =>  $data['expirationDate']['month'],
                "expire_year" =>  $data['expirationDate']['year'],
                "cvv2" =>  $data['CVV'],
                "first_name" =>  $data['firstname'],
                "last_name" =>  $data['lastname']
           );
            $paymentMehod = array(
            "payment_method" => "credit_card",
            "funding_instruments" => array(
                array(
                  "credit_card" => $creditCard
                )
              )
            );
        }else{
            $paymentMehod = array("payment_method" => "paypal");
        }
        
        $totals = $this->container->get('checkoutManager')->calculateTotals($transaction, $delivery);
        $this->getToken();

        $returnValues = array();
        foreach ($transaction->getItems() as $productPurchase) {
            $sub = array();
            $sub['quantity'] = $productPurchase->getQuantity();
            if($productPurchase->getProduct() instanceof Product){
                $sub['name'] = $productPurchase->getProduct()->getName();
                $sub['price'] = number_format($productPurchase->getProduct()->getPrice(), 2);
            }elseif($productPurchase->getAdvert() instanceof Advert){
                $sub['name'] = $productPurchase->getAdvert()->getTitle();
                $sub['price'] = number_format($this->advertUnitPrice, 2);
            }
            
            
            $sub['sku'] = $productPurchase->getId();
            $sub['currency'] = "EUR";
            $returnValues[] = $sub;
        }
        
        $host = $this->getHost();
        $url = $host.'/v1/payments/payment';
        $payment = array(
                        'intent' => 'sale',
                        'payer' => $paymentMehod,
                        'transactions' => array (array(
                                        'amount' => array(
                                                'total' => number_format($totals['amount'], 2),
                                                'currency' => 'EUR',
                                                'details' =>  array(
                                                    "subtotal" => number_format($totals['amount_clean'], 2),
                                                    "tax" => number_format($totals['vat'], 2),
                                                    "shipping" => $totals['delivery_expenses']
                                                  )
                                                ),
                                        'description' => 'payment using a PayPal account',
                                        "item_list" => array (
                                                "items" => $returnValues
                                                ),
                                        )),
                        'redirect_urls' => array (
                                'return_url' => $this->getReturnUrl(),
                                'cancel_url' => $this->getCancelUrl()
                        )
                    );

        $json = json_encode($payment);
        $json_resp = $this->call('POST', $url, $json);

        $em = $this->container->get('doctrine')->getManager();
        if($request->request->has('pay_pal_direct_payment')){
            if($json_resp['state'] == 'approved'){
                 //UPDATE TRANSACTION
                $pm = $em->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('paypal-direct-payment');
                $transaction->setStatus(Transaction::STATUS_PAID);
                $transaction->setPaymentMethod($pm);
                $transaction->setPaymentDetails(json_encode($json_resp));
                $em->persist($transaction);
                $em->flush();

                //confirmation payment
                $answer = new stdClass();
                $answer->redirectUrl = $this->container->get('router')->generate('ecommerce_checkout_confirmationpayment');

                return $answer;
            }else{
                //cancel payment
                $answer = new stdClass();
                $answer->redirectUrl = $this->getCancelUrl();

                return $answer;
            }
        }else{
            //UPDATE TRANSACTION
            $pm = $em->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('paypal');
            $transaction->setStatus(Transaction::STATUS_PENDING);
            $transaction->setPaymentMethod($pm);
            $transaction->setPaymentDetails(json_encode($json_resp));
            $em->persist($transaction);
            $em->flush();


            foreach ($json_resp['links'] as $link) {
                    if($link['rel'] == 'execute'){
                            $payment_execute_url = $link['href'];
                            $payment_execute_method = $link['method'];
                    }elseif($link['rel'] == 'approval_url'){
                            $payment_approval_url = $link['href'];
                            $payment_approval_method = $link['method'];
                    }
            }

            $answer = new \stdClass();
            $answer->redirectUrl = $payment_approval_url;

            return $answer;
        }
        
    }
807739
public function process(Request $request)
    {
        $this->validate($request->all(), $this->rules);

        if ($request->has('q')) {
            $this->searchQuery = $request->get('q');
        }
        if ($request->has('sort')) {
            foreach (explode(',', $request->get('sort')) as $sort) {
                $this->processOrderByParams($sort);
            }
        }
        $this->processPageParams($request);

        foreach ($this->parsers as $parser) {
            $parser->parse($request);
        }

        return $this;
    }
955724
public function summaryAction(Request $request)
    {
        /** @var CheckoutManager $checkoutManager */
        $checkoutManager = $this->get('checkout_manager');
        if (false === $checkoutManager->isDeliverySaved()) {
            return $this->redirect($this->generateUrl('ecommerce_checkout_deliveryinfo'));
        }

        $transaction = $checkoutManager->getCurrentTransaction();
        $delivery = $checkoutManager->getDelivery();
        $totals = $checkoutManager->calculateTotals($transaction, $delivery);

        /** @var PaymentManager $paymentManager */
        $paymentManager = $this->get('payment_manager');
        $psps = $paymentManager->getProviders();
 
        // process payment method form
        if ($request->isMethod('POST')) {
            foreach ($psps as $ppf) {
                if($request->request->has($ppf->getForm()->getName())){
                    $ppf->getForm()->handleRequest($request);
                    if ($ppf->getForm()->isValid()){
                        $answer = $paymentManager->processPayment($request, $transaction, $delivery, $ppf);
                        return $this->redirect($answer->redirectUrl);
                    }
                }
            }
        }

        return array(
            'transaction'    => $transaction,
            'delivery'       => $delivery,
            'totals'         => $totals,
            'psps'           => $psps
            );
    }
668144
public function callbackAction(Request $request): Response
    {
        /** @var LoggerInterface $logger */
        $logger = $this->get('logger');
        /** @var EventDispatcherInterface $dispatcher */
        $dispatcher = $this->get('event_dispatcher');

        // get the body from the request
        $content = $request->getContent();

        // decode the request object to see what kind of object this is
        $json = json_decode($content, true) ?? [];
        if (!\array_key_exists(self::NOTIFICATION_URL, $json)) {
            throw new HttpException(400, self::BAD_REQUEST);
        }

        // serialize into json and feed it to the api components
        $notificationStr = json_encode($json[self::NOTIFICATION_URL]);
        $notification = NotificationUrl::createFromJsonString($notificationStr);

        // if this is not a mutation, don't accept it
        if (self::MUTATION !== $notification->getCategory()) {
            throw new HttpException(405, self::WRONG_REQUEST_TYPE);
        }

        // if the mutation doesn't hold a payment, don't accept it
        $payment = $notification->getObject()->getPayment();
        if (null === $payment) {
            throw new HttpException(400, self::PAYMENT_MISSING_FROM_REQUEST);
        }

        // logging for historical reasons
        $logger->info(
            sprintf(
                self::RECEIVED_PAYMENT_OBJECT_FROM_BUNQ_FOR_ACCOUNT_ID,
                $payment->getMonetaryAccountId()
            ),
            [
                'monetaryAccountId' => $payment->getMonetaryAccountId(),
                'amount' => $payment->getAmount()->getValue(),
                'currency' => $payment->getAmount()->getCurrency(),
                'description' => $payment->getDescription(),
                'counter_party_iban' => $payment->getCounterpartyAlias()->getIban(),
                'counter_party_name' => $payment->getCounterpartyAlias()->getDisplayName(),
            ]
        );

        // create the event and dispatch it into the kernel
        $event = new MutationEvent($payment);
        $dispatcher->dispatch(MutationEvent::NAME, $event);

        // tell bunq we're cool
        return new Response(self::CALLBACK_OK, 200);
    }
1186960
protected function processPageParams(Request $request)
    {
        if ($request->has('page') && is_numeric($request->get('page'))) {
            $this->page = $request->get('page');
        }
        if ($request->has('per_page') && is_numeric($request->get('per_page'))) {
            $this->perPage = $request->get('per_page');
        }
    }
654527
public function execute($request): void
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var PaymentInterface $payment */
        $payment = $request->getSource();
        /** @var OrderInterface $order */
        $order = $payment->getOrder();

        $details = [];
        $details['PAYMENTREQUEST_0_INVNUM'] = $this->invoiceNumberGenerator->generate($order, $payment);
        $details['PAYMENTREQUEST_0_CURRENCYCODE'] = $order->getCurrencyCode();
        $details['PAYMENTREQUEST_0_AMT'] = $this->formatPrice($order->getTotal());
        $details['PAYMENTREQUEST_0_ITEMAMT'] = $this->formatPrice($order->getTotal());

        $m = 0;
        foreach ($order->getItems() as $item) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = $item->getVariant()->getProduct()->getName();
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($item->getDiscountedUnitPrice());
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = $item->getQuantity();

            ++$m;
        }

        if (0 !== $taxTotal = $order->getAdjustmentsTotalRecursively(AdjustmentInterface::TAX_ADJUSTMENT)) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = 'Tax Total';
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($taxTotal);
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = 1;

            ++$m;
        }

        if (0 !== $promotionTotal = $order->getOrderPromotionTotal()) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = 'Discount';
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($promotionTotal);
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = 1;

            ++$m;
        }

        if (0 !== $shippingTotal = $order->getShippingTotal()) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = 'Shipping Total';
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($shippingTotal);
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = 1;
        }

        $request->setResult($details);
    }
874128
protected function doRequest(Request $request)
    {

        $this->client->send($request, $response = new Response());

        return $response;
    }
1355013
public function cancelRedirectAction(Request $request)
    {
        $orderReference = $request->query->get('orderReference');
        $urlHmac = $request->query->get('sig');

        if ($orderReference) {
            $cancelRedirectTransfer = new PayoneCancelRedirectTransfer();
            $cancelRedirectTransfer->setOrderReference($orderReference);
            $cancelRedirectTransfer->setUrlHmac($urlHmac);

            $response = $this->getClient()->cancelRedirect($cancelRedirectTransfer);
        }

        return $this->redirectResponseInternal(PayoneControllerProvider::CHECKOUT_PAYMENT);
    }
251456
protected function call(Request $request) {
		$response = $request->execute();
		if (!$response->isSuccess()) {
			self::debug("Error in PayPal call", $response);			
			throw new PayPal_Exception_InvalidResponse("Error " . $response->status() . " in PayPal call (". $response->body() .")");
		}
		$res = json_decode($response->body());
		
		if (isset($res->error)) {
			self::error("Error in PayPal call: " . print_r($res, true));			
			throw new PayPal_Exception_InvalidResponse('PayPal: ' . $res->error_description . ' [' . $res->error . 
					'] while calling ' . $request->uri());
		}
		return $res;
	}
189321
public function handle(Request $request)
	{
		// Get response
		$response = $this->next($request);

		// Get authentication
		$token = $this->app['auth']->token();

		// Rate limit application/user id and get data
		$rateLimitData = $this->app['ratelimiter']->rateLimit($token['application_id'], $token['uidNumber']);

		// Calculate header values
		$limit     = $rateLimitData->limit_short;
		$remaining = $rateLimitData->limit_short - $rateLimitData->count_short;
		$reset     = with(new Date($rateLimitData->expires_short))->toUnix();

		// If we exceeded out rate limit lets respond accordingly
		if ($rateLimitData->exceeded_long || $rateLimitData->exceeded_short)
		{
			throw new \Exception('You have exceeded your rate limit allowance. Please see rate limit headers for details.', 429);

			// Use different values for long
			if ($rateLimitData->exceeded_long)
			{
				$limit = $rateLimitData->limit_long;
				$reset = with(new Date($rateLimitData->expires_long))->toUnix();
			}

			// Always 0 if exceeded
			$remaining = 0;
		}

		// Add rate limit headers
		$response->headers->set('X-RateLimit-Limit', $limit);
		$response->headers->set('X-RateLimit-Remaining', $remaining);
		$response->headers->set('X-RateLimit-Reset', $reset);

		// Return response
		return $response;
	}
1203848
public function charge(Request $request)
    {
        $payment = $this->paymentService->getFromSession('stripe');
        if ($payment instanceof Payment) {
            //Creates the charge on Stripe's servers - This will charge user's card
            $orderId = $this->paymentService->charge('stripe', $payment);

            if (false !== $orderId) {
                //Redirects to returnRoute, if defined, with orderId
                if (null !== $payment->getReturnRoute()) {
                    return $this->redirectToRoute($payment->getReturnRoute(), array('orderId' => $orderId));
                }

                //Redirects to payment
                return $this->redirectToRoute('payment_display', array('orderId' => $orderId));
            }

            //Redirects to payment
            return $this->redirectToRoute('payment_display', array('orderId' => $payment->getOrderId()));
        }

        //Not found
        throw $this->createNotFoundException();
    }