Gå til indhold
ShopentlyLearn

Rabatter · Opret

Rabatter · Opret. Alle koder skal tillade kombinationer. Rabatterne beregnes i rækkefølge.

POST/api/v1/discounts/coupons

Godkendelse
Bearer
Tilgængelig fra
STANDARD
Nødvendige rettigheder
discounts.coupons:create

Kodeeksempler

Eksempel på forespørgsel

cURL

: "${SHOPENTLY_SHOP_URL:?}"

curl --disable --globoff --fail-with-body --silent --show-error \
  --proto '=https' --connect-timeout 5 --max-time 30 \
  --request POST \
  --header "Authorization: Bearer ${SHOPENTLY_ACCESS_TOKEN:?}" \
  --header 'Idempotency-Key: learn-create_campaign_api_v1_discounts_coupons_post' \
  --header 'Content-Type: application/json' \
  --data-raw '{
  "code": "LEARN10",
  "markets": [
    {
      "currency": "PLN",
      "market_id": "poland",
      "minor_units": 2
    }
  ],
  "name": "Autumn guide offer"
}' \
  --url "${SHOPENTLY_SHOP_URL%/}"/api/v1/discounts/coupons

PHP

<?php
declare(strict_types=1);

$baseUrl = rtrim(getenv('SHOPENTLY_SHOP_URL') ?: '', '/');
$origin = parse_url($baseUrl);
if (!$origin || ($origin['scheme'] ?? '') !== 'https' || empty($origin['host']) ||
    isset($origin['user'], $origin['pass']) || isset($origin['user']) || isset($origin['path']) ||
    isset($origin['query']) || isset($origin['fragment'])) {
    throw new RuntimeException('SHOPENTLY_SHOP_URL must be an HTTPS origin');
}
$credential = getenv('SHOPENTLY_ACCESS_TOKEN') ?: '';
if ($credential === '' || strpbrk($credential, "\r\n") !== false) {
    throw new RuntimeException('Invalid credential');
}
$headers = ['Idempotency-Key: learn-create_campaign_api_v1_discounts_coupons_post', 'Content-Type: application/json'];
$headers[] = 'Authorization: Bearer ' . $credential;
$responseHeaders = [];
$handle = curl_init($baseUrl . '/api/v1/discounts/coupons');
curl_setopt_array($handle, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$responseHeaders): int {
        if (str_contains($line, ':')) {
            [$name, $value] = explode(':', $line, 2);
            $responseHeaders[strtolower(trim($name))] = trim($value);
        }
        return strlen($line);
    },
]);
curl_setopt($handle, CURLOPT_POSTFIELDS, '{
  "code": "LEARN10",
  "markets": [
    {
      "currency": "PLN",
      "market_id": "poland",
      "minor_units": 2
    }
  ],
  "name": "Autumn guide offer"
}');
$raw = curl_exec($handle);
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
$error = curl_error($handle);
curl_close($handle);
if ($raw === false) {
    throw new RuntimeException('Transport error: ' . $error);
}
if ($status < 200 || $status >= 300) {
    throw new RuntimeException('HTTP ' . $status . '; request_id=' .
        ($responseHeaders['x-request-id'] ?? '') . '; retry_after=' . ($responseHeaders['retry-after'] ?? ''));
}
$result = $raw === '' ? null : json_decode($raw, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), PHP_EOL;

Python

from contextlib import ExitStack
import json
import os
from urllib.parse import urlsplit

import requests  # python -m pip install requests

base_url = os.environ["SHOPENTLY_SHOP_URL"].rstrip("/")
origin = urlsplit(base_url)
if origin.scheme != "https" or not origin.hostname or origin.username or origin.password or origin.path or origin.query or origin.fragment:
    raise ValueError("SHOPENTLY_SHOP_URL must be an HTTPS origin")
credential = os.environ['SHOPENTLY_ACCESS_TOKEN']
if not credential or "\r" in credential or "\n" in credential:
    raise ValueError("Invalid credential")
