Pay an order.

@author yansongda <me@yansongda.cn>

@param string $gateway
@param array  $params

@throws InvalidGatewayException

@return Response|Collection
514023
public function pay($gateway, $params = [])
    {
        Events::dispatch(Events::PAY_STARTING, new Events\PayStarting('Alipay', $gateway, $params));

        $this->payload['return_url'] = $params['return_url'] ?? $this->payload['return_url'];
        $this->payload['notify_url'] = $params['notify_url'] ?? $this->payload['notify_url'];

        unset($params['return_url'], $params['notify_url']);

        $this->payload['biz_content'] = json_encode($params);

        $gateway = get_class($this).'\\'.Str::studly($gateway).'Gateway';

        if (class_exists($gateway)) {
            return $this->makePay($gateway);
        }

        throw new InvalidGatewayException("Pay Gateway [{$gateway}] not exists");
    }
508808
public function getGateway($id): GatewayInterface
    {
        $gateway = $this->_gateways[$id] ?? null;

        if ($gateway === null) {
            throw new InvalidArgumentException("Gateway: `$id` not exist!");
        } elseif (!$gateway instanceof GatewayInterface) {

            if (is_string($gateway)) {
                $gateway = ['class' => $gateway];
            }

            if (is_array($gateway)) {
                $gateway = ArrayHelper::merge($this->gatewayConfig, $gateway);
            }

            $gateway = $this->_gateways[$id] = Yii::createObject($gateway);
        }

        return $gateway;
    }
1128381
public function purchase(array $parameters = array())
    {
        /** @todo create customer before payment if none supplied */

        // schedule regular payment
        if (isset($parameters['frequency']) && $parameters['frequency'] !== 'once') {
            return $this->createRequest('\Omnipay\PaywayRest\Message\RegularPaymentRequest', $parameters);
        }

        // process once-off payment
        return $this->createRequest('\Omnipay\PaywayRest\Message\PurchaseRequest', $parameters);
    }
387791
public static function doCardPayment($arg_params)
    {
        //validate params
        $data = self::getParams($arg_params);
        if(!empty($data['order'])){
            $data['rdata']['order'] = json_decode(json_encode($data['order']), true);
        }
        unset($data['order']);
        if(!empty($data['metadata'])){
            $data['metadata'] = json_decode(json_encode($data['metadata']),true);
        }
        $data['source_id'] = Due::getAppId();
        $data['rail_type'] = Due::getRailType();
        $data['amount'] = number_format(floatval($data['amount']), 2, '.', '');

        if(
            !empty($data['webhook_url']) &&
            (!preg_match("%^(http|https)://\S+%", $data['webhook_url']) ||
                filter_var($data['webhook_url'], FILTER_VALIDATE_URL) === false)
        ){
            throw new \Exception('invalid webhook url given',4040001);
        }

        //submit to api
        $customer_data = APIRequests::request(
            '/ecommerce/payments/card',
            APIRequests::METHOD_POST,
            array('payload'=>$data)
        );

        //return response
        return self::toObj($customer_data['body']);
    }
359491
protected function redirect(Response $response, $route, array $params = [])
    {
        return $response->withRedirect($this->container['router']->pathFor($route, $params));
    }
609594
public function getUrl($path, array $params = [])
    {
        $parts = parse_url($this->baseUrl.'/'.trim($path, '/'));

        if ($parts === false) {
            throw new InvalidArgumentException('Not a valid path.');
        }

        $parts['path'] = '/'.trim($parts['path'], '/');

        if ($this->signature) {
            $params = $this->signature->addSignature($parts['path'], $params);
        }

        return $this->buildUrl($parts, $params);
    }
