sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function radio(FieldContract $field): Htmlable { return $this->form->radio($field->get('name'), $field->get('value'), $field->get('checked')); }
Radio template. @param \Orchestra\Contracts\Html\Form\Field $field @return \Illuminate\Contracts\Support\Htmlable
entailment
public function select(FieldContract $field): Htmlable { $attributes = $this->html->decorate($field->get('attributes'), ['class' => 'form-control']); return $this->form->select( $field->get('name'), $this->asArray($field->get('options')), $field->get('value'), $attributes ); }
Select template. @param \Orchestra\Contracts\Html\Form\Field $field @return \Illuminate\Contracts\Support\Htmlable
entailment
public function register($sType, $sUserFunction, $aOptions) { if($sType != $this->getName()) { return false; } if(!is_string($sUserFunction)) { throw new \Jaxon\Exception\Error($this->trans('errors.functions.invalid-declaration')); } if(is_string($aOptions)) { $aOptions = ['include' => $aOptions]; } if(!is_array($aOptions)) { throw new \Jaxon\Exception\Error($this->trans('errors.functions.invalid-declaration')); } // Check if an alias is defined $sFunctionName = $sUserFunction; foreach($aOptions as $sName => $sValue) { if($sName == 'alias') { $sFunctionName = $sValue; break; } } $this->aFunctions[$sFunctionName] = $aOptions; jaxon()->di()->set($sFunctionName, function () use ($sFunctionName, $sUserFunction) { $xUserFunction = new \Jaxon\Request\Support\UserFunction($sUserFunction); $aOptions = $this->aFunctions[$sFunctionName]; foreach($aOptions as $sName => $sValue) { $xUserFunction->configure($sName, $sValue); } return $xUserFunction; }); return true; }
Register a user defined function @param string $sType The type of request handler being registered @param string $sUserFunction The name of the function being registered @param array|string $aOptions The associated options @return \Jaxon\Request\Request
entailment
public function getScript() { $di = jaxon()->di(); $code = ''; foreach(array_keys($this->aFunctions) as $sName) { $xFunction = $di->get($sName); $code .= $xFunction->getScript(); } return $code; }
Generate client side javascript code for the registered user functions @return string
entailment
public function canProcessRequest() { // Check the validity of the function name if(($this->sRequestedFunction) && !$this->validateFunction($this->sRequestedFunction)) { $this->sRequestedFunction = null; } return ($this->sRequestedFunction != null); }
Check if this plugin can process the incoming Jaxon request @return boolean
entailment
public function processRequest() { if(!$this->canProcessRequest()) { return false; } // Security check: make sure the requested function was registered. if(!key_exists($this->sRequestedFunction, $this->aFunctions)) { // Unable to find the requested function throw new \Jaxon\Exception\Error($this->trans('errors.functions.invalid', ['name' => $this->sRequestedFunction])); } $xFunction = jaxon()->di()->get($this->sRequestedFunction); $jaxon = jaxon(); $aArgs = $jaxon->getRequestHandler()->processArguments(); $xResponse = $xFunction->call($aArgs); if(($xResponse)) { $jaxon->getResponseManager()->append($xResponse); } return true; }
Process the incoming Jaxon request @return boolean
entailment
public function make(callable $callback = null): BuilderContract { $builder = new TableBuilder( $this->app->make('request'), $this->app->make('translator'), $this->app->make('view'), new Grid($this->app, $this->config) ); return $builder->extend($callback); }
{@inheritdoc}
entailment
public function of(string $name, callable $callback = null): BuilderContract { if (! isset($this->names[$name])) { $this->names[$name] = $this->make($callback); $this->names[$name]->name = $name; } return $this->names[$name]; }
Create a new builder instance of a named builder. @param string $name @param callable|null $callback @return \Orchestra\Contracts\Html\Builder
entailment
public function validateUploadedFile($sName, array $aUploadedFile) { $this->sErrorMessage = ''; // Verify the file extension $xDefault = $this->xConfig->getOption('upload.default.types'); $aAllowed = $this->xConfig->getOption('upload.files.' . $sName . '.types', $xDefault); if(is_array($aAllowed) && !in_array($aUploadedFile['type'], $aAllowed)) { $this->sErrorMessage = $this->xTranslator->trans('errors.upload.type', $aUploadedFile); return false; } // Verify the file extension $xDefault = $this->xConfig->getOption('upload.default.extensions'); $aAllowed = $this->xConfig->getOption('upload.files.' . $sName . '.extensions', $xDefault); if(is_array($aAllowed) && !in_array($aUploadedFile['extension'], $aAllowed)) { $this->sErrorMessage = $this->xTranslator->trans('errors.upload.extension', $aUploadedFile); return false; } // Verify the max size $xDefault = $this->xConfig->getOption('upload.default.max-size', 0); $iSize = $this->xConfig->getOption('upload.files.' . $sName . '.max-size', $xDefault); if($iSize > 0 && $aUploadedFile['size'] > $iSize) { $this->sErrorMessage = $this->xTranslator->trans('errors.upload.max-size', $aUploadedFile); return false; } // Verify the min size $xDefault = $this->xConfig->getOption('upload.default.min-size', 0); $iSize = $this->xConfig->getOption('upload.files.' . $sName . '.min-size', $xDefault); if($iSize > 0 && $aUploadedFile['size'] < $iSize) { $this->sErrorMessage = $this->xTranslator->trans('errors.upload.min-size', $aUploadedFile); return false; } return true; }
Validate an uploaded file @param string $sName The uploaded file variable name @param array $aUploadedFile The file data received in the $_FILES array @return bool True if the file data are valid, and false if not
entailment
public function hasUploadedFiles() { if(($xUploadPlugin = $this->getPluginManager()->getRequestPlugin(self::FILE_UPLOAD)) == null) { return false; } return $xUploadPlugin->canProcessRequest(); }
Check if uploaded files are available @return boolean
entailment
public function saveUploadedFiles() { try { if(($xUploadPlugin = $this->getPluginManager()->getRequestPlugin(self::FILE_UPLOAD)) == null) { throw new Exception($this->trans('errors.upload.plugin')); } elseif(!$xUploadPlugin->canProcessRequest()) { throw new Exception($this->trans('errors.upload.request')); } // Save uploaded files $sKey = $xUploadPlugin->saveUploadedFiles(); $sResponse = '{"code": "success", "upl": "' . $sKey . '"}'; $return = true; } catch(Exception $e) { $sResponse = '{"code": "error", "msg": "' . addslashes($e->getMessage()) . '"}'; $return = false; } // Send the response back to the browser echo '<script>var res = ', $sResponse, '; </script>'; if(($this->getOption('core.process.exit'))) { exit(); } return $return; }
Check uploaded files validity and move them to the user dir @return boolean
entailment
public function getUploadedFiles() { if(($xUploadPlugin = $this->getPluginManager()->getRequestPlugin(self::FILE_UPLOAD)) == null) { return []; } return $xUploadPlugin->getUploadedFiles(); }
Get the uploaded files @return array
entailment
public function setUploadFileFilter(Closure $fFileFilter) { if(($xUploadPlugin = $this->getPluginManager()->getRequestPlugin(self::FILE_UPLOAD)) == null) { return; } $xUploadPlugin->setFileFilter($fFileFilter); }
Filter uploaded file name @param Closure $fFileFilter The closure which filters filenames @return void
entailment
public function buildFieldByType(string $type, $row, Fluent $control): FieldContract { $templates = $this->templates; $data = $this->buildFluentData($type, $row, $control); $method = $data->get('method'); $data->options($this->getOptionList($row, $control)); $data->checked($control->get('checked')); $data->attributes($this->decorate($control->get('attributes'), $templates[$method] ?? [])); return $data; }
Build field by type. @param string $type @param mixed $row @param \Illuminate\Support\Fluent $control @return \Illuminate\Support\Fluent
entailment
public function buildFluentData(string $type, $row, Fluent $control): FieldContract { // set the name of the control $name = $control->get('name'); $value = $this->resolveFieldValue($name, $row, $control); $data = new Field([ 'method' => '', 'type' => '', 'options' => [], 'checked' => false, 'attributes' => [], 'name' => $name, 'value' => $value, ]); return $this->resolveFieldType($type, $data); }
Build data. @param string $type @param mixed $row @param \Illuminate\Support\Fluent $control @return \Orchestra\Contracts\Html\Form\Field
entailment
protected function getOptionList($row, Fluent $control) { // set the value of options, if it's callable run it first $options = $control->get('options'); if ($options instanceof Closure) { $options = $options($row, $control); } return $options; }
Get options from control. @param mixed $row @param \Illuminate\Support\Fluent $control @return array|\Illuminate\Contracts\Support\Arrayable
entailment
public function render(array $templates, Fluent $field): string { $method = $field->get('method'); $template = $templates[$method] ?? [$this->presenter, $method]; if (! \is_callable($template)) { throw new InvalidArgumentException("Form template for [{$method}] is not available."); } return $template($field); }
Render the field. @param array $templates @param \Illuminate\Support\Fluent $field @throws \InvalidArgumentException @return string
entailment
protected function resolveFieldType(string $value, Fluent $data): FieldContract { if (\preg_match('/^(input):([a-zA-Z]+)$/', $value, $matches)) { $value = $matches[2]; } $filterable = \in_array($value, \array_keys($this->templates)) || \method_exists($this->presenter, $value); if ((bool) $filterable) { $data->method($value); } else { $data->method('input')->type($value ?: 'text'); } return $data; }
Resolve method name and type. @param string $value @param \Illuminate\Support\Fluent $data @return \Orchestra\Contracts\Html\Form\Field
entailment
protected function resolveFieldValue(string $name, $row, Fluent $control) { // Set the value from old input, followed by row value. $value = $control->get('value'); $model = \data_get($row, $name, $this->request->old($name)); if (! \is_null($model)) { return $model; } // If the value is set from the closure, we should use it instead of // value retrieved from attached data. Should also check if it's a // closure, when this happen run it. if ($value instanceof Closure) { $value = $value($row, $control); } return $value; }
Resolve field value. @param string $name @param mixed $row @param \Illuminate\Support\Fluent $control @return mixed
entailment
public function render() { $grid = $this->grid; $data = [ 'grid' => $grid, 'format' => $grid->format, 'submit' => $this->translator->get($grid->submit), 'token' => $grid->token, 'meta' => $grid->viewData, ]; $view = $this->view->make($grid->view())->with($data); return $view->render(); }
{@inheritdoc}
entailment
public function configure($sName, $sValue) { switch($sName) { // Set the separator case 'separator': if($sValue == '_' || $sValue == '.') { $this->separator = $sValue; } break; // Set the protected methods case 'protected': if(is_array($sValue)) { $this->aProtectedMethods = array_merge($this->aProtectedMethods, $sValue); } elseif(is_string($sValue)) { $this->aProtectedMethods[] = $sValue; } break; default: break; } }
Set configuration options / call options for each method @param string $sName The name of the configuration option @param string $sValue The value of the configuration option @return void
entailment
public function getMethods() { $aMethods = []; foreach($this->reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $xMethod) { $sMethodName = $xMethod->getShortName(); // Don't take magic __call, __construct, __destruct methods if(strlen($sMethodName) > 2 && substr($sMethodName, 0, 2) == '__') { continue; } // Don't take excluded methods if(in_array($sMethodName, $this->aProtectedMethods)) { continue; } $aMethods[] = $sMethodName; } return $aMethods; }
Return a list of methods of the callable object to export to javascript @return array
entailment
public function getRegisteredObject() { if($this->registeredObject == null) { $di = jaxon()->di(); // Use the Reflection class to get the parameters of the constructor if(($constructor = $this->reflectionClass->getConstructor()) != null) { $parameters = $constructor->getParameters(); $parameterInstances = []; foreach($parameters as $parameter) { // Get the parameter instance from the DI $parameterInstances[] = $di->get($parameter->getClass()->getName()); } $this->registeredObject = $this->reflectionClass->newInstanceArgs($parameterInstances); } else { $this->registeredObject = $this->reflectionClass->newInstance(); } } return $this->registeredObject; }
Return the registered callable object @return object
entailment
public function call($sMethod, $aArgs) { if(!$this->hasMethod($sMethod)) { return; } $reflectionMethod = $this->reflectionClass->getMethod($sMethod); $registeredObject = $this->getRegisteredObject(); return $reflectionMethod->invokeArgs($registeredObject, $aArgs); }
Call the specified method of the registered callable object using the specified array of arguments @param string $sMethod The name of the method to call @param array $aArgs The arguments to pass to the method @return void
entailment
public function confirm($question, $yesScript, $noScript) { return $this->getConfirm()->confirm($question, $yesScript, $noScript); }
Get the script which makes a call only if the user answers yes to the given question @return string
entailment
public function initiate(array $config, ControlContract $control, Template $presenter): void { $control->setTemplates($config)->setPresenter($presenter); $this->control = $control; }
Load grid configuration. @param array $config @param \Orchestra\Contracts\Html\Form\Control $control @param \Orchestra\Contracts\Html\Form\Template $presenter @return void
entailment
protected function buildBasic($name, Closure $callback = null): void { if ($name instanceof Closure) { $callback = $name; $name = null; } ! empty($name) && $this->legend($name); $callback($this); }
Build basic fieldset. @param string|\Closure $name @param \Closure|null $callback @return void
entailment
public function control($type, $name, $callback = null) { list($name, $control) = $this->buildControl($name, $callback); if (\is_null($control->field)) { $control->field = $this->control->generate($type); } $this->controls[] = $control; $this->keyMap[$name] = \count($this->controls) - 1; return $control; }
Append a new control to the form. <code> // add a new control using just field name $fieldset->control('input:text', 'username'); // add a new control using a label (header title) and field name $fieldset->control('input:email', 'E-mail Address', 'email'); // add a new control by using a field name and closure $fieldset->control('input:text', 'fullname', function ($control) { $control->label = 'User Name'; // this would output a read-only output instead of form. $control->field = function ($row) { return $row->first_name.' '.$row->last_name; }; }); </code> @param string $type @param mixed $name @param mixed $callback @return \Illuminate\Support\Fluent
entailment
public function find(string $name) { if (! \array_key_exists($name, $this->keyMap)) { throw new InvalidArgumentException("Name [{$name}] is not available."); } return $this->controls[$this->keyMap[$name]]; }
Find definition that match the given id. @param string $name @throws \InvalidArgumentException @return \Illuminate\Support\Fluent
entailment
public function legend($name = null) { if (! \is_null($name)) { $this->name = $name; } return $this->name; }
Set Fieldset Legend name. <code> $fieldset->legend('User Information'); </code> @param string|null $name @return string
entailment
public function minify($sJsFile, $sMinFile) { $xJsMinifier = new JsMinifier(); $xJsMinifier->add($sJsFile); $xJsMinifier->minify($sMinFile); return is_file($sMinFile); }
Minify javascript code @param string $sJsFile The javascript file to be minified @param string $sMinFile The minified javascript file @return boolean True if the file was minified
entailment
public function hasPageNumber() { foreach($this->aParameters as $xParameter) { if($xParameter->getType() == Jaxon::PAGE_NUMBER) { return true; } } return false; }
Check if the request has a parameter of type Jaxon::PAGE_NUMBER @return boolean
entailment
public function setPageNumber($nPageNumber) { // Set the value of the Jaxon::PAGE_NUMBER parameter foreach($this->aParameters as $xParameter) { if($xParameter->getType() == Jaxon::PAGE_NUMBER) { $xParameter->setValue(intval($nPageNumber)); break; } } return $this; }
Set a value to the Jaxon::PAGE_NUMBER parameter @param integer $nPageNumber The current page number @return Request
entailment
private function setMessageArgs(array $aArgs) { array_walk($aArgs, function (&$xParameter) { $xParameter = Parameter::make($xParameter); }); $this->aMessageArgs = $aArgs; }
Create parameters for message arguments @param $aArgs The arguments @return void
entailment
public function getScript() { /* * JQuery variables sometimes depend on the context where they are used, eg. when their value depends on $(this). * When a confirmation question is added, the Jaxon calls are made in a different context, * making those variables invalid. * To avoid issues related to these context changes, the JQuery selectors values are first saved into * local variables, which are then used in Jaxon function calls. */ $sVars = ''; // Javascript code defining all the variables values. $nVarId = 1; // Position of the variables, starting from 1. // This array will avoid declaring multiple variables with the same value. // The array key is the variable value, while the array value is the variable name. $aVariables = []; // Array of local variables. foreach($this->aParameters as &$xParameter) { $sParameterStr = $xParameter->getScript(); if($xParameter instanceof \Jaxon\Response\Plugin\JQuery\Dom\Element) { if(!array_key_exists($sParameterStr, $aVariables)) { // The value is not yet defined. A new variable is created. $sVarName = "jxnVar$nVarId"; $aVariables[$sParameterStr] = $sVarName; $sVars .= "$sVarName=$xParameter;"; $nVarId++; } else { // The value is already defined. The corresponding variable is assigned. $sVarName = $aVariables[$sParameterStr]; } $xParameter = new Parameter(Jaxon::JS_VALUE, $sVarName); } } $sPhrase = ''; if(count($this->aMessageArgs) > 0) { $sPhrase = array_shift($this->aMessageArgs); // The first array entry is the question. // $sPhrase = "'" . addslashes($sPhrase) . "'"; // Wrap the phrase with single quotes if(count($this->aMessageArgs) > 0) { $nParamId = 1; foreach($this->aMessageArgs as &$xParameter) { $sParameterStr = $xParameter->getScript(); if($xParameter instanceof \Jaxon\Response\Plugin\JQuery\Dom\Element) { if(!array_key_exists($sParameterStr, $aVariables)) { // The value is not yet defined. A new variable is created. $sVarName = "jxnVar$nVarId"; $aVariables[$sParameterStr] = $sVarName; $sVars .= "$sVarName=$xParameter;"; $nVarId++; } else { // The value is already defined. The corresponding variable is assigned. $sVarName = $aVariables[$sParameterStr]; } $xParameter = new Parameter(Jaxon::JS_VALUE, $sVarName); } $xParameter = "'$nParamId':" . $xParameter->getScript(); $nParamId++; } $sPhrase .= '.supplant({' . implode(',', $this->aMessageArgs) . '})'; } } $sScript = parent::getScript(); $xDialog = jaxon()->dialog(); if($this->sCondition == '__confirm__') { $sScript = $xDialog->confirm($sPhrase, $sScript, ''); } elseif($this->sCondition !== null) { $sScript = 'if(' . $this->sCondition . '){' . $sScript . ';}'; if(($sPhrase)) { $xDialog->getAlert()->setReturn(true); $sScript .= 'else{' . $xDialog->warning($sPhrase) . ';}'; } } return $sVars . $sScript; }
Returns a string representation of the script output (javascript) from this request object @return string
entailment
public function trans($sText, array $aPlaceHolders = [], $sLanguage = null) { return Container::getInstance()->getTranslator()->trans($sText, $aPlaceHolders, $sLanguage); }
Get a translated string @param string $sText The key of the translated string @param string $aPlaceHolders The placeholders of the translated string @param string $sLanguage The language of the translated string @return string The translated string
entailment
public function getScript() { if(count($this->aCalls) == 0) { return $this->sSelector; } return $this->sSelector . '.' . implode('.', $this->aCalls); }
Generate the jQuery call. @return string
entailment
public static function create($payment, array $data = null, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } if ($payment instanceof Payment) { $payment = $payment->id; } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->post( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::REFUND_RESOURCE, null, array('PAYMENT_ID' => $payment)), $data ); return Refund::fromAttributes($response['httpResponse']); }
Creates a refund on a payment. @param string|Payment $payment the payment id or the payment object @param array $data API data for refund @param Payplug\Payplug $payplug the client configuration @return null|Refund the refund object @throws Payplug\Exception\ConfigurationNotSetException
entailment
public static function retrieve($payment, $refundId, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } if ($payment instanceof Payment) { $payment = $payment->id; } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->get( Payplug\Core\APIRoutes::getRoute( Payplug\Core\APIRoutes::REFUND_RESOURCE, $refundId, array('PAYMENT_ID' => $payment) ) ); return Refund::fromAttributes($response['httpResponse']); }
Retrieves a refund object on a payment. @param string|Payment $payment the payment id or the payment object @param string $refundId the refund id @param Payplug\Payplug $payplug the client configuration @return null|Payplug\Resource\APIResource|Refund the refund object @throws Payplug\Exception\ConfigurationNotSetException
entailment
public static function listRefunds($payment, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } if ($payment instanceof Payment) { $payment = $payment->id; } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->get( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::REFUND_RESOURCE, null, array('PAYMENT_ID' => $payment)) ); if (!array_key_exists('data', $response['httpResponse']) || !is_array($response['httpResponse']['data'])) { throw new Payplug\Exception\UnexpectedAPIResponseException( "Expected API response to contain 'data' key referencing an array.", $response['httpResponse'] ); } $refunds = array(); foreach ($response['httpResponse']['data'] as &$refund) { $refunds[] = Refund::fromAttributes($refund); } return $refunds; }
Lists the last refunds of a payment. @param string|Payment $payment the payment id or the payment object @param Payplug\Payplug $payplug the client configuration @return null|Refund[] an array containing the refunds on success. @throws Payplug\Exception\ConfigurationNotSetException @throws Payplug\Exception\UnexpectedAPIResponseException
entailment
function getConsistentResource(Payplug\Payplug $payplug = null) { if (!array_key_exists('id', $this->_attributes)) { throw new Payplug\Exception\UndefinedAttributeException('The id of the refund is not set.'); } else if (!array_key_exists('payment_id', $this->_attributes)) { throw new Payplug\Exception\UndefinedAttributeException('The payment_id of the refund is not set.'); } return Payplug\Resource\Refund::retrieve($this->_attributes['payment_id'], $this->_attributes['id'], $payplug); }
Returns an API resource that you can trust. @param Payplug\Payplug $payplug the client configuration. @return Payplug\Resource\APIResource The consistent API resource. @throws Payplug\Exception\UndefinedAttributeException when the local resource is invalid.
entailment
protected function initialize(array $attributes) { parent::initialize($attributes); if (isset($attributes['customer'])) { $this->customer = PaymentCustomer::fromAttributes($attributes['customer']); } if (isset($attributes['failure'])) { $this->failure = PaymentPaymentFailure::fromAttributes($attributes['failure']); } if (isset($attributes['hosted_payment'])) { $this->hosted_payment = PaymentHostedPayment::fromAttributes($attributes['hosted_payment']); } if (isset($attributes['notification'])) { $this->notification = PaymentNotification::fromAttributes($attributes['notification']); } $schedules = array(); if (isset($attributes['schedule'])) { foreach ($attributes['schedule'] as &$schedule) { $schedules[] = InstallmentPlanSchedule::fromAttributes($schedule); } } $this->schedule = $schedules; }
Initializes the resource. This method must be overridden when the resource has objects as attributes. @param array $attributes the attributes to initialize.
entailment
public function listPayments(Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } if (!array_key_exists('id', $this->getAttributes())) { throw new Payplug\Exception\UndefinedAttributeException( "This installment plan object has no id. You can't list payments on it."); } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->get( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::INSTALLMENT_PLAN_RESOURCE, $this->id) ); $payments = array(); foreach ($response['httpResponse']['schedule'] as $schedule) { foreach ($schedule['payment_ids'] as $payment_id) { $payments[$payment_id] = Payment::retrieve($payment_id, $payplug); } } return $payments; }
List the payments of this installment plan. @param Payplug\Payplug $payplug the client configuration @return null|Payment[] the array of payments of this installment plan @throws Payplug\Exception\UndefinedAttributeException @throws Payplug\Exception\UnexpectedAPIResponseException
entailment
public static function retrieve($installmentPlanId, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->get( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::INSTALLMENT_PLAN_RESOURCE, $installmentPlanId) ); return InstallmentPlan::fromAttributes($response['httpResponse']); }
Retrieves an InstallmentPlan. @param string $installmentPlanId the installment plan ID @param Payplug\Payplug $payplug the client configuration @return null|InstallmentPlan the retrieved installment plan or null on error @throws Payplug\Exception\ConfigurationNotSetException
entailment
public static function create(array $data, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->post( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::INSTALLMENT_PLAN_RESOURCE), $data ); return InstallmentPlan::fromAttributes($response['httpResponse']); }
Creates an InstallmentPlan. @param array $data API data for payment creation @param Payplug\Payplug $payplug the client configuration @return null|InstallmentPlan the created installment plan instance @throws Payplug\Exception\ConfigurationNotSetException
entailment
public static function treat($requestBody, $authentication = null) { $postArray = json_decode($requestBody, true); if ($postArray === null) { throw new Exception\UnknownAPIResourceException('Request body is not valid JSON.'); } $unsafeAPIResource = Resource\APIResource::factory($postArray); return $unsafeAPIResource->getConsistentResource($authentication); }
This function treats a notification and verifies its authenticity. @param string $requestBody JSON Data sent by the notifier. @param Payplug $authentication The client configuration. @return Resource\IVerifiableAPIResource A safe API Resource. @throws Exception\UnknownAPIResourceException
entailment
public static function deleteCard($card, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } if ($card instanceof Card) { $card = $card->id; } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->delete(Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::CARD_RESOURCE, $card)); return $response; }
Delete the card. @param Payplug\Card $card the card or card id @param Payplug\Payplug $payplug the client configuration @return Card the deleted card or null on error @throws Payplug\Exception\ConfigurationNotSetException
entailment
public function delete(Payplug\Payplug $payplug = null) { self::deleteCard($this->id, $payplug); }
Delete the card. @param Payplug\Payplug $payplug the client configuration @throws Payplug\Exception\ConfigurationNotSetException
entailment
public function post($resource, $data = null, $authenticated = true) { return $this->request('POST', $resource, $data, $authenticated); }
Sends a POST request to the API. @param string $resource the path to the remote resource @param array $data Request data @param bool $authenticated the request should be authenticated @return array the response in a dictionary with following keys: <pre> 'httpStatus' => The 2xx HTTP status code as defined at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2 'httpResponse' => The HTTP response </pre> @throws Payplug\Exception\UnexpectedAPIResponseException When the API response is not parsable in JSON. @throws Payplug\Exception\HttpException When status code is not 2xx. @throws Payplug\Exception\ConnectionException When an error was encountered while connecting to the resource.
entailment
public static function addDefaultUserAgentProduct($product, $version = null, $comment = null) { self::$defaultUserAgentProducts[] = array($product, $version, $comment); }
Adds a default product for the User-Agent HTTP header sent for each HTTP request. @param string $product the product's name @param string $version the product's version @param string $comment a comment about the product
entailment
private static function formatUserAgentProduct($product, $version = null, $comment = null) { $productString = $product; if ($version) { $productString .= '/' . $version; } if ($comment) { $productString .= ' (' . $comment . ')'; } return $productString; }
Formats a product for a User-Agent HTTP header. @param string $product the product name @param string $version (optional) product version @param string $comment (optional) comment about the product. @return string a formatted User-Agent string (`PRODUCT/VERSION (COMMENT)`)
entailment
public static function getUserAgent() { $curlVersion = curl_version(); // Do not move this inside $headers even if it is used only there. // PHP < 5.4 doesn't support call()['value'] directly. $userAgent = self::formatUserAgentProduct('PayPlug-PHP', Payplug\Core\Config::LIBRARY_VERSION, sprintf('PHP/%s; curl/%s', phpversion(), $curlVersion['version'])); foreach (self::$defaultUserAgentProducts as $product) { $userAgent .= ' ' . self::formatUserAgentProduct($product[0], $product[1], $product[2]); } return $userAgent; }
Gets the User-Agent HTTP header sent for each HTTP request.
entailment
private function request($httpVerb, $resource, array $data = null, $authenticated = true) { if (self::$REQUEST_HANDLER === null) { $request = new CurlRequest(); } else { $request = self::$REQUEST_HANDLER; } $userAgent = self::getUserAgent(); $headers = array( 'Accept: application/json', 'Content-Type: application/json', 'User-Agent: ' . $userAgent ); if ($authenticated) { $headers[] = 'Authorization: Bearer ' . $this->_configuration->getToken(); } $request->setopt(CURLOPT_FAILONERROR, false); $request->setopt(CURLOPT_RETURNTRANSFER, true); $request->setopt(CURLOPT_CUSTOMREQUEST, $httpVerb); $request->setopt(CURLOPT_URL, $resource); $request->setopt(CURLOPT_HTTPHEADER, $headers); $request->setopt(CURLOPT_SSL_VERIFYPEER, true); $request->setopt(CURLOPT_SSL_VERIFYHOST, 2); $request->setopt(CURLOPT_CAINFO, self::$CACERT_PATH); if (!empty($data)) { $request->setopt(CURLOPT_POSTFIELDS, json_encode($data)); } $result = array( 'httpResponse' => $request->exec(), 'httpStatus' => $request->getInfo(CURLINFO_HTTP_CODE) ); // We must do this before closing curl $errorCode = $request->errno(); $errorMessage = $request->error(); $request->close(); // We want manage errors from HTTP in standards cases $curlStatusNotManage = array( 0, // CURLE_OK 22 // CURLE_HTTP_NOT_FOUND or CURLE_HTTP_RETURNED_ERROR ); // If there was an HTTP error if (in_array($errorCode, $curlStatusNotManage) && substr($result['httpStatus'], 0, 1) !== '2') { $this->throwRequestException($result['httpResponse'], $result['httpStatus']); // Unreachable bracket marked as executable by old versions of XDebug } // If there was an error with curl elseif ($result['httpResponse'] === false || $errorCode) { $this->throwConnectionException($result['httpStatus'], $errorMessage); // Unreachable bracket marked as executable by old versions of XDebug } $result['httpResponse'] = json_decode($result['httpResponse'], true); if ($result['httpResponse'] === null) { throw new Payplug\Exception\UnexpectedAPIResponseException('API response is not valid JSON.', $result['httpResponse']); } return $result; }
Performs a request. @param string $httpVerb the HTTP verb (PUT, POST, GET, …) @param string $resource the path to the resource queried @param array $data the request content @param bool $authenticated the request should be authenticated @return array the response in a dictionary with following keys: <pre> 'httpStatus' => The 2xx HTTP status code {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2} 'httpResponse' => The HTTP response </pre> @throws Payplug\Exception\UnexpectedAPIResponseException When the API response is not parsable in JSON. @throws Payplug\Exception\HttpException When status code is not 2xx. @throws Payplug\Exception\ConnectionException When an error was encountered while connecting to the resource.
entailment
private function throwRequestException($httpResponse, $httpStatus) { $exception = null; // Error 5XX if (substr($httpStatus, 0, 1) === '5') { throw new Payplug\Exception\PayplugServerException('Unexpected server error during the request.', $httpResponse, $httpStatus ); } switch ($httpStatus) { case 400: throw new Payplug\Exception\BadRequestException('Bad request.', $httpResponse, $httpStatus); break; case 401: throw new Payplug\Exception\UnauthorizedException('Unauthorized. Please check your credentials.', $httpResponse, $httpStatus); break; case 403: throw new Payplug\Exception\ForbiddenException('Forbidden error. You are not allowed to access this resource.', $httpResponse, $httpStatus); break; case 404: throw new Payplug\Exception\NotFoundException('The resource you requested could not be found.', $httpResponse, $httpStatus); break; case 405: throw new Payplug\Exception\NotAllowedException('The requested method is not supported by this resource.', $httpResponse, $httpStatus); break; } throw new Payplug\Exception\HttpException('Unhandled HTTP error.', $httpResponse, $httpStatus); }
Throws an exception from a given HTTP response and status. @param string $httpResponse the HTTP response @param int $httpStatus the HTTP status @throws Payplug\Exception\HttpException the generated exception from the request
entailment
protected function initialize(array $attributes) { parent::initialize($attributes); if (isset($attributes['card'])) { $this->card = PaymentCard::fromAttributes($attributes['card']); } if (isset($attributes['customer'])) { $this->customer = PaymentCustomer::fromAttributes($attributes['customer']); } if (isset($attributes['hosted_payment'])) { $this->hosted_payment = PaymentHostedPayment::fromAttributes($attributes['hosted_payment']); } if (isset($attributes['failure'])) { $this->failure = PaymentPaymentFailure::fromAttributes($attributes['failure']); } if (isset($attributes['notification'])) { $this->notification = PaymentNotification::fromAttributes($attributes['notification']); } if (isset($attributes['authorization'])) { $this->authorization = PaymentAuthorization::fromAttributes($attributes['authorization']); } }
Initializes the resource. This method must be overridden when the resource has objects as attributes. @param array $attributes the attributes to initialize.
entailment
public function refund(array $data = null, Payplug\Payplug $payplug = null) { if (!array_key_exists('id', $this->getAttributes())) { throw new Payplug\Exception\InvalidPaymentException("This payment object has no id. It can't be refunded."); } return Refund::create($this->id, $data, $payplug); }
Open a refund on the payment. @param array $data the refund data @param Payplug\Payplug $payplug the client configuration @return Refund|null the opened refund instance @throws Payplug\Exception\InvalidPaymentException when the id of the payment is invalid
entailment
public function listRefunds(Payplug\Payplug $payplug = null) { if (!array_key_exists('id', $this->getAttributes())) { throw new Payplug\Exception\InvalidPaymentException("This payment object has no id. You can't list refunds on it."); } return Refund::listRefunds($this->id, $payplug); }
List the refunds of this payment. @param Payplug\Payplug $payplug the client configuration @return null|Refund[] the array of refunds of this payment @throws Payplug\Exception\InvalidPaymentException @throws Payplug\Exception\UnexpectedAPIResponseException
entailment
public function capture(Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->patch( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::PAYMENT_RESOURCE, $this->id), array('captured' => true) ); return Payment::fromAttributes($response['httpResponse']); }
Captures a Payment. @param Payplug\Payplug $payplug the client configuration @return null|Payment the captured payment or null on error @throws Payplug\Exception\ConfigurationNotSetException
entailment
public static function retrieve($paymentId, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->get( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::PAYMENT_RESOURCE, $paymentId) ); return Payment::fromAttributes($response['httpResponse']); }
Retrieves a Payment. @param string $paymentId the payment ID @param Payplug\Payplug $payplug the client configuration @return null|Payment the retrieved payment or null on error @throws Payplug\Exception\ConfigurationNotSetException
entailment
public static function listPayments($perPage = null, $page = null, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } $httpClient = new Payplug\Core\HttpClient($payplug); $pagination = array('per_page' => $perPage, 'page' => $page); $response = $httpClient->get( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::PAYMENT_RESOURCE, null, array(), $pagination) ); if (!array_key_exists('data', $response['httpResponse']) || !is_array($response['httpResponse']['data'])) { throw new Payplug\Exception\UnexpectedAPIResponseException( "Expected 'data' key in API response.", $response['httpResponse'] ); } $payments = array(); foreach ($response['httpResponse']['data'] as &$payment) { $payments[] = Payment::fromAttributes($payment); } return $payments; }
List payments. @param Payplug\Payplug $payplug the client configuration @param int $perPage the number of results per page @param int $page the page number @return null|Payment[] the array of payments @throws Payplug\Exception\InvalidPaymentException @throws Payplug\Exception\UnexpectedAPIResponseException
entailment
public static function create(array $data, Payplug\Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug\Payplug::getDefaultConfiguration(); } $httpClient = new Payplug\Core\HttpClient($payplug); $response = $httpClient->post( Payplug\Core\APIRoutes::getRoute(Payplug\Core\APIRoutes::PAYMENT_RESOURCE), $data ); return Payment::fromAttributes($response['httpResponse']); }
Creates a Payment. @param array $data API data for payment creation @param Payplug\Payplug $payplug the client configuration @return null|Payment the created payment instance @throws Payplug\Exception\ConfigurationNotSetException
entailment
function getConsistentResource(Payplug\Payplug $payplug = null) { if (!array_key_exists('id', $this->_attributes)) { throw new Payplug\Exception\UndefinedAttributeException('The id of the payment is not set.'); } return Payment::retrieve($this->_attributes['id'], $payplug); }
Returns an API resource that you can trust. @param Payplug\Payplug $payplug the client configuration. @return Payplug\Resource\APIResource The consistent API resource. @throws Payplug\Exception\UndefinedAttributeException when the local resource is invalid.
entailment
public static function getRoute($route, $resourceId = null, array $parameters = array(), array $pagination = array()) { foreach ($parameters as $parameter => $value) { $route = str_replace('{' . $parameter . '}', $value, $route); } $resourceIdUrl = $resourceId ? '/' . $resourceId : ''; $query_pagination = ''; if (!empty($pagination)) $query_pagination = '?' . http_build_query($pagination); return self::$API_BASE_URL . '/v' . self::API_VERSION . $route . $resourceIdUrl . $query_pagination; }
Get the route to a specified resource. @param string $route One of the routes defined above @param string $resourceId The resource id you want to get. If null, will point to the endpoint. @param array $parameters The parameters required by the route. @param array $pagination The pagination parameters (mainly page and per_page keys that will be appended to the query parameters of the request. @return string the full URL to the resource
entailment
public static function delete($card, Payplug $payplug = null) { return Resource\Card::deleteCard($card, $payplug); }
Delete a card. @param string|\Payplug\Resource\Card $card the card ID or object @param Payplug $payplug the client configuration @return null|Resource\Card the deleted card or null on error @throws Exception\ConfigurationNotSetException
entailment
public static function factory(array $attributes) { if (!array_key_exists('object', $attributes)) { throw new Payplug\Exception\UnknownAPIResourceException('Missing "object" property.'); } switch ($attributes['object']) { case 'payment': return Payplug\Resource\Payment::fromAttributes($attributes); case 'refund': return Payplug\Resource\Refund::fromAttributes($attributes); case 'installment_plan': return Payplug\Resource\InstallmentPlan::fromAttributes($attributes); } throw new Payplug\Exception\UnknownAPIResourceException('Unknown "object" property "' . $attributes['object'] . '".'); }
Tries to recompose an API Resource from its attributes. For example, when you got it from a notification. The API Resource must have a known 'object' property. @param array $attributes The attributes of the object. @return IVerifiableAPIResource An unsafe API Resource. @throws Payplug\Exception\UnknownAPIResourceException When the given object is unknown.
entailment
public static function retrieve($paymentId, Payplug $payplug = null) { return Resource\Payment::retrieve($paymentId, $payplug); }
Retrieves a Payment. @param string $paymentId the payment ID @param Payplug $payplug the client configuration @return null|Resource\Payment the retrieved payment or null on error @throws Exception\ConfigurationNotSetException
entailment
public static function abort($paymentId, Payplug $payplug = null) { $payment = Resource\Payment::fromAttributes(array('id' => $paymentId)); return $payment->abort($payplug); }
Aborts a Payment. @param string $paymentId the payment ID @param Payplug $payplug the client configuration @return null|Resource\Payment the aborted payment or null on error @throws Exception\ConfigurationNotSetException
entailment
public static function create(array $data, Payplug $payplug = null) { return Resource\Payment::create($data, $payplug); }
Creates a Payment. @param array $data API data for payment creation @param Payplug $payplug the client configuration @return null|Resource\Payment the created payment instance @throws Exception\ConfigurationNotSetException
entailment
public static function listPayments($perPage = null, $page = null, Payplug $payplug = null) { return Resource\Payment::listPayments($perPage, $page, $payplug); }
List payments. @param int $perPage number of results per page @param int $page the page number @param Payplug $payplug the client configuration @return null|Resource\Payment[] the array of payments @throws Exception\InvalidPaymentException @throws Exception\UnexpectedAPIResponseException
entailment
protected function createSignature($resource) { if (!$this->key) { throw new Exception('Missing api key'); } if (!$this->secret) { throw new Exception('Missing api secret'); } if (!$this->workspace) { throw new Exception('Missing workspace id'); } $data = [ 'key' => $this->key, 'workspace' => $this->workspace, 'resource' => $resource ]; ksort($data); return hash_hmac('sha256', implode('', $data), $this->secret); }
@param string $resource @return string @throws Exception
entailment
public function request($method = self::REQUEST_POST, $resource, array $params = [], array $headers = []) { $signature = $this->createSignature($resource); $method = strtoupper($method); $options = [ 'headers' => array_merge($headers, [ 'X-Auth-Key' => $this->key, 'X-Auth-Workspace' => $this->workspace, 'X-Auth-Signature' => $signature, 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json' ]) ]; /** * If POST and data is not an url then send data in body as json string */ if ($method === self::REQUEST_POST && isset($params['data']) && !self::isUrl($params['data'])) { if (is_string($params['data'])) { $params['data'] = self::stringToArray($params['data']); } if ($params['data']) { $options[\GuzzleHttp\RequestOptions::JSON] = $params['data']; unset($params['data']); } } $options[\GuzzleHttp\RequestOptions::QUERY] = $params; return $this->handleRequest($method, $resource, $options); }
@param string $method @param string $resource @param array $params @param array $headers @return \stdClass @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
protected function handleRequest($method, $resource, $options) { $response = null; try { $response = $this->handleResponse($this->getHttpClient()->request($method, $resource, $options)); } catch (RequestException $e) { $this->handleException($e); } return $response; }
@param $method @param $resource @param $options @return \stdClass|null @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
protected function handleException(RequestException $e) { $message = $e->getMessage(); $code = $e->getCode(); $response = $e->getResponse(); if ($response) { $contents = null; try { $contents = \GuzzleHttp\json_decode($response->getBody()->getContents()); } catch (\InvalidArgumentException $e) { } if ($contents && property_exists($contents, 'error')) { $message = $contents->error; $code = $contents->status; } } throw new Exception($message, $code, $e); }
@param \GuzzleHttp\Exception\RequestException $e @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
protected function handleResponse(ResponseInterface $response) { $contents = $response->getBody()->getContents(); try { return $contents ? \GuzzleHttp\json_decode($contents) : null; } catch (\InvalidArgumentException $e) { throw new Exception('Unable to decode PDF Generator API response', $e->getCode(), $e); } }
@param \Psr\Http\Message\ResponseInterface $response @return \stdClass @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
public function getAll(array $access = [], array $tags = []) { $response = $this->request(self::REQUEST_GET, 'templates', [ 'access' => implode(',', $access), 'tags' => implode(',', $tags) ]); return $response->response; }
Returns list of templates available in active workspace @param array $access @param array $tags @return array @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
public function get($template) { $response = $this->request(self::REQUEST_GET, 'templates/'.$template); return $response->response; }
Returns template configuration @param integer $template @return \stdClass @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
public function create($name) { $response = $this->request(self::REQUEST_POST, 'templates', [ 'data' =>[ 'name' => $name, 'layout' => [ 'format' => 'A4', 'unit' => 'cm', 'orientation' => 'portrait', 'rotation' => 0, 'height' => 29.7, 'width' => 21, 'margins' => ['top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0], 'repeatLayout' => null ], 'pages' => [[ 'width' => 21, 'height' => 29.7, 'border' => false, 'margins' => ['right' => 0, 'bottom' => 0], 'components' => [] ]] ] ]); return $response->response; }
Creates blank template into active workspace and returns template info @param string $name @return \stdClass @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
public function copy($template, $newName = null) { $response = $this->request(self::REQUEST_POST, 'templates/'.$template.'/copy', [ 'name' => $newName ]); return $response->response; }
Creates copy of given template to active workspace @param integer $template @param string $newName @return \stdClass @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
public function output($template, $data, $format = self::FORMAT_PDF, $name = null, array $params = []) { return $this->request(self::REQUEST_POST, 'templates/'.$template.'/output', array_merge([ 'data' => $data, 'format' => $format, 'name' => $name ], $params)); }
Returns document as base64 encoded string for given template and data @param integer $template @param string|array|\stdClass $data @param string $format @param string $name @param array $params @return \stdClass @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
public function editor($template, $data = null, array $params = []) { $resource = 'templates/'.$template.'/editor'; $params = array_merge([ 'key' => $this->key, 'workspace' => $this->workspace, 'signature' => $this->createSignature($resource) ], $params); if ($data) { $params['data'] = self::dataToString($data); } return $this->baseUrl.$resource.'?'.http_build_query($params); }
Creates editor url @param integer $template @param array|\stdClass|string $data @param array $params @return string @throws \ActualReports\PDFGeneratorAPI\Exception
entailment
protected static function stringToArray($string) { $data = null; try { $data = \GuzzleHttp\json_decode($string, true); } catch (\InvalidArgumentException $e) { } return $data; }
@param string $string @return array|null
entailment
protected static function dataToString($data) { if (!is_string($data)) { try { $data = \GuzzleHttp\json_encode($data); } catch (\InvalidArgumentException $e) { } } return $data; }
Turns data into string, @param array|string|\stdClass $data @return string
entailment
public static function retrieve($installmentPlanId, Payplug $payplug = null) { return Resource\InstallmentPlan::retrieve($installmentPlanId, $payplug); }
Retrieves an InstallmentPlan. @param string $installmentPlanId the installment plan ID @param Payplug $payplug the client configuration @return null|Resource\InstallmentPlan the retrieved installment plan or null on error @throws Exception\ConfigurationNotSetException
entailment
public static function abort($installmentPlanId, Payplug $payplug = null) { $installmentPlan = Resource\InstallmentPlan::fromAttributes(array('id' => $installmentPlanId)); return $installmentPlan->abort($payplug); }
Aborts an InstallmentPlan. @param string $installmentPlanId the installment plan ID @param Payplug $payplug the client configuration @return null|Resource\InstallmentPlan the aborted installment plan or null on error @throws Exception\ConfigurationNotSetException
entailment
public static function create(array $data, Payplug $payplug = null) { return Resource\InstallmentPlan::create($data, $payplug); }
Creates an InstallmentPlan. @param array $data API data for payment creation @param Payplug $payplug the client configuration @return null|Resource\InstallmentPlan the created payment instance @throws Exception\ConfigurationNotSetException
entailment
public static function create($payment, array $data = null, Payplug $payplug = null) { return Resource\Refund::create($payment, $data, $payplug); }
Creates a refund on a payment. @param string|Payment $payment the payment id or the payment object @param array $data API data for refund @param Payplug $payplug the client configuration @return null|Refund the refund object @throws Exception\ConfigurationNotSetException
entailment
public static function retrieve($payment, $refundId, Payplug $payplug = null) { return Resource\Refund::retrieve($payment, $refundId, $payplug); }
Retrieves a refund object on a payment. @param string|Payment $payment the payment id or the payment object @param string $refundId the refund id @param Payplug $payplug the client configuration @return null|Resource\APIResource|Refund the refund object @throws Exception\ConfigurationNotSetException
entailment
public static function listRefunds($payment, Payplug $payplug = null) { return Resource\Refund::listRefunds($payment, $payplug); }
Lists the last refunds of a payment. @param string|Payment $payment the payment id or the payment object @param Payplug $payplug the client configuration @return null|Refund[] an array containing the refunds on success. @throws Exception\ConfigurationNotSetException @throws Exception\UnexpectedAPIResponseException
entailment
public static function setSecretKey($token) { if (!is_string($token)) { throw new Exception\ConfigurationException('Expected string values for the token.'); } $clientConfiguration = new Payplug($token); self::setDefaultConfiguration($clientConfiguration); return $clientConfiguration; }
Initializes a Authentication and sets it as the new default global authentication. It also performs some checks before saving the authentication. <pre> Expected array format for argument $authentication : $authentication['TOKEN'] = 'YOUR TOKEN' </pre> @param string $token the authentication token @return Payplug the new client authentication @throws Exception\ConfigurationException
entailment
public static function getKeysByLogin($email, $password) { $httpClient = new Core\HttpClient(null); $response = $httpClient->post( Core\APIRoutes::getRoute(Core\APIRoutes::KEY_RESOURCE), array('email' => $email, 'password' => $password), false ); return $response; }
Retrieve existing API keys for an user, using his email and password. This function is for user-friendly interface purpose only. You should probably not use this more than once, login/password MUST NOT be stored and API Keys are enough to interact with API. @param string $email the user email @param string $password the user password @return null|array the API keys @throws Exception\BadRequestException
entailment
public static function getAccount(Payplug $payplug = null) { if ($payplug === null) { $payplug = Payplug::getDefaultConfiguration(); } $httpClient = new Core\HttpClient($payplug); $response = $httpClient->get(Core\APIRoutes::getRoute(Core\APIRoutes::ACCOUNT_RESOURCE)); return $response; }
Retrieve account info. @param Payplug $payplug the client configuration @return null|array the account settings @throws Exception\ConfigurationNotSetException
entailment
public static function getPermissionsByLogin($email, $password) { $keys = self::getKeysByLogin($email, $password); $payplug = Payplug::setSecretKey($keys['httpResponse']['secret_keys']['live']); $httpClient = new Core\HttpClient($payplug); $response = $httpClient->get(Core\APIRoutes::getRoute(Core\APIRoutes::ACCOUNT_RESOURCE)); return $response['httpResponse']['permissions']; }
Retrieve the account permissions, using email and password. This function is for user-friendly interface purpose only. You should probably not use this more than once, login/password MUST NOT be stored and API Keys are enough to interact with API. @param string $email the user email @param string $password the user password @return null|array the account permissions @throws Exception\ConfigurationNotSetException
entailment
function paymentInit(Payment $payment, $extensions = array()) { $payment->checkAndPrepare($this->config); $array = $payment->signAndExport($this); $this->writeToLog("payment/init started for payment with orderNo " . $payment->orderNo); try { $ret = $this->sendRequest( "payment/init", $array, "POST", array("payId", "dttm", "resultCode", "resultMessage", "?paymentStatus", "?authCode"), null, false, false, $extensions ); } catch (Exception $e) { $this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage()); throw $e; } if (!isset($ret["payId"]) or !$ret["payId"]) { $this->writeToLog("Fail, no payId received."); throw new Exception("Bank API did not return a payId value."); } $payment->setPayId($ret["payId"]); $this->writeToLog("payment/init OK, got payId ".$ret["payId"]); return $ret; }
Performs payment/init API call. Use this to create new payment in payment gateway. After successful call, the $payment object will be updated by given PayID. @param Payment $payment Create and fill this object manually with real data. @param Extension[]|Extension $extensions Added extensions @return array Array with results of the call. You don't need to use any of this, PayID will be set to $payment automatically.
entailment
function getPaymentProcessUrl($payment) { $payId = $this->getPayId($payment); $payload = array( "merchantId" => $this->config->merchantId, "payId" => $payId, "dttm" => $this->getDTTM() ); $payload["signature"] = $this->signRequest($payload); $url = $this->sendRequest( "payment/process", $payload, "GET", array(), array("merchantId", "payId", "dttm", "signature"), true ); $this->writeToLog("URL for processing payment ".$payId.": $url"); return $url; }
Generates URL to send customer's browser to after initiating the payment. Use this after you successfully called paymentInit() and redirect the customer's browser on the URL that this method returns manually, or use redirectToGateway(). @param string|Payment $payment Either PayID given during paymentInit(), or just the Payment object you used in paymentInit() @return string @see redirectToGateway()
entailment
function getPaymentCheckoutUrl($payment, $oneClickPaymentCheckbox, $displayOmnibox = null, $returnCheckoutUrl = null) { $payId = $this->getPayId($payment); $payload = array( "merchantId" => $this->config->merchantId, "payId" => $payId, "dttm" => $this->getDTTM(), "oneclickPaymentCheckbox" => $oneClickPaymentCheckbox, ); if ($displayOmnibox !== null) { $payload["displayOmnibox"] = $displayOmnibox ? "true" : "false"; } if ($returnCheckoutUrl !== null) { $payload["returnCheckoutUrl"] = $returnCheckoutUrl; } $payload["signature"] = $this->signRequest($payload); $url = $this->sendRequest( "payment/checkout", $payload, "GET", array(), array("merchantId", "payId", "dttm", "oneclickPaymentCheckbox", "displayOmnibox", "returnCheckoutUrl", "signature"), true ); $this->writeToLog("URL for processing payment ".$payId.": $url"); return $url; }
Generates checkout URL to send customer's browser to after initiating the payment. @param string|Payment $payment Either PayID given during paymentInit(), or just the Payment object you used in paymentInit() @param int $oneClickPaymentCheckbox Flag to indicate whether to display the checkbox for saving card for future payments and to indicate whether it should be preselected or not. 0 - hidden, unchecked 1 - displayed, unchecked 2 - displayed, checked 3 - hidden, checked (you need to indicate to customer that this happens before initiating the payment) @param bool|null $displayOmnibox Flag to indicate whether to display omnibox in desktop's iframe version instead of card number, expiration and cvc fields @param string|null $returnCheckoutUrl URL for scenario when process needs to get back to checkout page @return string
entailment
function redirectToGateway($payment) { if (headers_sent($file, $line)) { $this->writeToLog("Can't redirect, headers sent at $file, line $line"); throw new Exception("Can't redirect the browser, headers were already sent at $file line $line"); } $url = $this->getPaymentProcessUrl($payment); $this->writeToLog("Redirecting to payment gate..."); header("HTTP/1.1 302 Moved"); header("Location: $url"); header("Connection: close"); }
Redirect customer's browser to payment gateway. Use this after you successfully called paymentInit() Note that HTTP headers must not have been sent before. @param string|Payment $payment Either PayID given during paymentInit(), or just the Payment object you used in paymentInit() @throws Exception If headers has been already sent
entailment
function paymentStatus($payment, $returnStatusOnly = true, $extensions = array()) { $payId = $this->getPayId($payment); $this->writeToLog("payment/status started for payment $payId"); $payload = array( "merchantId" => $this->config->merchantId, "payId" => $payId, "dttm" => $this->getDTTM() ); try { $payload["signature"] = $this->signRequest($payload); $ret = $this->sendRequest( "payment/status", $payload, "GET", array("payId", "dttm", "resultCode", "resultMessage", "paymentStatus", "?authCode"), array("merchantId", "payId", "dttm", "signature"), false, false, $extensions ); } catch (Exception $e) { $this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage()); throw $e; } $this->writeToLog("payment/status OK, status of payment $payId is ".$ret["paymentStatus"]); if ($returnStatusOnly) { return $ret["paymentStatus"]; } return $ret; }
Check payment status by calling payment/status API method. Use this to check current status of some transaction. See ČSOB's wiki on Github for explanation of each status. Basically, they are: - 1 = new; after paymentInit() but before customer starts filling in his card number and authorising the transaction - 2 = in progress; during customer's stay at payment gateway - 4 = after successful authorisation but before it is approved by you by calling paymentClose. This state is skipped if you use Payment->closePayment = true or Config->closePayment = true. - 7 = waiting for being processed by bank. The payment will remain in this state for about one working day. You can call paymentReverse() during this time to stop it from being processed. - 5 = cancelled by you. Payment gets here after calling paymentReverse(). - 8 = finished. This means money is already probably on your account. If you want to cancel the payment, you can only refund it by calling paymentRefund(). - 9 = being refunded - 10 = refunded - 6 or 3 = payment was not authorised or was cancelled by customer @param string|Payment $payment Either PayID given during paymentInit(), or just the Payment object you used in paymentInit() @param bool $returnStatusOnly Leave on true if you want to return only status code. Set to false if you want more information as array. @param Extension[]|Extension $extensions @return array|number Number if $returnStatusOnly was true, array otherwise.
entailment
function paymentReverse($payment, $ignoreWrongPaymentStatusError = false, $extensions = array()) { $payId = $this->getPayId($payment); $payload = array( "merchantId" => $this->config->merchantId, "payId" => $payId, "dttm" => $this->getDTTM() ); $this->writeToLog("payment/reverse started for payment $payId"); try { $payload["signature"] = $this->signRequest($payload); try { $ret = $this->sendRequest( "payment/reverse", $payload, "PUT", array("payId", "dttm", "resultCode", "resultMessage", "paymentStatus", "?authCode"), array("merchantId", "payId", "dttm", "signature"), false, false, $extensions ); } catch (Exception $e) { if ($e->getCode() != 150) { // Not just invalid state throw $e; } if (!$ignoreWrongPaymentStatusError) { throw $e; } $this->writeToLog("payment/reverse failed, payment is not in correct status"); return null; } } catch (Exception $e) { $this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage()); throw $e; } $this->writeToLog("payment/reverse OK"); return $ret; }
Performs payment/reverse API call. Reversing payment means stopping payment that has not yet been processed by bank (usually about 1 working day after being created). Normally, payment must be in state 4 or 7 to be reversable. If the payment is not in an acceptable state, then the gateway returns an error code 150 and exception is thrown from here. Set $ignoreWrongPaymentStatusError to true if you are okay with that situation and you want to silently ignore it. Method then returns null. If some other type of error occurs, exception will be thrown anyway. @param string|array|Payment $payment Either PayID given during paymentInit(), or whole returned array from paymentInit or just the Payment object you used in paymentInit() @param bool $ignoreWrongPaymentStatusError @param Extension[]|Extension $extensions @return array|null Array with results of call or null if payment is not in correct state @throws Exception
entailment
function paymentRecurrent($origPayment, Payment $newPayment) { trigger_error('paymentRecurrent() is deprecated now, please use paymentOneClick() instead.', E_USER_DEPRECATED); $origPayId = $this->getPayId($origPayment); $newOrderNo = $newPayment->orderNo; if (!$newOrderNo or !preg_match('~^\d{1,10}$~', $newOrderNo)) { throw new Exception("Given Payment object must have an \$orderNo property, numeric, max. 10 chars length."); } $newPaymentCart = $newPayment->getCart(); if ($newPaymentCart) { $totalAmount = array_sum(Arrays::transform($newPaymentCart, true, "amount")); } else { $totalAmount = 0; } $newDescription = Strings::shorten($newPayment->description, 240, "..."); $payload = array( "merchantId" => $this->config->merchantId, "origPayId" => $origPayId, "orderNo" => $newOrderNo, "dttm" => $this->getDTTM(), ); if ($totalAmount > 0) { $payload["totalAmount"] = $totalAmount; $payload["currency"] = $newPayment->currency ?: "CZK"; // Currency is mandatory since 2016-01-10 } if ($newDescription) { $payload["description"] = $newDescription; } $this->writeToLog("payment/recurrent started using orig payment $origPayId"); try { $payload["signature"] = $this->signRequest($payload); $ret = $this->sendRequest( "payment/recurrent", $payload, "POST", array("payId", "dttm", "resultCode", "resultMessage", "paymentStatus", "?authCode"), array("merchantId", "origPayId", "orderNo", "dttm", "totalAmount", "currency", "description", "signature") ); } catch (Exception $e) { $this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage()); throw $e; } $this->writeToLog("payment/recurrent OK, new payment got payId " . $ret["payId"]); $newPayment->setPayId($ret["payId"]); return $ret; }
Performs payment/recurrent API call. Use this method to redo a payment that has already been marked as a template for recurring payments and approved by customer - see Payment::setRecurrentPayment() You need PayID of the original payment and a new Payment object. Only $orderNo, $totalAmount (sum of cart items added by addToCart), $currency and $description of $newPayment are used, others are ignored. Note that if $totalAmount is set, then also $currency must be set. If not, CZK is used as default value. $orderNo is the only mandatory value in $newPayment. Other properties can be left null to use original values from $origPayment. After successful call, received PayID will be set in $newPayment object. @param Payment|string $origPayment Either string PayID or a Payment object @param Payment $newPayment @return array Data with new values @throws Exception @deprecated Deprecated since eAPI 1.7, please use paymentOneClick() instead. @see Payment::setRecurrentPayment() @see paymentOneClickInit()
entailment
function paymentOneClickStart(Payment $newPayment, $extensions = array()) { $newPayId = $newPayment->getPayId(); if (!$newPayId) { throw new Exception('Given Payment object does not have a PayId. Please provide a Payment object that was returned from paymentOneClickInit() method.'); } $payload = array( "merchantId" => $this->config->merchantId, "payId" => $newPayId, "dttm" => $this->getDTTM(), ); $this->writeToLog("payment/oneclick/start started with PayId $newPayId"); try { $payload["signature"] = $this->signRequest($payload); $ret = $this->sendRequest( "payment/oneclick/start", $payload, "POST", array("payId", "dttm", "resultCode", "resultMessage", "?paymentStatus"), array("merchantId", "payId", "dttm", "signature"), false, false, $extensions ); } catch (Exception $e) { $this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage()); throw $e; } $this->writeToLog("payment/oneclick/start OK"); return $ret; }
Performs a payment/oneclick/start API call. Use this method to confirm a recurring one click payment that was previously initiated using paymentOneClickInit() method. @param Payment $newPayment @param Extension[]|Extension $extensions @return array|string
entailment