headers = {'Idempotency-Key': 'learn-create_campaign_api_v1_discounts_coupons_post'}
headers["Authorization"] = 'Bearer' + " " + credential
body = '{\n  "code": "LEARN10",\n  "markets": [\n    {\n      "currency": "PLN",\n      "market_id": "poland",\n      "minor_units": 2\n    }\n  ],\n  "name": "Autumn guide offer"\n}'
if body is not None:
    headers["Content-Type"] = "application/json"

with ExitStack() as stack:
    session = stack.enter_context(requests.Session())
    files = None
    if False:
        image = stack.enter_context(open(os.environ["SHOPENTLY_IMAGE_FILE"], "rb"))
        if os.fstat(image.fileno()).st_size > 5242880:
            raise ValueError("Image exceeds 5 MiB")
        files = {"file": ("article.png", image, "image/png")}
    response = session.request(
        'POST', base_url + '/api/v1/discounts/coupons', headers=headers,
        data=body.encode("utf-8") if body is not None else None, files=files,
        timeout=(5, 30), allow_redirects=False,
    )
    if not 200 <= response.status_code < 300:
        raise RuntimeError(f"HTTP {response.status_code}; request_id={response.headers.get('X-Request-ID', '')}; retry_after={response.headers.get('Retry-After', '')}")
    if False:
        if response.headers.get("Content-Type") != "image/webp" or len(response.content) > 5242880:
            raise ValueError("Unexpected image response")
        with open(os.environ["SHOPENTLY_OUTPUT_FILE"], "xb") as output:
            output.write(response.content)
    else:
        result = response.json() if response.content else None
        print(json.dumps(result, ensure_ascii=False, indent=2))

Eksempel på svar 201

JSON
{
  "data": {
    "deleted": false,
    "id": "example-campaign",
    "version": null
  },
  "meta": {
    "locale": "example",
    "market_code": "example",
    "market_id": "poland",
    "pagination": {
      "has_more": false,
      "limit": 1,
      "next_cursor": null
    },
    "request_id": "learn-example-request"
  }
}

Oversigt

Valgte produkter og kategorier kombineres. Kategorier omfatter direkte tilknyttede produkter.

Parametre

Anmodningsheadere

Idempotency-KeyStrengObligatorisk

Unik identifikator for én logisk skriveoperation.

minLength: 1maxLength: 128
Begrænsninger
pattern
"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
Eksempel: "learn-create_campaign_api_v1_discounts_coupons_post"

Forespørgselsindhold

application/json · Obligatorisk

CampaignCreate
audienceStrengValgfrit

Kunder

Begrænsninger
enum
["all", "guest", "customer", "selected"]
Standard: "all"
benefit_typeStrengValgfrit

Variant af datastrukturen beskrevet ved de tilladte værdier.

Begrænsninger
enum
["percentage", "fixed", "none"]
Standard: "percentage"
category_idsArray <Streng> Valgfrit

Identifikatorer for tilknyttede kategorier.

maxItems: 1000
Begrænsninger · Array 1
pattern
"^[a-z0-9][a-z0-9_-]{0,62}$"
codeStreng nullValgfrit

Stabil maskinlæsbar kode.

Begrænsninger · Streng 1
pattern
"^[A-Za-z0-9]{6,16}$"
Eksempel: "LEARN10"
combine_couponsBoolesk værdiValgfrit

Kombinér med andre koder

Standard: false
combine_promotionsBoolesk værdiValgfrit

Tillad denne kode på produkter med automatiske kampagner

Standard: false
customer_idsArray <Streng> Valgfrit

Kundeoplysninger registreret for denne ressource.

maxItems: 1000
Begrænsninger · Array 1
pattern
"^[a-z0-9][a-z0-9_-]{0,62}$"
ends_atStreng nullValgfrit

Aktiv indtil

Streng:format: "date-time"
free_shippingBoolesk værdiValgfrit

Gratis fragt

Standard: false
marketsArray <MarketData-Input > Obligatorisk

Markeder tilgængelige i butikkens kontekst.

minItems: 1maxItems: 1000
Eksempel: [{"currency":"PLN","market_id":"poland","minor_units":2}]
minimum_quantityHeltalValgfrit

Mindste antal varer i kurven

minimum: 1maximum: 2147483647
Standard: 1
nameStrengObligatorisk

