Create Worldpay APM order
@param array $order
@return array Worldpay order response
778350
public function createApmOrder($order = array())
    {
        $myOrder = new APMOrder($order);
        $response = OrderService::createOrder($myOrder);

        if (isset($response["orderCode"])) {
            //success
            return $response;
        } else {
            Error::throwError("apierror");
        }
    }
1020831
public function refund(array $order)
    {
        BizData::set($order);
        //金额统一使用【分】为单位
        if (BizData::get('refund_fee')) {
            BizData::set('refund_fee', bcdiv(BizData::get('refund_fee'), 100, 2));
        }
        //设定接口名称
        Datasheet::set('method', 'alipay.trade.refund');

        return Helper::request();
    }
679172
public function query(array $order)
    {
        Datasheet::set($order);
        $param_keys = ['appid', 'mch_id', 'out_trade_no', 'transaction_id', 'nonce_str'];
        return Helper::request(Helper::GATEWAY_ORDERQUERY, $param_keys);
    }
426827
protected function getFormParameters(OrderInterface $order)
    {
        return [
            'PSPID' => $this->getOption('pspid'),
            'orderId' => $order->getReference(),
            'amount' => $order->getTotalInc() * 100,
            'currency' => $order->getCurrency()->getLabel(),
            'language' => $order->getLocale(),
            'CN' => $order->getBillingName(),
            'EMAIL' => $order->getBillingEmail(),
            'ownerZIP' => $order->getBillingPostcode(),
            'owneraddress' => $this->getAddress($order),
            'ownercty' => $order->getBillingCity(),
            'ownertelno' => $order->getBillingPhone() ?: $order->getBillingMobile(),

            'homeurl' => $this->getOption('home_url'),
            'catalogurl' => $this->getOption('catalog_url'),

            'COMPLUS' => '',
            'PARAMPLUS' => 'bank='.$this->getCode(),
            'PARAMVAR' => '',

            'PM' => 'CreditCard',
            'WIN3DS' => 'MAINW',
            'PMLIST' => 'VISA;MasterCard;CB',
            'PMListType' => 2,

            'accepturl' => $this->generateAbsoluteUrlFromOption('url_callback', $order),
            'declineurl' => $this->generateAbsoluteUrlFromOption('url_callback', $order),
            'exceptionurl' => $this->generateAbsoluteUrlFromOption('url_return_ko', $order),
            'cancelurl' => $this->generateAbsoluteUrlFromOption('url_return_ko', $order),

            'operation' => $this->getOperation(),
        ];
    }
882711
public function create(array $params)
    {
        if (!array_key_exists('amount', $params) ||
            !array_key_exists('currency', $params) ||
            !array_key_exists('description', $params) ||
            !array_key_exists('order_id', $params) ||
            !array_key_exists('payment_options', $params) ||
            !array_key_exists('type', $params)
        ) {
            throw new \InvalidArgumentException('Invalid data provided.');
        }

        return $this->post('/orders', [], $params);
    }
1267584
protected function getItemListForOrder(Order $order): array
    {
        $items = [];

        $priceCheck = 0;
        $count = -1;

        /** @var LineItem $item */
        foreach ($order->lineItems as $item) {
            $price = Currency::round($item->salePrice);
            // Can not accept zero amount items. See item (4) here:
            // https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#setting-order-details-on-the-paypal-review-page

            if ($price !== 0) {
                $count++;
                /** @var Purchasable $purchasable */
                $purchasable = $item->getPurchasable();
                $defaultDescription = Craft::t('commerce', 'Item ID').' '.$item->id;
                $purchasableDescription = $purchasable ? $purchasable->getDescription() : $defaultDescription;
                $description = isset($item->snapshot['description']) ? $item->snapshot['description'] : $purchasableDescription;
                $description = empty($description) ? 'Item '.$count : $description;
                $items[] = [
                    'name' => $description,
                    'description' => $description,
                    'quantity' => $item->qty,
                    'price' => $price,
                ];

                $priceCheck += ($item->qty * $item->salePrice);
            }
        }

        $count = -1;

        /** @var OrderAdjustment $adjustment */
        foreach ($order->adjustments as $adjustment) {
            $price = Currency::round($adjustment->amount);

            // Do not include the 'included' adjustments, and do not send zero value items
            // See item (4) https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#setting-order-details-on-the-paypal-review-page
            if (($adjustment->included == 0 || $adjustment->included == false) && $price !== 0) {
                $count++;
                $items[] = [
                    'name' => empty($adjustment->name) ? $adjustment->type." ".$count : $adjustment->name,
                    'description' => empty($adjustment->description) ? $adjustment->type.' '.$count : $adjustment->description,
                    'quantity' => 1,
                    'price' => $price,
                ];
                $priceCheck += $adjustment->amount;
            }
        }

        $priceCheck = Currency::round($priceCheck);
        $totalPrice = Currency::round($order->totalPrice);
        $same = (bool)($priceCheck === $totalPrice);

        if (!$same) {
            Craft::error('Item bag total price does not equal the orders totalPrice, some payment gateways will complain.', __METHOD__);
        }

        return $items;
    }