1275446
public function create($params)
    {
        Util::verifyKeys(self::createSignature(), $params);

        $file = $params['file'];

        if (!is_resource($file)) {
            throw new InvalidArgumentException('file must be a stream resource');
        }

        $payload = [
            'document_upload[kind]' => $params['kind']
        ];
        $path = $this->_config->merchantPath() . '/document_uploads/';
        $response = $this->_http->postMultipart($path, $payload, $file);

        if (isset($response['apiErrorResponse'])) {
            return new Result\Error($response['apiErrorResponse']);
        }

        if (isset($response['documentUpload'])) {
            $documentUpload = DocumentUpload::factory($response['documentUpload']);
            return new Result\Successful($documentUpload);
        }
    }
104473
public function initiate($data = array())
    {
        if ($this->payment->Status !== 'Created') {
            throw new InvalidStateException('Cannot create a card for this payment. Status is not "Created"');
        }

        if (!$this->payment->isInDB()) {
            $this->payment->write();
        }

        $gateway = $this->oGateway();
        if (!$gateway->supportsCreateCard()) {
            throw new InvalidConfigurationException(
                sprintf('The gateway "%s" doesn\'t support create card', $this->payment->Gateway)
            );
        }

        $gatewayData = $this->gatherGatewayData($data);

        $this->extend('onBeforeCreateCard', $gatewayData);
        $request = $this->oGateway()->createCard($gatewayData);
        $this->extend('onAfterCreateCard', $request);

        $this->createMessage(Message\CreateCardRequest::class, $request);

        try {
            $response = $this->response = $request->send();
        } catch (\Omnipay\Common\Exception\OmnipayException $e) {
            $this->createMessage(Message\CreateCardError::class, $e);
            // create an error response
            return $this->generateServiceResponse(ServiceResponse::SERVICE_ERROR);
        }

        ErrorHandling::safeExtend($this, 'onAfterSendCreateCard', $request, $response);

        $serviceResponse = $this->wrapOmnipayResponse($response);

        if ($serviceResponse->isRedirect() || $serviceResponse->isAwaitingNotification()) {
            $this->payment->Status = 'PendingCreateCard';
            $this->payment->write();

            $this->createMessage(
                $serviceResponse->isRedirect() ? Message\CreateCardRedirectResponse::class : Message\AwaitingCreateCardResponse::class,
                $response
            );
        } elseif ($serviceResponse->isError()) {
            $this->createMessage(Message\CreateCardError::class, $response);
        } else {
            $this->markCompleted('CardCreated', $serviceResponse, $response);
        }

        return $serviceResponse;
    }
561993
public function create($data, $gatewayAccountId = null)
    {
        if (isset($gatewayAccountId)) {
            return $this->client()->put($data, 'gateway-accounts/{gatewayAccountId}', ['gatewayAccountId' => $gatewayAccountId]);
        }

        return $this->client()->post($data, 'gateway-accounts');
    }
968431
public function onCharge($order)
    {
        if (!isset($this->omnipay))
            throw new ShopException('Omnipay gateway not set.', 0);

        try {

            $response = $this->omnipay->purchase(array_merge([
                'amount'    => $order->total,
                'currency'  => Config::get('shop.currency'),
                'card'      => $this->isCreditCard ? $this->creditCard : [],
                'returnUrl' => $this->callbackSuccess,
                'cancelUrl' => $this->callbackFail,
            ], $this->options))->send();

            if ($response->isSuccessful()) {

                $this->transactionId = $response->getTransactionReference();

                $this->detail = 'Success';


            } elseif ($response->isRedirect()) {

                $this->statusCode = 'pending';

                $this->approvalUrl = $response->getRedirectUrl();

                $this->detail = sprintf('Pending approval: %s', $response->getRedirectUrl());

            } else {

                throw new GatewayException($response->getMessage(), 1);

            }

            return true;

        } catch (Exception $e) {

            throw new ShopException(
                $e->getMessage(),
                1000,
                $e
            );

        }

        return false;
    }