Ressourcens navn i den relevante kontekst.

minLength: 1maxLength: 160
Eksempel: "Autumn guide offer"
per_customer_limitHeltalValgfrit

Grænse for anvendelser pr. kunde

minimum: -1maximum: 2147483647
Standard: -1
percentageStrengValgfrit

Procent

maxLength: 19
Begrænsninger
pattern
"^(0|[1-9][0-9]{0,13})(\\.[0-9]{1,4})?$"
Standard: "10"
product_idsArray <Streng> Valgfrit

Identifikatorer for tilknyttede produkter.

maxItems: 1000
Begrænsninger · Array 1
pattern
"^[a-z0-9][a-z0-9_-]{0,62}$"
product_scopeStrengValgfrit

Produkter

Begrænsninger
enum
["all", "selected"]
Standard: "all"
show_accountBoolesk værdiValgfrit

På kundekontoen

Standard: false
show_cartBoolesk værdiValgfrit

I kurven

Standard: false
show_productBoolesk værdiValgfrit

På produktsider

Standard: false
starts_atStreng nullValgfrit

Aktiv fra

Streng:format: "date-time"
usage_limitHeltalValgfrit

Grænse for anvendelser

minimum: -1maximum: 2147483647
Standard: -1

Svar

Svar 201

dataMutationData Obligatorisk

Indholdet af et vellykket svar.

Felter · data
deletedBoolesk værdiObligatorisk

Om sletningen blev udført.

idStrengObligatorisk

Ressourceidentifikator; bevar den som returneret.

versionHeltal nullObligatorisk

Ressourceversion anvendt til samtidighedskontrol.

metaContextPageMeta ContextMeta PageMeta RequestMeta Obligatorisk

Svarmetadata.

Felter · meta

ContextPageMeta

localeStrengObligatorisk

Sprog valgt til denne forespørgsel.

market_codeStrengObligatorisk

Markedskode returneret af kontekstendepunktet.

market_idStrengObligatorisk

Markedsidentifikator returneret af kontekstendepunktet.

paginationPagination Obligatorisk

Metadata for markørbaseret sideinddeling.

request_idStrengObligatorisk

Sagsidentifikator; i svarmetadata identificerer den HTTP-forespørgslen.

minLength: 1maxLength: 100

ContextMeta

localeStrengObligatorisk

Sprog valgt til denne forespørgsel.

market_codeStrengObligatorisk

Markedskode returneret af kontekstendepunktet.

market_idStrengObligatorisk

Markedsidentifikator returneret af kontekstendepunktet.

request_idStrengObligatorisk

Sagsidentifikator; i svarmetadata identificerer den HTTP-forespørgslen.

minLength: 1maxLength: 100

PageMeta

paginationPagination Obligatorisk

Metadata for markørbaseret sideinddeling.

request_idStrengObligatorisk

Sagsidentifikator; i svarmetadata identificerer den HTTP-forespørgslen.

minLength: 1maxLength: 100

RequestMeta

request_idStrengObligatorisk

Sagsidentifikator; i svarmetadata identificerer den HTTP-forespørgslen.

minLength: 1maxLength: 100
Eksempel på svar

HTTP-status

201
Ressource oprettet Skema
400
Ugyldig anmodning
401
Godkendelse påkrævet
403
Adgang nægtet
404
Ressource ikke fundet
409
Versionskonflikt
422
Validering mislykkedes
429
Grænsen for anmodninger er overskredet
Andre HTTP-statusser (7)
405
Metoden er ikke tilladt
413
Anmodningen er for stor
415
Formatet understøttes ikke
500
Serverfejl
502
Fejl i API-gateway
503
Tjenesten er utilgængelig
504
Tidsgrænsen er overskredet

Fejlkatalog: ErrorResponse

Headere

201

LocationStrengValgfrit

Relativ URL til den oprettede ressource.

401

WWW-AuthenticateStrengValgfrit

Godkendelsesmetode, som serveren kræver.

405

AllowStrengValgfrit

HTTP-metoder, som denne ressource understøtter.

429, 503

Retry-AfterHeltalValgfrit

Mindste ventetid før næste forsøg, i sekunder.

minimum: 0