201826
public function orderBy($sort, $order = null)
    {
        return $this->add('orderBy', $sort . ' ' . (! $order ? 'ASC' : $order), false);
    }
1293821
public function getAllSimpleItems($order)
    {
        $items = array();

        foreach ($order->getAllItems() as $item) {
            if ($item->getProductType() == 'simple') {
                $items[] = $item;
            }
        }

        return $items;
    }
1287373
protected function buildOrderJoin(string $order): array
    {
        list($column, $direction) = $this->formatOrderDirection($order);

        $lookupBuilder = $this->getLookupBuilder();

        $column = $lookupBuilder->fetchColumnName($column);
        $newOrder = $lookupBuilder->buildJoin($this, $column);
        if (false === $newOrder) {
            return [$column, $direction];
        }

        list($alias, $column) = $newOrder;

        return [
            $alias.'.'.$column,
            $direction,
        ];
    }
401395
public function createOrder(Array $params)
    {
        $createOrderRequest = $this->getRequestParam('CreateOrderRequestParam', $params, $this->config, $this->sign);

        $result = $this->executeCurlRequest($createOrderRequest);

        $result = json_decode($result, true);

        $sign = isset($result['sign']) ? $result['sign'] : '';
        $response = isset($result['alipay_trade_precreate_response']) ? $result['alipay_trade_precreate_response'] : [];
        if ($response['code'] != '10000') {
            return $this->error($this->getErrorMessage('qrpay', $response['sub_code']), $result);
        }

        $data['sign'] = $sign;
        $data['prestr'] = json_encode($response,  JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);

        if (!$this->sign->verifySign($data, $this->config['ali_rsa_public_key_path'])) {
            return $this->error('无效签名', $result);
        }

        return $this->success('发起支付成功', $response);
    }
1193895
public function applyOrder($order)
    {
        switch ($order) {
            case 'time':
                $this->orderBy(['created_at' => SORT_ASC]);
                break;

            case 'supports':
            default:
                $this->orderBy(['(supports / pow((((UNIX_TIMESTAMP(NOW()) - created_at) / 3600) + 2),1.8) )' => SORT_DESC]);
                break;
        }

        return $order;
    }
99925
public function newOrder($order)
    {
        $sorter = new Sorter();
        $sorter->target = $this;
        $sorter->order = $order;
        $sorter->query = (new Query())
                            ->from(static::tableName())
                            ->where(['and',
                                ['!=', 'id', $this->id],
                                ['category_id' => $this->category_id]
                            ])
                            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
                            ->indexBy('id');
        return $sorter->run();
    }
782467
public static function hostedOrderForm($order, $params = array())
    {
        $orderFormUrl = OpenPayU_Configuration::getServiceUrl() . 'orders';

        $formFieldValuesAsArray = array();
        $htmlFormFields = OpenPayU_Util::convertArrayToHtmlForm($order, '', $formFieldValuesAsArray);

        $signature = OpenPayU_Util::generateSignData(
            $formFieldValuesAsArray,
            OpenPayU_Configuration::getHashAlgorithm(),
            OpenPayU_Configuration::getMerchantPosId(),
            OpenPayU_Configuration::getSignatureKey()
        );

        $formParams = array_merge(self::$defaultFormParams, $params);

        $htmlOutput = sprintf("<form method=\"POST\" action=\"%s\" id=\"%s\" class=\"%s\">\n", $orderFormUrl, $formParams['formId'], $formParams['formClass']);
        $htmlOutput .= $htmlFormFields;
        $htmlOutput .= sprintf("<input type=\"hidden\" name=\"OpenPayu-Signature\" value=\"%s\" />", $signature);
        $htmlOutput .= sprintf("<button type=\"submit\" formtarget=\"%s\" id=\"%s\" class=\"%s\">%s</button>", $formParams['submitTarget'], $formParams['submitId'], $formParams['submitClass'], $formParams['submitContent']);
        $htmlOutput .= "</form>\n";

        return $htmlOutput;
    }