1054099
public function getGateway($id)
    {
        if (!array_key_exists($id, $this->_gateways)) {
            throw new InvalidParamException("Unknown gateway '{$id}'.");
        }
        if (!is_object($this->_gateways[$id])) {
            $this->_gateways[$id] = $this->createGateway($id, $this->_gateways[$id]);
        }
        return $this->_gateways[$id];
    }
842266
protected function create($method)
    {
        !$this->config->has('log.file') ?: $this->registeLog();

        $gateway = __NAMESPACE__.'\\Gateways\\'.Str::studly($method);

        if (class_exists($gateway)) {
            return self::make($gateway);
        }

        throw new InvalidGatewayException("Gateway [{$method}] Not Exists");
    }
34902
public function create($params, $optParams = [])
    {
        if (!$params instanceof AccessToken) {
            throw new InvalidParamException(AccessToken::class . ' is required!');
        }
        $class = get_class($params);

        return $this->sendRequest([], [
            'restAction' => 'create',
            'postParams' => $params->toArray(),
            'getParams' => $optParams,
        ], function ($response) use ($class) {
            return isset($response->data) ? new $class($response->data) : $response;
        });
    }
502947
public function payment(Payment $payment, &$paymentParams)
    {
        if (!$this->checkCurrency($payment->currency)) {
            Yii::$app->session->setFlash(Yii::t('payment', 'The gateway does not support the current currency!'));
        } else {
            $params = $this->buildPaymentParameter([
                'out_trade_no' => $payment->id,
                'subject' => !empty($payment->model_id) ? $payment->model_id . '付款' : '账号充值',
                'total_fee' => round($payment->money, 2),
            ]);
            //签名结果与签名方式加入请求提交参数组中
            $paraFilter = $this->paraFilter($params);
            $paraSort = $this->argSort($paraFilter);
            //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
            $preStr = $this->createLinkString($paraSort);

            $params['sign'] = $this->createSign($preStr);
            $params['sign_type'] = strtoupper($this->signType);
            $this->getRedirectResponse($params);
        }
    }
926843
protected function setGateway($gateway = null)
    {
        $deferred = new Deferred();

        $buildParams = function ($gateway) use ($deferred) {
            $params = [
                'v'        => self::GATEWAY_VERSION,
                'encoding' => $this->encoding,
            ];

            $query         = http_build_query($params);
            $this->gateway = trim($gateway, '/').'/?'.$query;

            $deferred->resolve($this->gateway);
        };

        if (is_null($gateway)) {
            $this->http->get('gateway')->then(function ($response) use ($buildParams) {
                $buildParams($response->url);
            }, function ($e) use ($buildParams) {
                // Can't access the API server so we will use the default gateway.
                $buildParams('wss://gateway.discord.gg');
            });
        } else {
            $buildParams($gateway);
        }

        $deferred->promise()->then(function ($gateway) {
            $this->logger->info('gateway retrieved and set', ['gateway' => $gateway]);
        }, function ($e) {
            $this->logger->error('error obtaining gateway', ['e' => $e->getMessage()]);
        });

        return $deferred->promise();
    }
1058361
public static function getSupportedGateways($nice = true)
    {
        $allowed = Payment::config()->allowed_gateways;

        if (!is_array($allowed) || empty($allowed)) {
            throw new InvalidConfigurationException(
                'No allowed gateways configured. Use SilverStripe\Omnipay\Model\Payment.allowed_gateways config.'
            );
        }

        $allowed = array_combine($allowed, $allowed);

        if ($nice) {
            $allowed = array_map('SilverStripe\Omnipay\GatewayInfo::niceTitle', $allowed);
        }

        return $allowed;
    }
286386
public function execute(array $args, array $options = [])
    {
        if (empty($args) || strpos($args[0], '/') < 1) {
            throw new \InvalidArgumentException('please input action');
        }
        Route::setPathInfo(explode('/', trim(trim($args[0], '/\\'))));
        return 'don_not_exit';
    }