67588
public function updateFromApiResponse(array $data): OrderInterface
    {
        $order = $this->orderRepository->findOneByExternalId($data['id']);
        if (!$order) {
            $order = new Order();
        }

        // we start by syncing the currency, since we use the currency to create Money objects
        $currency = $this->currencyRepository->findOneByCode($data['currencyCode']);
        if (!$currency) {
            $currency = $this->currencySynchronizer->syncOne([
                'code' => $data['currencyCode'],
            ]);

            // this means that the currency does not exist anymore
            // @todo create placeholder
            if (!$currency) {
                throw new \RuntimeException('Could not sync currency `'.$data['currencyCode'].'`. Try again');
            }
        }

        $currencyCode = $currency->getIsoCodeAlpha();

        // set shortcuts for embedded objects
        $orderLinesData = $data['orderLines'] ?? [];
        $paymentData = $data['paymentInfo'] ?? [];
        $shippingData = $data['shippingInfo'] ?? [];

        $createdDate = DateTimeImmutable::createFromJson($data['createdDate']);
        $modifiedDate = $data['modifiedDate'] ? DateTimeImmutable::createFromJson($data['modifiedDate']) : null;

        $giftCertificateAmount = DandomainFoundation\createMoneyFromFloat($currencyCode, $data['giftCertificateAmount']);
        $totalPrice = DandomainFoundation\createMoneyFromFloat($currencyCode, $data['totalPrice']);
        $salesDiscount = DandomainFoundation\createMoneyFromFloat($currencyCode, $data['salesDiscount']);
        $paymentMethodFee = DandomainFoundation\createMoneyFromFloat($currencyCode, $paymentData['fee'] ?? 0.0);
        $shippingMethodFee = DandomainFoundation\createMoneyFromFloat($currencyCode, $shippingData['fee'] ?? 0.0);

        $order
            ->setExternalId($data['id'])
            ->setCurrency($currency)
            ->setComment($data['comment'])
            ->setCreatedDate($createdDate)
            ->setCustomerComment($data['customerComment'])
            ->setGiftCertificateAmount($giftCertificateAmount)
            ->setGiftCertificateNumber($data['giftCertificateNumber'])
            ->setIncomplete($data['incomplete'])
            ->setIp($data['ip'])
            ->setModified($data['modified'])
            ->setModifiedDate($modifiedDate)
            ->setReferenceNumber($data['referenceNumber'])
            ->setReferrer($data['referrer'])
            ->setReservedField1($data['reservedField1'])
            ->setReservedField2($data['reservedField2'])
            ->setReservedField3($data['reservedField3'])
            ->setReservedField4($data['reservedField4'])
            ->setReservedField5($data['reservedField5'])
            ->setSalesDiscount($salesDiscount)
            ->setTotalPrice($totalPrice)
            ->setTotalWeight($data['totalWeight'])
            ->setTrackingNumber($data['trackingNumber'])
            ->setTransactionNumber($data['transactionNumber'])
            ->setVatPct((float) $data['vatPct'])
            ->setVatRegNumber($data['vatRegNumber'])
            ->setXmlParams($data['xmlParams'])
            ->setShippingMethodFee($shippingMethodFee)
            ->setPaymentMethodFee($paymentMethodFee)
        ;

        // populate customer info
        $customer = $this->customerUpdater->updateFromEmbeddedApiResponse($data['customerInfo']);
        $order->setCustomer($customer);

        // populate delivery info
        $delivery = $this->deliveryUpdater->updateFromEmbeddedApiResponse($data['deliveryInfo'], $order->getDelivery());
        $order->setDelivery($delivery);

        // populate invoice info
        $invoice = $this->invoiceUpdater->updateFromEmbeddedApiResponse($data['invoiceInfo'], $order->getInvoice());
        $order->setInvoice($invoice);

        // populate payment info
        $paymentMethod = $this->paymentMethodUpdater->updateFromEmbeddedApiResponse($data['paymentInfo'], $currencyCode, $order->getPaymentMethod());
        $order->setPaymentMethod($paymentMethod);

        // populate shipping info
        $shippingMethod = $this->shippingMethodUpdater->updateFromEmbeddedApiResponse($data['shippingInfo'], $currencyCode, $order->getShippingMethod());
        $order->setShippingMethod($shippingMethod);

        // populate site
        $site = $this->siteRepository->findOneByExternalId($data['siteId']);
        if (!$site) {
            $site = $this->siteSynchronizer->syncOne([
                'externalId' => $data['siteId'],
            ]);

            // this means that the site does not exist anymore so we create a placeholder
            if (!$site) {
                $site = new Site();
                $site->setExternalId($data['siteId'])
                    ->setName((string) $data['siteId'])
                    ->setCurrency($currency)
                ;

                // we soft delete the site because it does not exist anymore
                $site->delete();

                $this->siteRepository->save($site);
            }
        }
        $order->setSite($site);

        // populate state
        $state = $this->stateRepository->findOneByExternalId($data['orderState']['id']);
        if(!$state) {
            $state = $this->stateSynchronizer->syncOne([
                'externalId' => $data['orderState']['id']
            ]);

            if(!$state) {
                // @todo create placeholder
                throw new \InvalidArgumentException('The order state `'.$data['orderState']['name'].'` (id: '.$data['orderState']['id'].') does not exist');
            }
        }
        $order->setState($state);

        if (count($orderLinesData)) {
            // first remove order lines that are not present anymore
            $removeOrderLines = [];
            foreach ($order->getOrderLines() as $orderLineEntity) {
                $found = false;
                foreach ($orderLinesData as $orderLineData) {
                    if ($orderLineData['id'] === $orderLineEntity->getExternalId()) {
                        $found = true;
                    }
                }

                if (!$found) {
                    $removeOrderLines[] = $orderLineEntity;
                }
            }

            foreach ($removeOrderLines as $removeOrderLine) {
                $order->removeOrderLine($removeOrderLine);
            }

            // then update the rest of the order lines
            foreach ($orderLinesData as $orderLineData) {
                if (!$orderLineData['id']) {
                    continue;
                }

                $collection = $order
                    ->getOrderLines()
                    ->matching(
                        Criteria::create()->where(Criteria::expr()->eq('externalId', $orderLineData['id']))
                    );

                if ($collection->count()) {
                    $orderLineEntity = $collection->first();
                } else {
                    $orderLineEntity = new OrderLine();
                    $order->addOrderLine($orderLineEntity);
                }

                $orderLineUnitPrice = DandomainFoundation\createMoneyFromFloat($currencyCode, $orderLineData['unitPrice'] ?? 0.0);
                $orderLineTotalPrice = DandomainFoundation\createMoneyFromFloat($currencyCode, $orderLineData['totalPrice'] ?? 0.0);

                $orderLineEntity
                    ->setExternalId((int) $orderLineData['id'])
                    ->setFileUrl($orderLineData['fileUrl'])
                    ->setProductNumber($orderLineData['productId'])
                    ->setProductName($orderLineData['productName'])
                    ->setQuantity((int) $orderLineData['quantity'])
                    ->setTotalPrice($orderLineTotalPrice)
                    ->setUnitPrice($orderLineUnitPrice)
                    ->setVatPct((float) $orderLineData['vatPct'])
                    ->setVariant($orderLineData['variant'])
                    ->setXmlParams($orderLineData['xmlParams'])
                ;

                $product = $this->getProductFromOrderLine($orderLineEntity);
                if ($product) {
                    $orderLineEntity->setProduct($product);
                }
            }
        } else {
            $order->clearOrderLines();
        }

        return $order;
    }
478936
protected function doPay(Order $order)
    {
        if ('TEST' == Paybox::getConfigValue('mode', false)) {
            $platformUrl = Paybox::getConfigValue('url_serveur_test', false);
        } else {
            $platformUrl = Paybox::getConfigValue('url_serveur', false);
        }

        // Be sure to have a valid platform URL, otherwise give up
        if (false === $platformUrl) {
            throw new \InvalidArgumentException(
                Translator::getInstance()->trans(
                    "The platform URL is not defined, please check Paybox module configuration.",
                    [],
                    Paybox::MODULE_DOMAIN
                )
            );
        }

        $hashAlgo = $this->getHashAlgorithm();
        $clefPrivee = Paybox::getConfigValue('clef_privee');

        $paybox_params = $this->doPayPayboxParameters($order)
            + [
                'PBX_HASH' => $hashAlgo,
                'PBX_SECRET' => $clefPrivee
            ];

        // Generate signature
        $param = '';

        foreach ($paybox_params as $key => $value) {
            $param .= "&" . $key . '=' . $value;
        }

        $param = ltrim($param, '&');

        $binkey = pack('H*', $clefPrivee);

        $paybox_params['PBX_HMAC'] = strtoupper(hash_hmac($hashAlgo, $param, $binkey));

        return $this->generateGatewayFormResponse($order, $platformUrl, $paybox_params);
    }
630573
public function create(array $data) {
        $this->_checkAcl('create');
        $pk = $this->_model->insert($data);
        return $pk;
    }
1056945
protected function calculateOrderStatus($orderPayment, $order)
    {
        $orderPaymentStatusCalculator = $this->getOrderPaymentStatusCalculator();
        $orderPaymentStatusCalculator->setOrderPayment($orderPayment);
        $orderPaymentStatusCalculator->setOrder($order);

        $newOrderStatus = $orderPaymentStatusCalculator->getStatus();

        return $newOrderStatus;
    }