EasyWebshop API

A Interface de Programação de Aplicações (API) conecta sua loja virtual a plataformas externas como provedores de pagamento, serviços de entrega e aplicativos de escritório. Investimos um enorme esforço para tornar a API fácil de usar, mesmo para pessoas sem conhecimentos técnicos avançados. Isso permitirá, em alguns casos, que nossos usuários conectem sua loja virtual por conta própria, em vez de dependerem de um desenvolvedor caro.

Image of developers

Graças à compatibilidade com práticas gerais e padrões da indústria, as conexões com nossa API podem ser feitas rapidamente e possivelmente com a ajuda de código gerado por IA. Leia esta página atentamente se deseja criar uma conexão por conta própria.

Visão geral das funcionalidades

  • Conectar-se a provedores de serviços de pagamento
  • Conectar-se a serviços de entrega
  • Conectar-se a software de PDV, local e na nuvem
  • Importar produtos de fornecedores ou atacadistas
  • Exportar produtos para sites de comparação
  • Conectar software de faturamento
  • Conectar software de CRM
  • Conectar software de gestão logística
  • Atualizar estoque em tempo real
  • Aceitar ou recusar clientes com base em determinados critérios
  • Exportar pedidos em tempo real para dropshipping
  • Exportar clientes para aplicações de newsletter
  • Exportar dados para relatórios e análises
  • Criar conexões que instalam widgets HTML/JavaScript/CSS com um simples clique
  • Criar relatórios personalizados para inventário, pedidos, clientes e vendas

API, API Push e Conexões

APIAPI PushConexões
Para importar e exportar categorias, produtos, pedidos e clientes.Para sincronizar estoque ou aceitar clientes em tempo real.Para conectar provedores de pagamento, serviços de entrega, sites de comparação, pontos de venda, aplicações de faturamento e instalação de widgets.
Autenticação com token Bearer.Inserir URL Push no módulo API.Autenticação com token Bearer (conexão) e instalação da conexão (utilizador).
Personalizado para um utilizador.Personalizado para um utilizador.Pode ser instalado por todos os utilizadores.


API

Ative a EasyWebshop API em Configurações > Módulos > Easywebshop API utilizando o código de ativação MODA.
Se EasyWebshop API não for exibido no menu, navegue até Configurações > Mais opções > Nível de experiência do utilizador e altere o nível de experiência do utilizador para Especialista.

API Module

Ative a API apenas se for utilizá-la. Por razões de segurança, desative a API quando não estiver em uso.

Endpoint da APICopiar
https://easywebshop.com/apiUtilize sempre a versão https! A autenticação através de http em texto simples pode causar o vazamento do seu Token API.
Não inclua o subdomínio www.
?format=xml
Altere o formato de saída de JSON para XML.
?pretty=1
Saída formatada para melhor legibilidade humana. Remova isto para economizar largura de banda em sistemas automatizados.

Ao utilizar múltiplos parâmetros, separe-os com & (e comercial). Por exemplo: ?format=xml&pretty=1.
Na linha de comando, escape os e comerciais desta forma: ?format=xml\&pretty=1.

Utilize a nossa API com cuidado e apenas consulte ou atualize o que for necessário. Não utilize polling se a funcionalidade API Push puder ser utilizada. Limites são impostos para evitar o desperdício de recursos do servidor.

Autenticação

Clique no botão Adicionar para criar um Token API e selecione as permissões desejadas para este token.

API Permissions

Para maior segurança, selecione apenas as permissões estritamente necessárias. Revogue as permissões quando não forem mais necessárias.

Após salvar, copie o seu Token API para utilização na sua aplicação ou para enviá-lo a um desenvolvedor. Só poderá fazer isto uma vez: se perder o seu Token API, terá de eliminá-lo e criar um novo.

API Token

Utilize seu Token de API com cuidado.
Não envie seu Token de API por meio de canais de comunicação inseguros, como e-mail ou WhatsApp. Recomendamos o SimpleX Chat se precisar enviar seu Token de API para um desenvolvedor. Não armazene seu Token de API em um dispositivo inseguro. Não armazenamos seu Token de API, apenas um hash dele.

  • Solicitação
  • Resposta
  • curl
  • PHP
GET /api/status HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "status": "success", "message": "API online" } Recupera o estado da API curl -D - https://easywebshop.com/api/status Guarda a resposta num ficheiro JSON curl https://easywebshop.com/api/status -o status.json -D, --dump-header -o, --output <file> curl man page: https://curl.se/docs/manpage.html <?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/status';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Optional: If you are sending data (e.g., for a POST request)
// Uncomment the following lines to send a JSON payload
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
*/

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;
}

// Close the cURL session
curl_close($ch);
?>

Copiar

Nesta documentação, fornecemos exemplos para curl e PHP. A IA moderna está cada vez melhor a converter código para outras linguagens de programação como C, Java ou Python.

Categorias

Visualização de categorias

GET /api/category
Recupera todas as categorias
GET /api/category/[categoryName]
Recupera todos os produtos dentro de uma categoria específica
Use o nome da categoria no idioma padrão da loja virtual
GET /api/category HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "categorylist": [ { "category": { "name:lang=en": "Cocktails", "name:lang=fr": "Cocktails", "name:lang=nl": "Cocktails", "visible": "1", "image": "https:\/\/ew.ms\/shops\/fashion\/category\/cocktails.jpg", "url": "https:\/\/all4you.be\/cocktails", "categorylist": [ { "category": { "name:lang=en": "Non-alcoholic", "name:lang=fr": "Sans alcool", "name:lang=nl": "Alcoholvrij", "visible": "1", "url": "https:\/\/all4you.be\/non-alcoholic" } } ] } } ] } Recupera todas as categorias curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/category Recupera todos os produtos dentro de uma categoria específica curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/category/Cocktails Recupera todas as categorias em formato JSON legível por humanos curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/category?pretty=1 Recupera todas as categorias em formato XML legível por humanos curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/category?format=xml\&pretty=1<?php
header
("Content-Type: text/plain");

// API endpoint
// You can add a category name behind the slash for searching products within that category
const API_URL 'https://easywebshop.com/api/category/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Optional: If you are sending data (e.g., for a POST request)
// Uncomment the following lines to send a JSON payload
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
*/

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "categorylist": [ { "category": { "name:lang=en": "Cocktails", "name:lang=fr": "Cocktails", "name:lang=nl": "Cocktails", "visible": "1", "image": "https:\/\/ew.ms\/shops\/fashion\/category\/cocktails.jpg", "url": "https:\/\/all4you.be\/cocktails", "categorylist": [ { "category": { "name:lang=en": "Non-alcoholic", "name:lang=fr": "Sans alcool", "name:lang=nl": "Alcoholvrij", "visible": "1", "url": "https:\/\/all4you.be\/non-alcoholic" } } ] } } ] } <?xml version="1.0" encoding="UTF-8" ?> <categorylist> <category> <name lang="en">Cocktails</name> <name lang="fr">Cocktails</name> <name lang="nl">Cocktails</name> <visible>1</visible> <image>https://ew.ms/shops/fashion/category/cocktails.jpg</image> <url>https://all4you.be/cocktails</url> <categorylist> <category> <name lang="en">Non-alcoholic</name> <name lang="fr">Sans alcool</name> <name lang="nl">Alcoholvrij</name> <visible>1</visible> <url>https://all4you.be/non-alcoholic</url> </category> </categorylist> </category> </categorylist>

Copiar

As categorias podem ser apenas visualizadas. Não há implementação de API para criar, editar e excluir categorias, pois esses recursos são raramente utilizados e criariam superfície adicional para ataques. O gerenciamento de categorias pode ser feito utilizando a interface web.

Produtos

Visualização de produtos

EasyWebshop segue o formato schema.org/Product sempre que possível.

GET /api/product
Recupera os últimos 1000 produtos
GET /api/product?offset=1000
Recupera os últimos 1000 produtos, mas ignora os primeiros 1000 produtos
GET /api/product/86400
Recupera produtos que foram adicionados ou modificados nas últimas 24h
GET /api/product/[productID]
Pesquisa um produto por productID, sensível a maiúsculas e minúsculas
GET /api/product HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "productlist": [ { "product": { "productID": "LA-B03", "category": "Ambiance", "price": 49.99, "stock": 0, "weight": 5, "status": "Available", "vat_code": 0, "old_price": "75", "colors": "Blue,Red,Violet", "promotion": 1 } }, { "product": { "productID": "LA-C05", "category": "Ambiance", "name:lang=en": "Example paint", "name:lang=nl": "Voorbeeld verf", "description:lang=en": "Lorem ipsum dolor sit amet.", "price": 79, "stock": 1, "status": "Available", "weight": 5, "vat_code": 0, "condition": "New", "gtin": "123456", "old_price": "179", "units": "test", "mpq": 1, "purchase_price": 50, "promo": 1, "label_id": 1, "colors": "Blue,Red,Violet", "params": "T,en,Name,,,\nS,en,Select size,[A|B|C],A,1", "review": 1 } }, { "product": { "productID": "LA-C05-A", "parent_productID": "LA-C05", "name:lang=en": "Variation A", "price": "79", "colors": "LightCoral" } }, { "product": { "productID": "LA-C05-B", "parent_productID": "LA-C05", "name:lang=en": "Variation B", "price": "89" } } ] } Recupera os últimos 1000 produtos curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/product Recupera os últimos 1000 produtos, mas ignora os primeiros 1000 produtos curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/product?offset=1000 Recupera produtos que foram adicionados ou modificados nas últimas 24h curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/product/86400 Pesquisa um produto por productID, sensível a maiúsculas e minúsculas curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/product/LA-C05<?php
header
("Content-Type: text/plain");

// API endpoint
// You can add a product search behind the slash
const API_URL 'https://easywebshop.com/api/product/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Optional: If you are sending data (e.g., for a POST request)
// Uncomment the following lines to send a JSON payload
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
*/

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($categories json_decode($responsetrue)) {
        echo 
"\n\n" print_r($categoriestrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "productlist": [ { "product": { "productID": "LA-B03", "category": "Ambiance", "price": 49.99, "stock": 0, "weight": 5, "status": "Available", "vat_code": 0, "old_price": "75", "colors": "Blue,Red,Violet", "promotion": 1 } }, { "product": { "productID": "LA-C05", "category": "Ambiance", "name:lang=en": "Example paint", "name:lang=nl": "Voorbeeld verf", "description:lang=en": "Lorem ipsum dolor sit amet.", "price": 79, "stock": 1, "status": "Available", "weight": 5, "vat_code": 0, "condition": "New", "gtin": "123456", "old_price": "179", "units": "test", "mpq": 1, "purchase_price": 50, "promo": 1, "label_id": 1, "colors": "Blue,Red,Violet", "params": "T,en,Name,,,\nS,en,Select size,[A|B|C],A,1", "review": 1 } }, { "product": { "productID": "LA-C05-A", "parent_productID": "LA-C05", "name:lang=en": "Variation A", "price": "79", "colors": "LightCoral" } }, { "product": { "productID": "LA-C05-B", "parent_productID": "LA-C05", "name:lang=en": "Variation B", "price": "89" } } ] } <?xml version="1.0" encoding="UTF-8" ?> <productlist> <product> <productID>LA-B03</productID> <category>Ambiance</category> <price>49.99</price> <stock>0</stock> <weight>5</weight> <status>Available</status> <vat_code>0</vat_code> <old_price>75</old_price> <colors>Blue,Red,Violet</colors> <promotion>1</promotion> </product> <product> <productID>LA-C05</productID> <category>Ambiance</category> <name lang="en">Example paint</name> <name lang="nl">Voorbeeld verf</name> <description lang="en">Lorem ipsum dolor sit amet.</description> <price>79</price> <stock>1</stock> <status>Available</status> <weight>5</weight> <vat_code>0</vat_code> <condition>New</condition> <gtin>123456</gtin> <old_price>179</old_price> <units>test</units> <mpq>1</mpq> <purchase_price>50</purchase_price> <promo>1</promo> <label_id>1</label_id> <colors>Blue,Red,Violet</colors> <params>T,en,Name,,, S,en,Select size,[A|B|C],A,1</params> <review>1</review> </product> <product> <productID>LA-C05-A</productID> <parent_productID>LA-C05</parent_productID> <name lang="en">Variation A</name> <price>79</price> <colors>LightCoral</colors> </product> <product> <productID>LA-C05-B</productID> <parent_productID>LA-C05</parent_productID> <name lang="en">Variation B</name> <price>89</price> </product> </productlist>

Copiar

Importação de produtos

POST /api/product
Em caso de sucesso, 201 Created será retornado
POST /api/product HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json { "productlist": [ { "product": { "productID": "LA-B03", "category": "Ambiance", "price": 49.99, "stock": 0, "weight": 5, "status": "Available", "vat_code": 0, "old_price": "75", "colors": "Blue,Red,Violet", "promotion": 1 } }, { "product": { "productID": "LA-C05", "category": "Ambiance", "name:lang=en": "Example paint", "name:lang=nl": "Voorbeeld verf", "description:lang=en": "Lorem ipsum dolor sit amet.", "price": 79, "stock": 1, "status": "Available", "weight": 5, "vat_code": 0, "condition": "New", "gtin": "123456", "old_price": "179", "units": "test", "mpq": 1, "purchase_price": 50, "promo": 1, "label_id": 1, "colors": "Blue,Red,Violet", "params": "T,en,Name,,,\nS,en,Select size,[A|B|C],A,1", "review": 1 } }, { "product": { "productID": "LA-C05-A", "parent_productID": "LA-C05", "name:lang=en": "Variation A", "price": "79", "colors": "LightCoral" } }, { "product": { "productID": "LA-C05-B", "parent_productID": "LA-C05", "name:lang=en": "Variation B", "price": "89" } } ] } HTTP/2 201 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "status": "success", "message": [ "4 products inserted" ] } curl -X POST -H "Authorization: Bearer YOUR_API_TOKEN" -d @product-import.json https://easywebshop.com/api/product<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/product/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Uncomment the following lines to set data in PHP
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];

$data = json_encode($data);
*/

// Get data from file
$data file_get_contents('product-import.json');

curl_setopt($chCURLOPT_POSTtrue);
curl_setopt($chCURLOPT_POSTFIELDS$data);

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "productlist": [ { "product": { "productID": "LA-B03", "category": "Ambiance", "price": 49.99, "stock": 0, "weight": 5, "status": "Available", "vat_code": 0, "old_price": "75", "colors": "Blue,Red,Violet", "promotion": 1 } }, { "product": { "productID": "LA-C05", "category": "Ambiance", "name:lang=en": "Example paint", "name:lang=nl": "Voorbeeld verf", "description:lang=en": "Lorem ipsum dolor sit amet.", "price": 79, "stock": 1, "status": "Available", "weight": 5, "vat_code": 0, "condition": "New", "gtin": "123456", "old_price": "179", "units": "test", "mpq": 1, "purchase_price": 50, "promo": 1, "label_id": 1, "colors": "Blue,Red,Violet", "params": "T,en,Name,,,\nS,en,Select size,[A|B|C],A,1", "review": 1 } }, { "product": { "productID": "LA-C05-A", "parent_productID": "LA-C05", "name:lang=en": "Variation A", "price": "79", "colors": "LightCoral" } }, { "product": { "productID": "LA-C05-B", "parent_productID": "LA-C05", "name:lang=en": "Variation B", "price": "89" } } ] } <?xml version="1.0" encoding="UTF-8" ?> <productlist> <product> <productID>LA-B03</productID> <category>Ambiance</category> <price>49.99</price> <stock>0</stock> <weight>5</weight> <status>Available</status> <vat_code>0</vat_code> <old_price>75</old_price> <colors>Blue,Red,Violet</colors> <promotion>1</promotion> </product> <product> <productID>LA-C05</productID> <category>Ambiance</category> <name lang="en">Example paint</name> <name lang="nl">Voorbeeld verf</name> <description lang="en">Lorem ipsum dolor sit amet.</description> <price>79</price> <stock>1</stock> <status>Available</status> <weight>5</weight> <vat_code>0</vat_code> <condition>New</condition> <gtin>123456</gtin> <old_price>179</old_price> <units>test</units> <mpq>1</mpq> <purchase_price>50</purchase_price> <promo>1</promo> <label_id>1</label_id> <colors>Blue,Red,Violet</colors> <params>T,en,Name,,, S,en,Select size,[A|B|C],A,1</params> <review>1</review> </product> <product> <productID>LA-C05-A</productID> <parent_productID>LA-C05</parent_productID> <name lang="en">Variation A</name> <price>79</price> <colors>LightCoral</colors> </product> <product> <productID>LA-C05-B</productID> <parent_productID>LA-C05</parent_productID> <name lang="en">Variation B</name> <price>89</price> </product> </productlist>

Copiar

Você pode encontrar uma explicação detalhada de todos os campos de produto na página de documentação de Gerenciamento básico de produtos e Gerenciamento avançado de produtos.

ParâmetroTipoDescrição
productIDstringArtigo. Um identificador único e definido pelo usuário para o produto.
Evite caracteres especiais e identificadores duplicados ou ambíguos. Ao editar um produto, o productID é usado como identificador. O productID só pode ser alterado com o gerenciamento de produtos.
parent_productIDstringSe desejar que este produto seja uma variação de produto, insira aqui o productID do produto principal. As variações atuam como produtos independentes. Elas estão conectadas a um produto principal em vez de uma categoria e, portanto, não são visíveis nas listas de produtos. Subvariações não são recomendadas e só podem ser definidas com o gerenciamento de produtos.
categorystringO nome da categoria no idioma padrão da loja virtual. Não aplicável para variações de produto.
name:langstringNome. Você pode definir nomes e descrições para todos os idiomas, mesmo que não estejam ativados na loja virtual.
Idiomas disponíveis (ISO 639-1): cs, da, de, el, en, es, fi, fr, it, ja, ko, nl, no, pl, pt, ro, ru, sv, tr, zh
description:langstringDescrição
Idiomas disponíveis (ISO 639-1): cs, da, de, el, en, es, fi, fr, it, ja, ko, nl, no, pl, pt, ro, ru, sv, tr, zh
pricestringPreço. Pode ser decimal, inteiro, vazio ou uma string.
stockintegerEstoque. Deixe em 0 para estoque infinito ou estoque desativado.
statusstringStatus
Available, Available but not online, Pre-order, Sold Out, Invisible, Customers only, Price visible for customers, Choose property, Hide status, custom0, custom1, ..., custom9
image:nostringInclua uma URL de imagem para carregar fotos de produtos. A primeira imagem é a foto principal, as próximas quatro são fotos secundárias. Quando uma foto de produto já existe, ela será substituída. Após o carregamento, as imagens serão dimensionadas proporcionalmente de acordo com as configurações da loja virtual, miniaturas serão criadas automaticamente e a imagem será sincronizada com vários servidores de arquivos. Certifique-se de que cada imagem tenha uma URL válida, um tamanho máximo de arquivo de 25MB, uma extensão válida (.jpg, .jpeg, .png ou .gif) e um tipo MIME válido (image/jpeg, image/jpg, image/png, image/gif).
O carregamento de imagens leva tempo e recursos do servidor. Evite substituir as mesmas imagens ao atualizar produtos. Se encontrar tempos limite, carregue um número limitado de produtos em lotes de 25 imagens cada.1 - 5
thumbnail:nostringAs miniaturas são geradas automaticamente. Este é um parâmetro somente leitura.
weightdecimalPeso. Unidade SI quilograma.
vat_codeintegerTarifa de ICMS. Taxa de IVA definida nas configurações de fatura.
0, 1, 2
conditionstringCondições
New, Used, Refurbished
gtinstringEAN codigo
old_pricestringPreço antigo
unitsstringNúmero de peças
mpqintegerCompra mínima
purchase_pricedecimalPreço de compra
promobooleanPromover este produto na página inicial da minha loja virtual. Não aplicável para variações de produto.
label_idintegerEtiqueta. Deixe em 0 para nenhum rótulo. Não aplicável para variações de produto.
0 - 100
colorsstringCores. Escolha entre os 256 nomes de cores web seguras em inglês, separados por vírgulas.
paramsstringPersonalização do produto. Os parâmetros têm um formato especial e podem ser melhor definidos usando a interface de gerenciamento de produtos. Depois de ter um exemplo, você pode copiá-lo para importação.
reviewbooleanAvaliações. Ativar ou desativar avaliações de produtos.
last_updatedatetimeúltima atividade. Somente leitura.

Estas seções só podem ser definidas usando a interface de gerenciamento: desconto por quantidade, grupo de clientes, vouchers de presente, reservas, produtos digitais, filtros, produtos relacionados.

Até 100 produtos podem ser importados de uma vez. Se desejar importar mais produtos, pode repetir o comando a cada 5 minutos.

Edição de produtos

Você também pode editar produtos usando o recurso de edição rápida, o recurso de importação e o recurso de operações em massa.

PUT /api/product
Em caso de sucesso, 200 OK será retornado
PUT /api/product HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json { "productlist": [ { "product": { "code": "LA-C05", "price": 16, "status": "Available", "stock": 7, "image:no=1": "https://easywebshop.com/img/slideshow/9001.jpg", "image:no=2": "https://easywebshop.com/img/easywebshop.png" } }, { "product": { "code": "SI-V55", "price": "28", "status": "Sold Out", "stock": "0", "weight": "2", "old_price": "43" } } ] } HTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "status": "success", "message": [ "Product SI-V55 not found, skipping", "1 products updated" ] } curl -X PUT -H "Authorization: Bearer YOUR_API_TOKEN" -d @product-edit.json https://easywebshop.com/api/product<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/product/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Uncomment the following lines to set data in PHP
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];

$data = json_encode($data);
*/

// Get data from file
$data file_get_contents('product-edit.json');

curl_setopt($chCURLOPT_CUSTOMREQUEST'PUT');
curl_setopt($chCURLOPT_POSTFIELDS$data);

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "productlist": [ { "product": { "code": "LA-C05", "price": 16, "status": "Available", "stock": 7, "image:no=1": "https://easywebshop.com/img/slideshow/9001.jpg", "image:no=2": "https://easywebshop.com/img/easywebshop.png" } }, { "product": { "code": "SI-V55", "price": "28", "status": "Sold Out", "stock": "0", "weight": "2", "old_price": "43" } } ] } <?xml version="1.0" encoding="UTF-8" ?> <productlist> <product> <code>LA-C05</code> <price>16</price> <status>Available</status> <stock>7</stock> <image no="1">https://easywebshop.com/img/slideshow/9001.jpg</image> <image no="2">https://easywebshop.com/img/easywebshop.png</image> </product> <product> <code>SI-V55</code> <price>28</price> <status>Sold Out</status> <stock>0</stock> <weight>2</weight> <old_price>43</old_price> </product> </productlist>

Copiar

Se desejar atualizar o estoque de produtos, atualize apenas os campos status e estoque. Lembre-se de definir o status de produto apropriado para situações como Esgotado ou Estoque infinito.

Até 100 produtos podem ser atualizados de uma vez. Se desejar atualizar mais produtos, pode repetir o comando a cada 5 minutos.

Exclusão de produtos

DELETE /api/product/[productID]
Em caso de sucesso, 204 No Content será retornado
  • Solicitação
  • Resposta
  • curl
  • PHP
DELETE /api/product/LA-C05 HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 204 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 curl -k -X DELETE -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/product/LA-C05<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/product/LA-B03';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);


curl_setopt($chCURLOPT_CUSTOMREQUEST'DELETE');

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
$httpcode curl_getinfo($chCURLINFO_HTTP_CODE);
    if (
$httpcode == 204) {
        echo 
"Delete successful";
    } else {
        echo 
$response;
    }

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }


}

// Close the cURL session
curl_close($ch);
?>

Copiar

Clientes

Visualização de clientes

EasyWebshop segue o formato schema.org/Person.

GET /api/customer
Recupera os últimos 1000 clientes
GET /api/customer?offset=1000
Recupera os últimos 1000 clientes, mas ignora os primeiros 1000 clientes
GET /api/customer/86400
Recupera clientes que foram adicionados ou modificados nas últimas 24h
GET /api/customer/[email]
Recupera um cliente específico por endereço de e-mail
GET /api/customer HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "customerlist": [ { "customer": { "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "en", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "memberOf": "OpenGroup", "denied": 0 } }, { "customer": { "givenName": "Cindy", "familyName": "Test", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "cindytest@ew.ms", "denied": 0 } } ] } Recupera os últimos 1000 clientes curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/customer Recupera os últimos 1000 clientes, mas ignora os primeiros 1000 clientes curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/customer?offset=1000 Recupera clientes que foram adicionados ou modificados nas últimas 24h curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/customer/86400 Recupera um cliente específico por endereço de e-mail curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/customer/email@address.com<?php
header
("Content-Type: text/plain");

// API endpoint
// You can add an email address behind the slash for searching a specific customer
const API_URL 'https://easywebshop.com/api/customer/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Optional: If you are sending data (e.g., for a POST request)
// Uncomment the following lines to send a JSON payload
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
*/

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($categories json_decode($responsetrue)) {
        echo 
"\n\n" print_r($categoriestrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "customerlist": [ { "customer": { "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "en", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "memberOf": "OpenGroup", "denied": 0 } }, { "customer": { "givenName": "Cindy", "familyName": "Test", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "cindytest@ew.ms", "denied": 0 } } ] } <?xml version="1.0" encoding="UTF-8" ?> <customerlist> <customer> <givenName>Test</givenName> <familyName>Buddy</familyName> <brand></brand> <vatID></vatID> <knowsLanguage>en</knowsLanguage> <address> <addressCountry>BE</addressCountry> <addressLocality>Gent</addressLocality> <addressRegion></addressRegion> <postalCode>9000</postalCode> <streetAddress>Veldstraat</streetAddress> <houseNo>1</houseNo> </address> <telephone>123456789</telephone> <email>testbuddy@ew.ms</email> <memberOf>OpenGroup</memberOf> <denied>0</denied> </customer> <customer> <givenName>Cindy</givenName> <familyName>Test</familyName> <brand></brand> <vatID></vatID> <knowsLanguage>nl</knowsLanguage> <address> <addressCountry>BE</addressCountry> <addressLocality>Gent</addressLocality> <addressRegion></addressRegion> <postalCode>9000</postalCode> <streetAddress>Veldstraat</streetAddress> <houseNo>1</houseNo> </address> <telephone>123456789</telephone> <email>cindytest@ew.ms</email> <denied>0</denied> </customer> </customerlist>

Copiar

Importação de clientes

Cada cliente recebe um e-mail para verificar o endereço de e-mail.

POST /api/customer
Em caso de sucesso, 201 Created será retornado
POST /api/customer HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json { "customerlist": [ { "customer": { "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "en", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "memberOf": "OpenGroup", "denied": 0 } }, { "customer": { "givenName": "Cindy", "familyName": "Test", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "cindytest@ew.ms", "denied": 0 } } ] } HTTP/2 201 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "status": "success", "message": [ "Customer testbuddy@ew.ms: inserted successfully", "Customer testbuddy@ew.ms: verification email sent successfully", "Customer cindytest@ew.ms: inserted successfully", "Customer cindytest@ew.ms: verification email sent successfully", "2 customers inserted" ] } curl -X POST -H "Authorization: Bearer YOUR_API_TOKEN" -d @customer-import.json https://easywebshop.com/api/customer<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/customer/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Uncomment the following lines to set data in PHP
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];

$data = json_encode($data);
*/

// Get data from file
$data file_get_contents('customer-import.json');

curl_setopt($chCURLOPT_POSTtrue);
curl_setopt($chCURLOPT_POSTFIELDS$data);

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "customerlist": [ { "customer": { "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "en", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "memberOf": "OpenGroup", "denied": 0 } }, { "customer": { "givenName": "Cindy", "familyName": "Test", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "cindytest@ew.ms", "denied": 0 } } ] } <?xml version="1.0" encoding="UTF-8" ?> <customerlist> <customer> <givenName>Test</givenName> <familyName>Buddy</familyName> <brand></brand> <vatID></vatID> <knowsLanguage>en</knowsLanguage> <address> <addressCountry>BE</addressCountry> <addressLocality>Gent</addressLocality> <addressRegion></addressRegion> <postalCode>9000</postalCode> <streetAddress>Veldstraat</streetAddress> <houseNo>1</houseNo> </address> <telephone>123456789</telephone> <email>testbuddy@ew.ms</email> <memberOf>OpenGroup</memberOf> <denied>0</denied> </customer> <customer> <givenName>Cindy</givenName> <familyName>Test</familyName> <brand></brand> <vatID></vatID> <knowsLanguage>nl</knowsLanguage> <address> <addressCountry>BE</addressCountry> <addressLocality>Gent</addressLocality> <addressRegion></addressRegion> <postalCode>9000</postalCode> <streetAddress>Veldstraat</streetAddress> <houseNo>1</houseNo> </address> <telephone>123456789</telephone> <email>cindytest@ew.ms</email> <denied>0</denied> </customer> </customerlist>

Copiar

Informações detalhadas podem ser encontradas na página wiki de gerenciamento de clientes.

ParâmetroTipoDescrição
emailstringE-mail. O endereço de e-mail é o identificador único para o cliente.
givenNamestringNome
familyNamestringSobrenome
brandstringEmpresa
vatIDstringNumero do ICMS
knowsLanguagestringIdioma (ISO 639-1): cs, da, de, el, en, es, fi, fr, it, ja, ko, nl, no, pl, pt, ro, ru, sv, tr, zh
addressCountrystringPaís (ISO_3166-1)
addressLocalitystringCidade
addressRegionstringProvíncia. Não é obrigatório para a maioria dos países e frequentemente omitido para tornar o formulário de checkout mais curto.
postalCodestringCódigo postal. Nem todos os países têm códigos postais.
streetAddressstringRua
houseNostringNúmero da casa. Alguns lugares não têm números de casa.
telephonestringTelefone
memberOfstringGrupo de clientes
statusstringStatus
Unconfirmed, Confirmed, Denied
deniedbooleanRecusado
0 - 1
newsletterbooleanAssinatura boletim. Apenas os próprios clientes podem ativar isso.
registration_datedatetimeData de Registro. Somente leitura.

Até 100 clientes podem ser importados de uma vez. Se desejar importar mais clientes, pode repetir o comando a cada 5 minutos.

Edição de clientes

Observe que apenas clientes podem atualizar seus dados como medida de segurança. Você pode atualizar o grupo de clientes e o status do cliente (permitido ou negado).

PUT /api/customer
Em caso de sucesso, 200 OK será retornado
PUT /api/customer HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json { "customerlist": [ { "customer": { "email": "cindytest@ew.ms", "memberOf": "OpenGroup", "denied": 0 } } ] } HTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "status": "success", "message": [ "Customer cindytest@ew.ms: updated successfully", "1 customers updated" ] } curl -X PUT -H "Authorization: Bearer YOUR_API_TOKEN" -d @customer-edit.json https://easywebshop.com/api/customer<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/customer/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Uncomment the following lines to set data in PHP
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];

$data = json_encode($data);
*/

// Get data from file
$data file_get_contents('customer-edit.json');

curl_setopt($chCURLOPT_CUSTOMREQUEST'PUT');
curl_setopt($chCURLOPT_POSTFIELDS$data);

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "customerlist": [ { "customer": { "email": "cindytest@ew.ms", "memberOf": "OpenGroup", "denied": 0 } } ] } <?xml version="1.0" encoding="UTF-8" ?> <customerlist> <customer> <email>cindytest@ew.ms</email> <memberOf>OpenGroup</memberOf> <denied>0</denied> </customer> </customerlist>

Copiar

Até 100 clientes podem ser atualizados de uma vez. Se desejar atualizar mais clientes, pode repetir o comando a cada 5 minutos.

Exclusão de clientes

DELETE /api/customer/[email]
Em caso de sucesso, 204 No Content será retornado
  • Solicitação
  • Resposta
  • curl
  • PHP
DELETE /api/customer/email@address.com HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 204 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 curl -k -X DELETE -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/customer/email@address.com<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/customer/email@address.com';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);


curl_setopt($chCURLOPT_CUSTOMREQUEST'DELETE');

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
$httpcode curl_getinfo($chCURLINFO_HTTP_CODE);
    if (
$httpcode == 204) {
        echo 
"Delete successful";
    } else {
        echo 
$response;
    }

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }


}

// Close the cURL session
curl_close($ch);
?>

Copiar

Pagamentos

Visualização de pedidos

EasyWebshop segue o formato schema.org/Order sempre que possível.

GET /api/order
Recupera os últimos 1000 pedidos
GET /api/order?offset=1000
Recupera os últimos 1000 pedidos, mas ignora os primeiros 1000 pedidos
GET /api/order/86400
Recupera pedidos que foram feitos ou modificados nas últimas 24h
GET /api/order/[orderNumber]
Recupera um pedido específico por número de pedido
GET /api/order HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "orderlist": [ { "order": { "@context": "https:\/\/schema.org", "@type": "Order", "orderNumber": "20250-71911-55107-56027", "orderDate": "2025-04-16 15:39:52", "OrderStatus": "OrderPaymentDue", "description": "", "language": "en", "currency": "EUR", "totalprice": "79", "productlist": [ { "product": { "@type": "Product", "productId": "LA-C05", "description": "Example paint", "price": "79", "amount": "1", "vat_code": "0" } } ], "customer": { "@context": "https:\/\/schema.org", "@type": "Person", "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "status": "Confirmed", "newsletter": 0, "registration_date": "2009-03-27 15:42:02" }, "paymentMethod": "bank", "paymentUrl": "https:\/\/all4you.be\/payment\/20250-71911-55107-56027", "last_update": "2025-04-19 13:18:17" } } ] } Recupera os últimos 1000 pedidos curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/order Recupera os últimos 1000 pedidos, mas ignora os primeiros 1000 pedidos curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/order?offset=1000 Recupera pedidos que foram feitos ou modificados nas últimas 24h curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/order/86400 Recupera um pedido específico por número de pedido curl -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/order/20250-00544-27497-22264<?php
header
("Content-Type: text/plain");

// API endpoint
// You can add an order code behind the slash for searching a specific order
const API_URL 'https://easywebshop.com/api/order/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Optional: If you are sending data (e.g., for a POST request)
// Uncomment the following lines to send a JSON payload
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
*/

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($categories json_decode($responsetrue)) {
        echo 
"\n\n" print_r($categoriestrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "orderlist": [ { "order": { "@context": "https:\/\/schema.org", "@type": "Order", "orderNumber": "20250-71911-55107-56027", "orderDate": "2025-04-16 15:39:52", "OrderStatus": "OrderPaymentDue", "description": "", "language": "en", "currency": "EUR", "totalprice": "79", "productlist": [ { "product": { "@type": "Product", "productId": "LA-C05", "description": "Example paint", "price": "79", "amount": "1", "vat_code": "0" } } ], "customer": { "@context": "https:\/\/schema.org", "@type": "Person", "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "status": "Confirmed", "newsletter": 0, "registration_date": "2009-03-27 15:42:02" }, "paymentMethod": "bank", "paymentUrl": "https:\/\/all4you.be\/payment\/20250-71911-55107-56027", "last_update": "2025-04-19 13:18:17" } } ] } <?xml version="1.0" encoding="UTF-8" ?> <orderlist> <order> <@context>https://schema.org</@context> <@type>Order</@type> <orderNumber>20250-71911-55107-56027</orderNumber> <orderDate>2025-04-16 15:39:52</orderDate> <OrderStatus>OrderPaymentDue</OrderStatus> <description></description> <language>en</language> <currency>EUR</currency> <totalprice>79</totalprice> <productlist> <product> <@type>Product</@type> <productId>LA-C05</productId> <description>Example paint</description> <price>79</price> <amount>1</amount> <vat_code>0</vat_code> </product> </productlist> <customer> <@context>https://schema.org</@context> <@type>Person</@type> <givenName>Test</givenName> <familyName>Buddy</familyName> <brand></brand> <vatID></vatID> <knowsLanguage>nl</knowsLanguage> <address> <addressCountry>BE</addressCountry> <addressLocality>Gent</addressLocality> <addressRegion></addressRegion> <postalCode></postalCode> <streetAddress>Veldstraat</streetAddress> <houseNo>1</houseNo> </address> <telephone>123456789</telephone> <email>testbuddy@ew.ms</email> <status>Confirmed</status> <newsletter>0</newsletter> <registration_date>2009-03-27 15:42:02</registration_date> </customer> <paymentMethod>bank</paymentMethod> <paymentUrl>https://all4you.be/payment/20250-71911-55107-56027</paymentUrl> <last_update>2025-04-19 13:18:17</last_update> </order> </orderlist>

Copiar

Importação de pedidos

Devido à natureza complexa do fluxo de checkout, os pedidos só podem ser inseridos fazendo o pedido na loja virtual ou usando o aplicativo POS.

Edição de pedidos

PUT /api/order
Em caso de sucesso, 200 OK será retornado
PUT /api/customer HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json { "orderlist": [ { "order": { "code": "20250-71911-55107-56027", "status": "OrderDelivered", "reference": "Internal note", "mail_customer": 1 } } ] } HTTP/2 200 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 { "status": "success", "message": [ "Order 20250-71911-55107-56027: updated successfully", "Order 20250-71911-55107-56027: email successfully sent to testbuddy@ew.ms" ] } curl -X PUT -H "Authorization: Bearer YOUR_API_TOKEN" -d @order-edit.json https://easywebshop.com/api/order<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/order/';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);

// Uncomment the following lines to set data in PHP
/*
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];

$data = json_encode($data);
*/

// Get data from file
$data file_get_contents('order-edit.json');

curl_setopt($chCURLOPT_CUSTOMREQUEST'PUT');
curl_setopt($chCURLOPT_POSTFIELDS$data);

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
echo $response;

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }
}

// Close the cURL session
curl_close($ch);
?>
{ "orderlist": [ { "order": { "code": "20250-71911-55107-56027", "status": "OrderDelivered", "reference": "Internal note", "mail_customer": 1 } } ] } <?xml version="1.0" encoding="UTF-8" ?> <orderlist> <order> <code>20250-71911-55107-56027</code> <status>OrderDelivered</status> <reference>Internal note</reference> <mail_customer>1</mail_customer> </order> </orderlist>

Copiar

Informações detalhadas podem ser encontradas na página wiki de gerenciamento de pedidos.

ParâmetroTipoDescrição
orderNumberstringNúmero do pedido. O número do pedido ou código do pedido é o identificador único para o pedido.
statusstringStatus
ParâmetroDescrição
OrderReceivedPedido recebido
OrderPaymentDueAguardando pagamento
OrderPaymentReceivedPagamento recebido
OrderProcessingNo processamento de pedidos
OrderInTransitPedido enviado
OrderDeliveredPedido concluído
OrderCancelledCancelado
referencestringEsta é uma referência para fins internos que pode ser definida para cada pedido. A referência não será mostrada ao cliente.
mail_customerbooleanEnviar uma notificação por e-mail ao cliente.

Até 100 pedidos podem ser atualizados de uma vez. Se desejar atualizar mais pedidos, pode repetir o comando a cada 5 minutos.

Exclusão de pedidos

DELETE /api/order/[orderNumber]
Em caso de sucesso, 204 No Content será retornado
  • Solicitação
  • Resposta
  • curl
  • PHP
DELETE /api/order/20250-00544-27497-22264 HTTP/2 Host: easywebshop.com Authorization: Bearer YOUR_API_TOKEN Content-Type: application/jsonHTTP/2 204 Server: nginx Date: Wed, 12 Mar 2025 12:00:00 GMT Content-Type: text/plain;charset=UTF-8 curl -k -X DELETE -H "Authorization: Bearer YOUR_API_TOKEN" -D - https://easywebshop.com/api/order/20250-00544-27497-22264<?php
header
("Content-Type: text/plain");

// API endpoint
const API_URL 'https://easywebshop.com/api/order/20250-71911-55107-56027';

// Your Bearer token
const API_TOKEN 'YOUR_API_TOKEN';

// True: show request and response headers
const DEBUG true;

// Initialize cURL session
$ch curl_init(API_URL);

// Set cURL options
// Return the response as a string
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_HTTPHEADER, [
    
'Authorization: Bearer ' API_TOKEN,
    
'Content-Type: application/json'
]);


curl_setopt($chCURLOPT_CUSTOMREQUEST'DELETE');

// Activate request and response details (for showing later)
if (DEBUG) {
    
curl_setopt($chCURLOPT_HEADERtrue);
    
curl_setopt($chCURLINFO_HEADER_OUTtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_SSL_VERIFYHOSTfalse);
}

// Execute the cURL request
$response curl_exec($ch);

// Show the request details
if (DEBUG) {
    echo 
curl_getinfo($chCURLINFO_HEADER_OUT);
}

// Check for errors
if (curl_errno($ch)) {
    echo 
'cURL error: ' curl_error($ch);

// Print the response
} else {

    
// Print request and response header
    
if (DEBUG) {
        
$header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
        
$header substr($response0$header_size);
        
$response substr($response$header_size);
        echo 
$header;
    }

    
// Print response
    
$httpcode curl_getinfo($chCURLINFO_HTTP_CODE);
    if (
$httpcode == 204) {
        echo 
"Delete successful";
    } else {
        echo 
$response;
    }

    
// Print response in PHP array
    
if ($response_array json_decode($responsetrue)) {
        echo 
"\n\n" print_r($response_arraytrue);
    }


}

// Close the cURL session
curl_close($ch);
?>

Copiar

Observe que ao excluir pedidos ou alterar o status para Cancelado, o estoque será readicionado (se os produtos ainda existirem) e os produtos mudarão o status de Esgotado para Disponível, se aplicável. Ao descancelar um pedido, o estoque será subtraído dos produtos novamente.

Limites

EasyWebshop é otimizado para redundância e tempos de carregamento de site extremamente rápidos. Nos bastidores, existe um cluster de servidores geograficamente distribuído por vários centros de dados em diversos países. Isso tem um custo: ao adicionar e atualizar dados e arquivos, eles precisam ser sincronizados pelo cluster de servidores e os caches precisam ser limpos em todos os servidores. As imagens precisam ser comprimidas e redimensionadas para vários formatos para fotos com zoom e miniaturas, nomes de arquivos otimizados para SEO precisam ser verificados e criados, e todos os dados precisam ser sincronizados entre servidores de arquivos distribuídos e servidores de backup.

O propósito dos limites é garantir que um único utilizador não sobrecarregue os nossos sistemas, o que causaria danos a outros utilizadores.

Solicitações de API300 solicitações por 24h
Visualização de itens1000 itens por solicitação
Importação de itens100 itens por solicitação
Atualização de itens100 itens por solicitação
Carregamento de imagens100 imagens por solicitação (25 Megabyte per image)

Limites elevados de API

Em situações normais, os limites padrão devem ser suficientes. Apenas para lojas online com uma enorme quantidade de produtos, os limites poderiam ser uma barreira.

Em Configurações > Mais opções > EasyWebshop API, a funcionalidade Limites elevados de API pode ser ativada. Isto permite a compra de solicitações adicionais de API.

API Push

API Push envia uma solicitação HTTPS com dados JSON ou XML. Estes dados podem ser "capturados" por um servidor e processados.

Se simplesmente deseja receber um e-mail dos seus pedidos num destino adicional, utilize contas de administrador. Também pode receber notificações instantâneas para pedidos recebidos.

Em Configurações > Módulos > EasyWebshop API > API Push, introduza o URL da sua aplicação e guarde. Após guardar, um botão Testar aparecerá, permitindo-lhe enviar uma solicitação de exemplo. Para desativar, simplesmente deixe os URLs vazios e guarde.

API Push

Customer PushOrder Push
Uma solicitação HTTPS é enviada quando um cliente cria uma conta, contendo todas as informações sobre o cliente, semelhante à API de Cliente.Uma solicitação HTTPS é enviada quando um cliente faz um pedido na loja online ou quando um pedido é feito utilizando o POS. Esta solicitação contém todos os dados do pedido, os produtos adquiridos e informações sobre o cliente, semelhante à API de Pedidos.


  • Customer Push
  • Order Push
  • index.php
{ "customerlist": [ { "customer": { "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "en", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "memberOf": "OpenGroup", "denied": 0 } }, { "customer": { "givenName": "Cindy", "familyName": "Test", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "9000", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "cindytest@ew.ms", "denied": 0 } } ] } { "orderlist": [ { "order": { "@context": "https:\/\/schema.org", "@type": "Order", "orderNumber": "20250-71911-55107-56027", "orderDate": "2025-04-16 15:39:52", "OrderStatus": "OrderPaymentDue", "description": "", "language": "en", "currency": "EUR", "totalprice": "79", "productlist": [ { "product": { "@type": "Product", "productId": "LA-C05", "description": "Example paint", "price": "79", "amount": "1", "vat_code": "0" } } ], "customer": { "@context": "https:\/\/schema.org", "@type": "Person", "givenName": "Test", "familyName": "Buddy", "brand": "", "vatID": "", "knowsLanguage": "nl", "address": { "addressCountry": "BE", "addressLocality": "Gent", "addressRegion": "", "postalCode": "", "streetAddress": "Veldstraat", "houseNo": "1" }, "telephone": "123456789", "email": "testbuddy@ew.ms", "status": "Confirmed", "newsletter": 0, "registration_date": "2009-03-27 15:42:02" }, "paymentMethod": "bank", "paymentUrl": "https:\/\/all4you.be\/payment\/20250-71911-55107-56027", "last_update": "2025-04-19 13:18:17" } } ] } <?php
/*--------------------------------------------
 * EasyWebshop API Push test script
--------------------------------------------*/

// Address to send data to
$email 'test@ew.ms';

// Collect data
$feedback "\n\nGET variables:\n\n";

foreach (
$_GET as $name => $value) {
    
$feedback .= $name ': ' $value "\n";
}

$feedback .= "\n\nPOST variables:\n\n";
foreach (
$_POST as $name => $value) {
    
$feedback .= $name ': ' $value "\n";
}

$feedback .= "\n\nInput data:\n\n" file_get_contents("php://input");

// Send mail
mail($email'EasyWebshop API Push '$feedback "\n\n" .

    
// Username
    
(isset($_SERVER['PHP_AUTH_USER']) ? 'User: ' $_SERVER['PHP_AUTH_USER'] . "\n" '') .

    
// IP Address
    
(isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] . "\n" '') .
    
$_SERVER['REMOTE_ADDR']);


// Return success
header('HTTP/1.1 200 OK');
die(
'200 OK');

?>

Copiar

Conexões

Conexões são pequenas aplicações web que residem no seu próprio servidor e têm o seu próprio URL. Podem ser instaladas por todas as lojas online, portanto o seu código pode ser reutilizado por todos os utilizadores do EasyWebshop.

Em Configurações > Módulos > EasyWebshop API > Tokens de Conexões, clique no botão Adicionar para criar um novo Token de Conexão API. Terá de introduzir o URL da conexão.

Certifique-se de que está a criar um Token de Conexão API e não um Token API regular.

API Connections

Os tipos de conexões são:
Serviço de entrega, Widget HTML, Fatura, Feed de produtos, Provedor de Serviços de Pagamento.

As conexões tipicamente têm vários arquivos:

ArquivoDescrição
settings.xmlEste é o arquivo de configuração da conexão.
name
O nome da conexão. Utilize apenas letras maiúsculas e minúsculas, números e sublinhados. Este nome é usado como identificador.
logo
O nome do arquivo de um logotipo dentro do diretório da conexão.
type
O tipo de conexão, escolha entre:
ds (delivery service), html (HTML widget), invoice, productfeed, psp (Payment Service Provider)
url
O URL onde o arquivo index.php está hospedado.
parameter
Cinco parâmetros opcionais podem ser introduzidos pelo comerciante ao instalar ou editar a conexão. Por exemplo: o token API de um PSP pode ser introduzido aqui pelo comerciante.
easywebshop.phpEste é o arquivo que se conecta à API EasyWebshop.
Defina o seu Token de Conexão API (não um Token API regular) neste arquivo.
index.phpEste é o arquivo principal e o primeiro a ser acedido quando a conexão é utilizada. No caso de um serviço de entrega, os campos GET com o endereço do cliente são enviados para este arquivo. No caso de um PSP, os campos POST do pedido são enviados para este arquivo.
report.phpEste arquivo é utilizado no caso de PSP e Fatura e é tipicamente solicitado em segundo plano pelo PSP para enviar atualizações sobre o estado do pagamento. Este arquivo então atualiza o estado do pedido na loja online para Pagamento recebido.

Para facilitar a criação de novas conexões, mantivemos os exemplos abaixo o mais simples e diretos possível.

Serviço de entrega

Utilize o exemplo abaixo para criar conexões com serviços de entrega ou transporte.

A conexão precisa ser instalada pelo comerciante e os métodos de envio precisam ser conectados selecionando-os.

  1. O cliente está na página de checkout e seleciona um método de envio. Como a sua conexão está ligada a um método de envio, isto aciona um popup com um iframe que aponta para o seu arquivo index.php.
  2. Os dados de endereço do cliente são enviados como variáveis GET na string de consulta.
  3. Na sua conexão, o cliente pode escolher um método de envio ou selecionar um ponto de recolha a partir de um mapa.
  4. A sua conexão envia o nome do método de envio, preço, descrição e um logotipo para o nosso URL de confirmação (/dsconfirm).
  5. Os dados são adicionados ao pedido e o cliente recebe uma confirmação.
  • settings.xml
  • easywebshop.php
  • index.php
  • style.css
<?xml version="1.0" encoding="UTF-8" ?> <settings> <name>ExampleDeliveryService</name> <logo>logo.png</logo> <type>ds</type> <url>https://www.webshopdata.com/app/easywebshop-ds/index.php</url> <parameter name="Account ID"></parameter> <parameter name="Passphrase"></parameter> </settings> <?php
/*
   EasyWebshop API Connector
   Documentation: https://easywebshop.com/doc/api
*/
function easyApp($data '') {

    
// Set your API Connection Token (not API Token!) here
    
$conn_token 'YOUR_API_TOKEN';

    
// No need to change anything below. You can watch, but you can't touch!
    
if (!isset($_REQUEST['shop_id']) || !$_REQUEST['shop_id'] ||
        !
filter_var($_REQUEST['shop_id'], FILTER_VALIDATE_INT,
        array(
'options' => array('min_range' => 1'max_range' => 1000000000)))) {
        die(
'Error: $_REQUEST[\'shop_id\'] not set');
    }

    
$settings = new SimpleXMLElement(file_get_contents(dirname(__FILE__) . '/settings.xml'));
    
$method      = isset($data['function']) && substr($data['function'], 03) == 'set' 'PUT' 'GET';
    
$format   = isset($data['format']) && in_array(strtolower($data['format']), array('json''xml')) ?
            
strtolower($data['format']) : 'array';
    
$data     is_array($data) ? ($method == 'GET' http_build_query($data) : json_encode($data)) : '';
    
$apiurl      'https://easywebshop.jan/api/conn/' $_REQUEST['shop_id'] . '/' $settings->name .
            (
$method == 'GET' && $data '?' $data ''); // HTTPS only
    
$opts     = array(
        
'http' => array(
            
'header' =>    "Content-Type: application/x-www-form-urlencoded\r\n" .
                    
'Authorization: Bearer ' .
                    
hash('sha512'$_REQUEST['shop_id'] . $settings->name hash('sha256'$conn_token) . $data) . "\r\n",
            
'method' =>    $method,
            
'ignore_errors' => true),
        
'ssl'  => array('verify_peer' => false'verify_peer_name' => false)
        );
    if (
$method == 'PUT') { $opts['http']['content'] = $data; }
    
$response file_get_contents($apiurlfalsestream_context_create($opts));
    
$appdata  $format == 'array' json_decode($responsetrue) : $response;

    
// Output log - only in debug mode
    
if (defined('DEBUG') && DEBUG) {
        echo 
"-- easywebshop.php " $settings->name "\n> Accessing API: " .
            
$apiurl "\n> API response: " $response "--\n";
    }

    return 
$appdata// this can be a PHP array, JSON or XML, depending on the $data['format'] value

// easyApp()
?>
<?php
/*--------------------------------------------
   EasyWebshop Delivery service example 

    Install link:
    https://easywebshop.com/software/connections?install=https://www.webshopdata.com/app/easywebshop-ds

    Block 1: Variables
    Block 2: Languages
    Block 3: Delivery service API code
    Block 4: Process form data
    Block 5: Start page

--------------------------------------------*/

/*--------------------------------
    Block 1: Variables
-------------------------------*/
// Debug mode for testing, set to false in production
define('DEBUG'true); 

// Use test data
define('TEST'true);

// Use for testing without GET vars from checkout form
if (TEST) {
    
$_REQUEST = array('shop_id' => 71911'lang' => 'en');
    
$_GET = array('shop_id'        => $_REQUEST['shop_id'],
        
'webshop_url'        => 'https://all4you.be',
        
'shipping_method'    => 'Standard delivery',
        
#'shipping_method'    => 'Pickup at collection point',
        
'firstname'        => 'Bruno',
        
'lastname'        => 'Test',
        
'street'        => 'Mottakerveien',
        
'no'            => '14',
        
'zipcode'        => '0150',
        
'city'            => 'Oslo',
        
'province'        => '',
        
'country'        => 'NO',
        
'lang'            => $_REQUEST['lang'],
        
'weight'        => 0.5// total weight of the shopping basket in kg
        
'freeshipping'        => ''// shipping discount
        
'email'            => 'bruno@mailinator.com',
        
'phone'            => '12345678',
        
'total'            => 100); // total price of the order, can be used to give discounts
// TEST

// Get the connection settings
$settings = new SimpleXMLElement(file_get_contents(dirname(__FILE__) . '/settings.xml'));

// Get the data from the webshop
require 'easywebshop.php';
$appdata easyApp();

/* This gives us the following array
Array
(
    [webshop] => Array
        (
            [email]    => example@voorbeeldshop.be
            [url]    => https://voorbeeldshop.be
            [name]    => Voorbeeld webshop
            [country]    => BE
            [lang]    => nl
            [currency]    => EUR
        )

    [response_time] => 0.00084
)*/

// Show all the data we have for testing
if (DEBUG) {
    echo 
"<pre>--------------------------------\n\tGET variables:\n--------------------------------\n\n";
    
print_r($_GET);
    echo 
"\n\n</pre>";

    echo 
"<pre>--------------------------------\n\tConnection variables:\n--------------------------------\n\n";
    
print_r($appdata);
    echo 
"\n\n</pre>";
}

/*--------------------------------
    Block 3: Delivery service API code
    Delivery variables
        - These can be hard coded, or requested from another source
        - Prices can also depend on customer location, use $_GET['zipcode'] for this
-------------------------------*/

$delivery_prices = array(2.51.50);

/*--------------------------------
    Block 2: Languages
-------------------------------*/

// Dutch
if ($_REQUEST['lang'] == 'nl') {
    
$l_deliverymethod 'Kies uw verzendmethode';
    
$l_deliverymethods = array('Levering met drone''Levering met fiets''Afhalen in pakketautomaat');
    
$l_confirm 'Bevestigen';

// Other languages
} else {
    
$l_deliverymethod 'Choose your delivery method';
    
$l_deliverymethods = array('Delivery by drone''Delivery by bicycle''Pick up in a parcel machine');
    
$l_confirm 'Confirm';
}



/*--------------------------------
    Block 4: Process form data
-------------------------------*/

if (isset($_POST['deliverymethod'])) {

    
// Send delivery method
    
$ds_method $l_deliverymethods[0];
    if (
is_numeric($_POST['deliverymethod']) && isset($l_deliverymethods[$_POST['deliverymethod']])) {
        
$ds_method $l_deliverymethods[$_POST['deliverymethod']];
    }

    
// Separate prices per delivery method
    
$ds_price $delivery_prices[0];
    if (
is_numeric($_POST['deliverymethod']) && isset($delivery_prices[$_POST['deliverymethod']])) {
        
$ds_price $delivery_prices[$_POST['deliverymethod']];
    }

    
// Show a logo on the confirm page, always use HTTPS for displaying images on a HTTPS page
    
$ds_logo 'https://www.webshopdata.com/app/easywebshop-ds/logo.png';

    
// Order number
    
$ds_info 'Reference ' rand(010000); // this can be a reference to an external database

    // Confirm delivery method
    
header('Location: ' $appdata['webshop']['url'] . '/dsconfirm' .
        
'?ds=' urlencode($settings->name) .
        
'&ds_price=' $ds_price .
        
'&ds_method=' urlencode($ds_method) .
        
'&ds_info=' urlencode($ds_info) .
        
'&ds_logo=' urlencode($ds_logo) .
        
'&ds_seconds=5'); // how long to show the confirmation message

    
die;
}
/*--------------------------------
    Block 5: Start page
        - Let's keep it very simple
-------------------------------*/

// Header
echo '<!DOCTYPE html><html lang="en"><head><title>' $settings->name '</title><meta charset="utf-8">' .
    
'<link rel="stylesheet" href="style.css"></head>' // you can also include javascript here
    
'<body><main><img src="logo.png" alt="' $settings->name '" id="logo"><h1>' $settings->name '</h1>' .

    
// Form
    
'<form method="POST">' .
    
'<input type="hidden" name="shop_id" value="' $_REQUEST['shop_id'] . '">' .
    
'<input type="hidden" name="lang" value="' $_REQUEST['lang'] . '">' .
    
'<table>' .
    
'<tr><td>' $l_deliverymethod '</td><td>';

// Loop delivery methods
foreach ($l_deliverymethods as $k => $v) {
    echo 
'<input type="radio" name="deliverymethod" value="' $k '" id="' $k '">' .
        
'<label for="' $k '">' $v ' <strong>€ ' $delivery_prices[$k] . '</strong></label><br>';
}
echo 
'</td></tr>' .

    
// Submit form
    
'<tr><td></td><td><input type="submit" name="submit" value="' $l_confirm '"></td></tr>' .
    
'</table></form>' .

    
// End page
    
'</main></body></html>';

?>
body    { margin: 0; font-family: Helvetica, Arial, sans-serif; color: #333; background-color: #E4E4E4; }
main    { margin: 0 auto; margin-top: 30px; margin-bottom: 30px; padding: 20px; width: 760px; background-color: #FFF; border-radius: 8px; border: 1px solid #CCC; box-shadow: 5px 5px 5px #888; }
#logo    { margin-bottom: 10px; }
h1    { font-size: 22px; margin: 0; padding: 0; color: #06C; margin-bottom: 80px; }
hr    { clear: both; border-style: solid; border-width: 1px 0 0 0; border-color: #E4E4E4; margin: 20px 0; }

/*--------------------------------
     Navigation
-------------------------------*/
nav    { margin: 40px 0; clear: both; }
nav a    {
    display: block; width: 70%; margin: 30px auto; padding: 20px; vertical-align: top;
    border: 1px solid #E4E4E4; box-shadow: 2px 2px 2px #888;
    /*border-style: solid; border-width: 0 0 1px 0; border-color: #CCC;*/
    text-decoration: none; color: #06C; font-size: 20px; font-weight: bold;
    transition: background 0.4s;
}

nav a:hover { background: #EEE; }
nav img    { display: inline-block; float: left; width: 100px; height: 100px; vertical-align: top; }
nav span{ display: inline-block; line-height: 100px; text-indent: 30px; }
.langselect { font-size: 0.8em; font-weight: bold; }
/*--------------------------------
     Buttons
-------------------------------*/
a.glowbutton, input[type="submit"], input[type="button"]    {
    white-space: nowrap; display: inline-block; min-width: 210px; margin: 0 0 10px 0; padding: 0;
    text-decoration: none; text-align: center;
    color: #FFF; background-color: #06C; border: 0; border-radius: 3px;
    line-height: 33px; height: 33px; font-weight: bold; font-size: 0.9em;
    -webkit-appearance: none; -moz-appearance: none; appearance: none;
    transition: background 0.4s;
}

a.glowbutton:hover, input[type="submit"]:hover    {
    background-color: #06F; text-decoration: none;
}

/*--------------------------------
     Fancy
-------------------------------*/

a    { color: #06C; text-decoration: none; }
a:hover    { text-decoration: underline; }
h2    { font-size: 1.6em; }
h3    { font-size: 1.4em; }
h4    { font-size: 1.1em; color: #666; }
.blue    { color: #06C; }
.orange { color: #F60; }
.code    { font-family: monospace; color: #090; }
.code a    { font-weight: bold; color: #090; }
.warn    { background-color: #FC0; padding: 15px 5px; text-align: center; border-radius: 5px; font-size: 0.9em; box-shadow: 2px 2px 2px #888; }

/*--------------------------------
     Forms
-------------------------------*/
textarea                    { width: 99%; height: 200px; font-size: 1.2em; color: #666; }
input, select, textarea                { border: 1px solid #CCC; border-radius: 3px; padding: 3px; }
input:focus, textarea:focus            { background-color: #EEE; }
input[type="checkbox"], input[type="radio"]    { border: 0;}
input[type="submit"], input[type="button"]    { cursor: pointer; float: right; margin: 10px 0 0 0;  }
form table                    { width: 100%; }
form table td:first-child            { width: 50%; }
label                        { display: inline-block; max-width: 90%; padding: 0 0 0 10px; cursor: pointer; }
/*--------------------------------
     Responsive
-------------------------------*/
@media all and (max-width: 790px) {
    main        { width: 100%; margin: 0; padding: 20px 0; border: none; border-radius: 0; }
    nav a        { margin: 0 auto; margin-top: 20px; margin-bottom: 20px; }
    textarea    { width: 97%; }
}

Widget HTML

Os widgets podem ser utilizados para inserir facilmente código HTML, CSS e JavaScript. O utilizador pode escolher em quais páginas do site deseja instalar este código. É basicamente o mesmo que copiar e colar, mas mais amigável ao utilizador.

  • settings.xml
<?xml version="1.0" encoding="UTF-8" ?> <settings> <name>ExampleWidget</name> <type>html</type> <parameter name="Enter variable data 1">Example data 1</parameter> <parameter name="Enter variable data 2">Example data 2</parameter> <url>https://www.webshopdata.com/app/easywebshop-html/settings.xml</url> <html><![CDATA[<p> Hello! I'm a <strong>HTML example</strong>.<br> You can use HTML, CSS and JavaScript code here.<br> The user can insert it on any page of the website. </p> <p> Your first parameter was <strong>[PARAMETER1]</strong>.<br> Your second parameter was <strong>[PARAMETER2]</strong>. </p> <p> To install me, redirect your user to:<br> https://easywebshop.com/software/connections?install=https://www.webshopdata.com/app/easywebshop-html </p> <p> Replace the second part of the URL by the directory on your sever.<br> Only this settings.xml file is required in the directory. </p>]]></html> </settings>

Fatura

A Fatura funciona da mesma forma que o Provedor de Serviços de Pagamento, mas focada no pagamento por fatura onde os dados do cliente são necessários. Quando o tipo é definido como psp, apenas os dados necessários que um PSP precisa para processar um pagamento estão disponíveis. Quando o tipo é invoice, os dados do cliente também se tornam disponíveis.

Feed de produtos

Utilizado para recuperar dados de produtos, por exemplo, para uso em sites de comparação.

  • settings.xml
  • easywebshop.php
  • index.php
  • style.css
<?xml version="1.0" encoding="UTF-8" ?> <settings> <name>DemoFeed</name> <type>productfeed</type> <url>https://www.webshopdata.com/app/easywebshop-productfeed/index.php</url> </settings> <?php
/*
   EasyWebshop API Connector
   Documentation: https://easywebshop.com/doc/api
*/
function easyApp($data '') {

    
// Set your API Connection Token (not API Token!) here
    
$conn_token 'YOUR_API_TOKEN';

    
// No need to change anything below. You can watch, but you can't touch!
    
if (!isset($_REQUEST['shop_id']) || !$_REQUEST['shop_id'] ||
        !
filter_var($_REQUEST['shop_id'], FILTER_VALIDATE_INT,
        array(
'options' => array('min_range' => 1'max_range' => 1000000000)))) {
        die(
'Error: $_REQUEST[\'shop_id\'] not set');
    }

    
$settings = new SimpleXMLElement(file_get_contents(dirname(__FILE__) . '/settings.xml'));
    
$method      = isset($data['function']) && substr($data['function'], 03) == 'set' 'PUT' 'GET';
    
$format   = isset($data['format']) && in_array(strtolower($data['format']), array('json''xml')) ?
            
strtolower($data['format']) : 'array';
    
$data     is_array($data) ? ($method == 'GET' http_build_query($data) : json_encode($data)) : '';
    
$apiurl      'https://easywebshop.jan/api/conn/' $_REQUEST['shop_id'] . '/' $settings->name .
            (
$method == 'GET' && $data '?' $data ''); // HTTPS only
    
$opts     = array(
        
'http' => array(
            
'header' =>    "Content-Type: application/x-www-form-urlencoded\r\n" .
                    
'Authorization: Bearer ' .
                    
hash('sha512'$_REQUEST['shop_id'] . $settings->name hash('sha256'$conn_token) . $data) . "\r\n",
            
'method' =>    $method,
            
'ignore_errors' => true),
        
'ssl'  => array('verify_peer' => false'verify_peer_name' => false)
        );
    if (
$method == 'PUT') { $opts['http']['content'] = $data; }
    
$response file_get_contents($apiurlfalsestream_context_create($opts));
    
$appdata  $format == 'array' json_decode($responsetrue) : $response;

    
// Output log - only in debug mode
    
if (defined('DEBUG') && DEBUG) {
        echo 
"-- easywebshop.php " $settings->name "\n> Accessing API: " .
            
$apiurl "\n> API response: " $response "--\n";
    }

    return 
$appdata// this can be a PHP array, JSON or XML, depending on the $data['format'] value

// easyApp()
?>
<?php
/*--------------------------------------------
   EasyWebshop Productfeed example 

    Install link:
    https://easywebshop.com/software/connections?install=https://www.webshopdata.com/app/easywebshop-productfeed

    Block 1: Variables
    Block 2: Generate feed
    Block 3: Languages
    Block 4: Productfeed form
    Block X: Functions

--------------------------------------------*/

/*--------------------------------
    Block 1: Variables
-------------------------------*/

define('DEBUG'true);            // Debug mode for testing, set to false in production
$languages = array('cs''da''de''el''en''es''fi''fr''it''ja''ko''nl''no''pl''pt''ro''ru''sv''tr''zh');

define('SHOP_ID', isset($_REQUEST['shop_id']) && checkId($_REQUEST['shop_id']) ? $_REQUEST['shop_id'] : 0);
define('LANG', isset($_REQUEST['lang']) && in_array($_REQUEST['lang'], $languages) ? $_REQUEST['lang'] : 'en');

$settings = new SimpleXMLElement(file_get_contents(dirname(__FILE__) . '/settings.xml'));

/*--------------------------------
    Block 2: Generate feed
-------------------------------*/
if (SHOP_ID && isset($_GET['token']) &&
    
preg_match('/^[0-9a-f]{40}$/i'$_GET['token']) && $_GET['token'] == sha1(SHOP_ID LANG 'roor8weiChait0gai')) {

    
/*--------------------------------
        Connect to the EasyWebshop App API
            easyApp(
                [data]        Data to send to the API, optional
            )
        - Returns an array of requested data, view with: print_r($appdata);
    -------------------------------*/

    
header('Content-Type: text/xml; charset=utf-8');

    
// Show feed in XML format
    
echo "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" ">\n<items>\n";

    if (
DEBUG) {
        echo 
'<debug><![CDATA[';
    }

    include 
'easywebshop.php';
    
$appdata easyApp(array('lang' => LANG'seconds' => 0'start' => 0'length' => 1000)); //, 'format' => 'xml'));

    
if (DEBUG) {
        echo 
"]]></debug>\n";
    }

    if (isset(
$appdata['products'])) {
        
displayProducts($appdata);

        
// Max 5000 products
        
for ($i 1$i 5$i++) {
            if (
count($appdata['products']) >= 1000) {
                
$appdata easyApp(array('lang' => LANG'seconds' => 0'start' => ($i 1000), 'length' => 1000)); //, 'format' => 'xml'));
                
displayProducts($appdata);
            }
        }
            
        
//"<updated>" . gmdate("Ymd\THis\Z") . "</updated>\n";
    
}

    echo 
'</items>';
    die;

}

/*--------------------------------
    Block 3: Languages
-------------------------------*/

// Danish
if (LANG == 'da') {

    
$l_language        'Sprog';
    
$l_languages        = array('cs' => 'Tjekkisk''da' => 'Dansk''de' => 'Tysk''el' => 'Greek''en' => 'Engelsk''es' => 'Spansk''fi' => 'Finsk''fr' => 'Fransk''it' => 'Italiensk''ja' => 'Japansk''ko' => 'Koreansk''nl' => 'Nederlandsk''no' => 'Norsk''pl' => 'Polsk''pt' => 'Portugisisk''ro' => 'Rumænsk''ru' => 'Russisk''sv' => 'Svensk''tr' => 'Tyrkisk''zh' => 'Kinesisk');
    
$l_generate_feed     'Generer produktfeed';
    
$l_feed_url         'Din <strong>' $settings->name '</strong> feedwebadresse er:';

// German
} elseif (LANG == 'de') {

    
$l_language        'Sprache';
    
$l_languages        = array('cs' => 'Tschechisch''da' => 'Dänisch''de' => 'Deutsch''el' => 'Griechisch''en' => 'Englisch''es' => 'Spanisch''fi' => 'Finnisch''fr' => 'Französisch''it' => 'Italienisch''ja' => 'Japanisch''ko' => 'Koreanisch''nl' => 'Niederländisch''no' => 'Norwegisch''pl' => 'Polnisch''pt' => 'Portugiesisch''ro' => 'Rumänisch''ru' => 'Russisch''sv' => 'Schwedisch''tr' => 'Türkisch''zh' => 'Chinesisch');
    
$l_generate_feed     'Produktfeed generieren';
    
$l_feed_url         'Ihre Feed-URL für <strong>' $settings->name '</strong> lautet:';


// Spanish
} elseif (LANG == 'es') {

    
$l_language        'Idioma';
    
$l_languages        = array('cs' => 'Checo''da' => 'Danés''de' => 'Alemán''el' => 'Griego''en' => 'Inglés''es' => 'Español''fi' => 'Finlandés''fr' => 'Francés''it' => 'Italiano''ja' => 'Japonés''ko' => 'Coreano''nl' => 'Neerlandés''no' => 'Noruego''pl' => 'Polaco''pt' => 'Portugués''ro' => 'Rumano''ru' => 'Ruso''sv' => 'Sueco''tr' => 'Turco''zh' => 'Chino');
    
$l_generate_feed     'Generar feed de producto';
    
$l_feed_url         'Su <strong>' $settings->name '</strong> URL de feed es:';

// French
} elseif (LANG == 'fr') {

    
$l_language        'Langue';
    
$l_languages        = array('cs' => 'Tchèque''da' => 'Danois''de' => 'Allemand''el' => 'Grecque''en' => 'Anglais''es' => 'Espagnol''fi' => 'Finnois''fr' => 'Français''it' => 'Italien''ja' => 'Japonais''ko' => 'Coréen''nl' => 'Néerlandais''no' => 'Norvège''pl' => 'Polonais''pt' => 'Portugais''ro' => 'Roumain''ru' => 'Russe''sv' => 'Suédois''tr' => 'Turc''zh' => 'Chinois');
    
$l_generate_feed     'Générer le flux de produits';
    
$l_feed_url         'Votre URL de flux <strong>' $settings->name '</strong> est la suivante:';

// Dutch
} elseif (LANG == 'nl') {

    
$l_language         'Taal';
    
$l_languages         = array('cs' => 'Tsjechisch''da' => 'Deens''de' => 'Duits''el' => 'Grieks''en' => 'Engels''es' => 'Spaans''fi' => 'Fins''fr' => 'Frans''it' => 'Italiaans''ja' => 'Japans''ko' => 'Koreaans''nl' => 'Nederlands''no' => 'Noors''pl' => 'Pools''pt' => 'Portugees''ro' => 'Roemeens''ru' => 'Russisch''sv' => 'Zweeds''tr' => 'Turks''zh' => 'Chinees');
    
$l_generate_feed     'Productfeed genereren';
    
$l_feed_url 'Uw <strong>' $settings->name '</strong> feed URL is:';

// Norwegian
} elseif (LANG == 'no') {

    
$l_language        'Språk';
    
$l_languages        = array('cs' => 'Tsjekkisk''da' => 'Danske''de' => 'Tysk''el' => 'Gresk''en' => 'Engelsk''es' => 'Spansk''fi' => 'Finske''fr' => 'Fransk''it' => 'Italiensk''ja' => 'Japansk''ko' => 'Koreansk''nl' => 'Nederlandsk''no' => 'Norsk''pl' => 'Polsk''pt' => 'Portugisisk''ro' => 'Rumensk''ru' => 'Russiske''sv' => 'Svenske''tr' => 'Turkish''zh' => 'Kinesisk');
    
$l_generate_feed     'Generer produktmating';
    
$l_feed_url         'Din <strong>' $settings->name '</strong> feed-nettadresse er:';

// Swedish
} elseif (LANG == 'sv') {

    
$l_language        'Språk';
    
$l_languages        = array('cs' => 'Tjeckisk''da' => 'Danska''de' => 'Tyska''el' => 'Grekiska''en' => 'Engelska''es' => 'Spanska''fi' => 'Finska''fr' => 'Franska''it' => 'Italienska''ja' => 'Japansk''ko' => 'koreansk''nl' => 'Nederländska''no' => 'Norska''pl' => 'Polska''pt' => 'Portugisiska''ro' => 'Rumänska''ru' => 'Ryska''sv' => 'Svenska''tr' => 'Turkiska''zh' => 'Kinesisk');
    
$l_generate_feed     'Generera produktmatning';
    
$l_feed_url         'Din <strong>' $settings->name '</strong> matningsadress är:';

// English by default
} else {

    
$l_language 'Language';
    
$l_languages = array('cs' => 'Czech''da' => 'Danish''de' => 'German''el' => 'Greek''en' => 'English''es' => 'Spanish''fi' => 'Finnish''fr' => 'French''it' => 'Italian''ja' => 'Japanese''ko' => 'Korean''nl' => 'Dutch''no' => 'Norwegian''pl' => 'Polish''pt' => 'Portuguese''ro' => 'Romanian''ru' => 'Russian''sv' => 'Swedish''tr' => 'Turkish''zh' => 'Chinese');
    
$l_generate_feed     'Generate product feed';
    
$l_feed_url         'Your <strong>' $settings->name '</strong> feed URL is:';
}

/*--------------------------------
    Block 4: Productfeed form
-------------------------------*/

echo '<!DOCTYPE html><html lang="en"><head><title>' $settings->name '</title><meta charset="utf-8">' .
    
'<link rel="stylesheet" href="style.css"></head>' .
    
'<body><main><h1>' $settings->name '</h1>';

// Show feed URL
if (isset($_POST['shop_id']) && SHOP_ID) {

    
// Create a token for this feed so the URL cannot be guessed
    
$feedurl 'https://' $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_URI'] .
        
'?shop_id=' SHOP_ID '&lang=' LANG '&token=' sha1(SHOP_ID LANG 'roor8weiChait0gai');
    echo 
'<p>' $l_feed_url '<br><a href="' $feedurl '" target="_blank">' $feedurl '</a></p>';

// Show generate feed form
} else {
    echo 
'<form method="POST"><table>';

    
// Shop ID
    
if (SHOP_ID) {
        echo 
'<input type="hidden" name="shop_id" value="' SHOP_ID '">';
    } else {
        echo 
'<tr><td>Shop ID</td><td><input type="text" name="shop_id" size="6"></td></tr>';
    }

    
// Language
    
echo '<tr><td>' $l_language '</td><td><select name="lang">';
    
asort($l_languages);
    foreach (
$l_languages as $l => $l_name) {
        echo 
'<option value="' $l '"' . ($l == $lang ' selected' '') . '>' $l_name '</option>';
    }
    echo 
'</select></td></tr>';

    
// Submit form
    
echo '<tr><td></td><td><input type="submit" name="submit" value="' $l_generate_feed '"></td></tr>' .
        
'</table></form>';
}

echo 
'</main></body></html>';

/*--------------------------------
    Block X: Functions
-------------------------------*/

function displayProducts($appdata) {

    
/* Google product feed:
        https://support.google.com/merchants/answer/7052112?hl=en
    */

    
foreach ($appdata['products'] as $p) {

        if (!isset(
$p['category'])) {
            
$p['category'] = '';
        }

        
//echo "<item>\n";
                
        // Image
        //echo '<additional_image_link>' . $p['image'] . "</additional_image_link>\n

        // ID (mandatory)
        
echo "<item>\n<id><![CDATA[" $p['productID'] . "]]></id>\n<availability>" .

        
// Availability (Mandatory)
            
$p['status'] . "</availability>\n<brand><![CDATA[" .

        
// Brand (Mandatory)
            
$p['category'] . "]]></brand>\n" .

        
// Color
            
($p['colors'] ? '<color>' $p['colors'] . "</color>\n" '') .

        
// Condition (Recommended)
            
'<condition>' $p['itemCondition'] . "</condition>\n<title><![CDATA[" .

        
// Title (Mandatory)
            
$p['name'] . "]]></title>\n<description><![CDATA[" .

        
// Description (Mandatory)
            
preg_replace('/[^(\x20-\x7F)]*/'''$p['description']) . "]]></description>\n";

        
// EAN (Recommended)
        
if ($p['ean']) {
            echo 
'<ean>' $p['ean'] . "</ean>\n";
        }

        
// Product code
        //echo '<unique_id><![CDATA[' . $p['productID'] . "]]></unique_id>\n<size>" .

        // Size (Mandatory)
        
echo '<size>' $p['weight'] . "</size>\n<image_link>" .

        
// Image link (Mandatory)
            
$p['image'] . "</image_link>\n";

        
// Additional image links
        
for ($i 2$i <= 5$i++) {
            if (isset(
$p['image' $i])) {
                echo 
'<additional_image_link>' $p['image' $i] . "</additional_image_link>\n";
            }
        }

        
// Purchase price
        
if ($p['purchase_price']) {
            echo 
'<cost_of_goods_sold>' $p['purchase_price'] . "</cost_of_goods_sold>\n";
        }

        
// Price (Mandatory)
        
echo '<price>' . ($p['old_price'] ? $p['old_price'] : $p['price']) . "</price>\n<sale_price>" .

        
// Sale price (Mandatory)
            
$p['price'] . "</sale_price>\n<link>" .

        
// Link (Mandatory)
            
$p['url'] . "</link>\n<product_type><![CDATA[" .

        
// Breadcrumb (Mandatory)
            
$p['category'] . "]]></product_type>\n<stock>" .

        
// Stock (Recommended)
            
$p['stock'] . "</stock>\n";



        
/* Shipping costs

                    [shipping] => Array
                        (
                            [Worldwide] => Array
                                (
                                    [Pickup in the store] => 0
                                    [Pickup at collection point] => 0
                                )

                            [BE] => Array
                                (
                                    [Standard delivery] => 10
                                )

                            [NL] => Array
                                (
                                    [Collect on delivery] => 5
                                )

                        )

        */
        
if (isset($p['shipping']) && $p['shipping']) {

            
$price_set false;
            foreach (
$p['shipping'] as $country => $methods) {

                
// Try to set a shipping price
                
foreach ($methods as $method => $price) {

                    if (
$price_set) {
                        break;
                    }

                    if (
$method != 'Pickup in the store') {
                        echo 
'<shipping_price>' $price "</shipping_price>\n"// ' ' . $appdata['webshop']['currency']
                        
$price_set true;
                        break;
                    }
                }
            }
        }


        echo 
"</item>\n";

    }
// displayProducts()

// Check for a valid shop id
function checkId($id) {
    return 
filter_var($idFILTER_VALIDATE_INT, array('options' => array('min_range' => 1'max_range' => 1000000000)));
// checkId()
?>
body    { margin: 0; font-family: Helvetica, Arial, sans-serif; color: #333; background-color: #e4e4e4; }
main    { margin: 0 auto; margin-top: 30px; margin-bottom: 30px; padding: 20px; width: 760px; background-color: #fff; border-radius: 8px; border: 1px solid #ccc; box-shadow: 5px 5px 5px #888; }
#logo    { float: left; margin-bottom: 10px; }
h1    { font-size: 22px; margin: 0; padding: 0; color: #06c; margin-bottom: 80px; }
hr    { clear: both; border-style: solid; border-width: 1px 0 0 0; border-color: #e4e4e4; margin: 20px 0; }

/*--------------------------------
     Buttons
-------------------------------*/
a.glowbutton, input[type="submit"], input[type="button"]    {
    white-space: nowrap; display: inline-block; min-width: 210px; margin: 0 0 10px 0; padding: 0;
    text-decoration: none; text-align: center;
    color: #fff; background-color: #06c; border: 0; border-radius: 3px;
    line-height: 33px; height: 33px; font-weight: bold; font-size: 0.9em;
    -webkit-appearance: none; -moz-appearance: none; appearance: none;
    transition: background 0.4s;
}

a.glowbutton:hover, input[type="submit"]:hover    {
    background-color: #06f; text-decoration: none;
}

/*--------------------------------
     Fancy
-------------------------------*/

a    { color: #06c; text-decoration: none; }
a:hover    { text-decoration: underline; }
h2    { font-size: 1.6em; }
h3    { font-size: 1.4em; }
h4    { font-size: 1.1em; color: #666; }
.blue    { color: #06c; }
.orange { color: #f60; }
.code    { font-family: monospace; color: #090; }
.code a    { font-weight: bold; color: #090; }
.warn    { background-color: #fc0; padding: 15px 5px; text-align: center; border-radius: 5px; font-size: 0.9em; box-shadow: 2px 2px 2px #888; }

/*--------------------------------
     Forms
-------------------------------*/
textarea                    { width: 99%; height: 200px; font-size: 1.2em; color: #666; }
input, select, textarea                { border: 1px solid #ccc; border-radius: 3px; margin: 0px 0 8px 0; padding: 8px; }
input:focus, textarea:focus            { background-color: #eee; }
input[type="checkbox"], input[type="radio"]    { border: 0;}
input[type="submit"], input[type="button"]    { cursor: pointer; float: right; margin: 10px 0 0 0;  }
form table                    { width: 100%; }
form table td:first-child            { width: 50%; }
/*--------------------------------
     Responsive
-------------------------------*/
@media all and (max-width: 790px) {
    main        { max-width: calc(100vw - 20px); margin: 0; padding: 20px 10px; border: none; border-radius: 0; }
    textarea    { width: 97%; }
}

Provedor de Serviços de Pagamento

Esta é a forma de conectar um Provedor de Serviços de Pagamento (PSP) ao EasyWebshop.

A conexão precisa ser instalada pelo comerciante e os métodos de pagamento precisam ser conectados selecionando-os.

Depois de o cliente ter feito um pedido na loja online, aparece a página com o botão Pagar agora. Este botão submete um formulário HTML.

  1. A sua conexão recebe os dados POST deste formulário, que inclui o código do pedido. Com o Token de Conexão API, pode recuperar com segurança os dados do pedido necessários para processar o pagamento.
  2. Conecte-se à API do PSP e envie os dados do pedido.
  3. Se o pagamento for executado com sucesso, o provedor de serviços de pagamento solicita o arquivo report.php, que atualiza o estado do pedido na loja online para Pagamento recebido.
  4. O cliente é redirecionado para o URL de pagamento bem-sucedido ou para o URL de pagamento falhou, dependendo do sucesso ou falha do pagamento.
  5. Se vários métodos de pagamento estiverem definidos, o cliente pode escolher outro método de pagamento após um pagamento falhar.
  • settings.xml
  • easywebshop.php
  • index.php
  • report.php
  • style.css
<?xml version="1.0" encoding="UTF-8" ?> <settings> <name>DemoPSP</name> <logo>demo-psp.png</logo> <type>psp</type> <url>https://www.webshopdata.com/app/easywebshop-psp/index.php</url> <parameter name="PSP API key">123456789</parameter> </settings> <?php
/*
   EasyWebshop API Connector
   Documentation: https://easywebshop.com/doc/api
*/
function easyApp($data '') {

    
// Set your API Connection Token (not API Token!) here
    
$conn_token 'YOUR_API_TOKEN';

    
// No need to change anything below. You can watch, but you can't touch!
    
if (!isset($_REQUEST['shop_id']) || !$_REQUEST['shop_id'] ||
        !
filter_var($_REQUEST['shop_id'], FILTER_VALIDATE_INT,
        array(
'options' => array('min_range' => 1'max_range' => 1000000000)))) {
        die(
'Error: $_REQUEST[\'shop_id\'] not set');
    }

    
$settings = new SimpleXMLElement(file_get_contents(dirname(__FILE__) . '/settings.xml'));
    
$method      = isset($data['function']) && substr($data['function'], 03) == 'set' 'PUT' 'GET';
    
$format   = isset($data['format']) && in_array(strtolower($data['format']), array('json''xml')) ?
            
strtolower($data['format']) : 'array';
    
$data     is_array($data) ? ($method == 'GET' http_build_query($data) : json_encode($data)) : '';
    
$apiurl      'https://easywebshop.jan/api/conn/' $_REQUEST['shop_id'] . '/' $settings->name .
            (
$method == 'GET' && $data '?' $data ''); // HTTPS only
    
$opts     = array(
        
'http' => array(
            
'header' =>    "Content-Type: application/x-www-form-urlencoded\r\n" .
                    
'Authorization: Bearer ' .
                    
hash('sha512'$_REQUEST['shop_id'] . $settings->name hash('sha256'$conn_token) . $data) . "\r\n",
            
'method' =>    $method,
            
'ignore_errors' => true),
        
'ssl'  => array('verify_peer' => false'verify_peer_name' => false)
        );
    if (
$method == 'PUT') { $opts['http']['content'] = $data; }
    
$response file_get_contents($apiurlfalsestream_context_create($opts));
    
$appdata  $format == 'array' json_decode($responsetrue) : $response;

    
// Output log - only in debug mode
    
if (defined('DEBUG') && DEBUG) {
        echo 
"<pre>-- easywebshop.php " $settings->name "\n> Accessing API: " .
            
$apiurl "\n> API response: " $response "--\n</pre>";
    }

    return 
$appdata// this can be a PHP array, JSON or XML, depending on the $data['format'] value

// easyApp()
?>
<?php
/*--------------------------------------------
 * This page redirects a customer to the PSP

    Install link:
    https://easywebshop.com/software/connections?install=https://www.webshopdata.com/app/easywebshop-psp

    Block 1: Variables
    Block 2: Languages
    Block 3: PSP API code
    Block 4: Start page
    Block X: Functions

--------------------------------------------*/

/*--------------------------------
    Block 1: Variables
-------------------------------*/

// Debug mode for testing, set to false in production
define('DEBUG',    true);

// Use test data
define('TEST'true);

// Use for testing without POST vars from payment form
if (TEST) {
    
$_REQUEST    = array('shop_id' => 71911'ordercode' => '20250-71911-19417-18497''lang' => 'en');
}

define('SHOP_ID', isset($_REQUEST['shop_id']) && checkId($_REQUEST['shop_id']) ? $_REQUEST['shop_id'] : 0);
define('ORDERCODE', isset($_REQUEST['ordercode']) && checkOrderCode($_REQUEST['ordercode']) ? $_REQUEST['ordercode'] : '');

$error        '';

if (!
ORDERCODE) {
    
$error    'Invalid Order code';
}

// Easywebshop API connector
require        'easywebshop.php';
$appdata    easyApp(array('ordercode' => ORDERCODE));
$settings    = (array)simplexml_load_file('settings.xml');
$log        "REQUEST variables:\n\n" print_r($_REQUESTtrue) .
        
"\n\nAppdata: \n\n" print_r($appdatatrue) . "\n\nSettings: \n\n" print_r($settingstrue);

// URL requested by PSP on payment status update
$reporturl    'https://' $_SERVER['HTTP_HOST'] .
            
substr($_SERVER['DOCUMENT_URI'], 0strrpos($_SERVER['DOCUMENT_URI'], '/')) .
            
'/report.php?shop_id=' SHOP_ID;

/*--------------------------------
    Block 2: Languages
-------------------------------*/

// Dutch
if ($_REQUEST['lang'] == 'nl') {

    
$l_paymentok        'Betaling geslaagd';
    
$l_paymentfail        'Betaling mislukt';

// German
} elseif ($_REQUEST['lang'] == 'de') {

    
$l_paymentok        'Zahlung erfolgreich';
    
$l_paymentfail        'Zahlung fehlgeschlagen';

// Spanish
} elseif ($_REQUEST['lang'] == 'es') {

    
$l_paymentok        'Pago efectuado';
    
$l_paymentfail        'Pago fallido';

// French
} elseif ($_REQUEST['lang'] == 'fr') {

    
$l_paymentok        'Paiement réussi';
    
$l_paymentfail        'Échec du paiement';

// Default to English
} else {

    
$l_paymentok        'Payment successful';
    
$l_paymentfail        'Payment failed';
}

/*--------------------------------
    Block 3: PSP API code
-------------------------------*/

/*--------------------------------
    Block 4: Start page
-------------------------------*/
echo '<!DOCTYPE html><html lang="en"><head><title>' $settings['name'] .
    
'</title><meta charset="utf-8"><link rel="stylesheet" href="style.css"></head>' .
    
'<body><main><p><img src="' $settings['logo'] . '" style="margin: 5px"></p>';

// Error message
if ($error) {
    echo 
'<p class="warn">' $error '</p>';
}

// Action buttons
if (isset($appdata['order']['code'])) {
    echo 
'<p class="leftbuttons"><a href="' $reporturl '&ordercode=' $appdata['order']['code'] .
        
'" class="glowbutton" style="background: #5fc331">' $l_paymentok '</a><a href="' .
        
$appdata['webshop']['paymentfailed'] . '" class="glowbutton" style="background: #c00">' .
        
$l_paymentfail '</a></p>';


    
// Back to webshop
    
echo '<hr><p><a href="' $appdata['webshop']['url'] . '/payment/' $appdata['order']['code'] .
        
'" class="glowbutton">' $appdata['webshop']['name'] . '</a></p>';
}

// Debug output -- you can find all $_POST, $appdata and $settings variables here
if (DEBUG) {
    echo 
'<h2>Debug log</h2><pre>' $log '</pre>';
}

echo 
'</main></body></html>';

/*--------------------------------
    Block X: Functions
-------------------------------*/

// Check for a valid shop id
function checkId($id) {
    return 
filter_var($idFILTER_VALIDATE_INT, array('options' => array('min_range' => 1'max_range' => 1000000000)));
// checkId()

function checkOrderCode($code) {
    return 
strlen($code) == 23 && preg_match('/\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d/'$code);
// checkOrderCode()
?>
<?php
/*--------------------------------------------
 * This page is usually requested "under water" by the PSP and updates the payment status

    Block 1: Variables for EasyWebshop API
    Block 2: PSP API code
    Block 3: Set order paid
    Block X: Functions
--------------------------------------------*/

header("Content-Type: text/plain; charset=utf-8");

/*--------------------------------
    Block 1: Variables
-------------------------------*/
define('DEBUG',        true);        // Debug mode for testing, set to false in production
define('DEBUG_EMAIL',    'test@ew.ms');    // Send an email with debug log
$error        '';

// Easywebshop API connector
require 'easywebshop.php';
$appdata    easyApp(); // PSP must send shop_id in GET or POST
$settings    = (array)simplexml_load_file('settings.xml');
$log        $settings['name'] . " report.php\n\n" .
            
'X forwarded: ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
            
$_SERVER['HTTP_X_FORWARDED_FOR'] : '') .
            
', IP: ' $_SERVER['REMOTE_ADDR'] .
            
"\n\nGET variables:\n\n" print_r($_GETtrue) .
            
"\n\nPOST variables:\n\n" print_r($_POSTtrue) .
            
"\n\nAppdata: \n\n" print_r($appdatatrue) .
            
"\n\nSettings: \n\n" print_r($settingstrue);

// report.php needed variables
$order_code    ''// PSP must send order_code in GET or POST
$order_paid    false// Set to TRUE if payment is successful

/*--------------------------------
    Block 2: PSP API code
-------------------------------*/

// Check if ordercode is correct
if (isset($_REQUEST['ordercode']) && strlen($_REQUEST['ordercode']) == 23 &&
    
preg_match('/\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d/'$_REQUEST['ordercode'])) {
    
$order_code $_REQUEST['ordercode']; // this variable is safe now

} else {
    
$error 'Invalid order code';
}

// Check if correct GET or POST variables are received
if (!$error) {

    
/* Here you can check if the payment status update request is valid:
        - Calculate a hash
        - Make a request to the PSP API
    */

    // Calculate hash
    
if (true) {
        
$order_paid true;
    }

    
/* Check payment status with PSP
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, '');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'api_key: ' . $appdata['parameter1'],
        'Accept: application/json',
        'Content-Type: application/json'
        )
    );
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    if (DEBUG) {
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_STDERR, $verbose = fopen('php://temp', 'rw+'));
        curl_setopt($ch, CURLOPT_FILETIME, true);
    }

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
    }
    curl_close($ch);

    if (DEBUG) {
        $log .= (isset($error_msg) ? "\n\nHTTP Log:\n" . print_r($error_msg, true) . "\n\n" : '') .
                "Verbose information:\n" . !rewind($verbose) . stream_get_contents($verbose) . "\n\n" .
                print_r($response, true);
    }

    $response = json_decode($response, true);
    if ($response && isset($response['success']) && $response['success'] &&
        isset($response['data']['financial_status']) && $response['data']['financial_status'] == 'completed') {

        $order_paid = true;
        $order_code = $response['data']['var2'];

    }
    */

// Error found
} elseif (DEBUG) {
    
mailLog($log "\n\nErrors:\n\n" $error);

// no errors


/*--------------------------------
    Block 3: Set order paid
-------------------------------*/
if ($order_paid) {

    
// The connector needs $_REQUEST['shop_id'] and $_REQUEST['ordercode'] for changing the order status
    
$pmdata        easyApp(array('function' => 'setOrderPaid''ordercode' => $order_code));
    
$log        .= "\n\nOrder update result:\n\n" print_r($pmdatatrue);
}

if (
DEBUG) {
    echo 
$log;
    
mailLog($log);
}

// Optional: redirect if customer comes on this page directly
header('Location: ' $appdata['webshop']['paymentok']);

// Acknowledge we have successfully received a valid notification by returning OK
echo 'OK';

/*--------------------------------
    Block X: Functions
-------------------------------*/

// Send mail
function mailLog($log) {

    
$subject preg_split('#\r?\n#'ltrim($log), 2)[0]; // get first line

    
mail(DEBUG_EMAIL$subject$log "\n\n" .

        
// Username
        
(isset($_SERVER['PHP_AUTH_USER']) ? 'User: ' $_SERVER['PHP_AUTH_USER'] . "\n" '') .

        
// IP Address
        
(isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] . "\n" '') .
        
$_SERVER['REMOTE_ADDR']);
// mailLog()

die;
?>
body    { margin: 0; font-family: Helvetica, Arial, sans-serif; color: #333; background-color: #E4E4E4; }
main {
    margin: 0 auto; margin-top: 30px; margin-bottom: 30px; padding: 20px; width: 760px;
    background-color: #FFF; border-radius: 8px; border: 1px solid #CCC; box-shadow: 5px 5px 5px #888;
}
h1    { font-size: 22px; margin: 0; padding: 0; color: #06C; margin-bottom: 80px; }
hr    { clear: both; border-style: solid; border-width: 1px 0 0 0; border-color: #E4E4E4; margin: 20px 0; }

/*--------------------------------
     Navigation
-------------------------------*/
nav    { margin: 40px 0; clear: both; }
nav a    {
    display: block; width: 70%; margin: 30px auto; padding: 20px; vertical-align: top;
    border: 1px solid #E4E4E4; box-shadow: 2px 2px 2px #888;
    /*border-style: solid; border-width: 0 0 1px 0; border-color: #CCC;*/
    text-decoration: none; color: #06C; font-size: 20px; font-weight: bold;
    transition: background 0.4s;
}

nav a:hover { background: #EEE; }
nav img    { display: inline-block; float: left; width: 100px; height: 100px; vertical-align: top; }
nav span{ display: inline-block; line-height: 100px; text-indent: 30px; }
.langselect { font-size: 0.8em; font-weight: bold; }

/*--------------------------------
     Buttons
-------------------------------*/
a.glowbutton, input[type="submit"], input[type="button"]    {
    white-space: nowrap; display: inline-block; min-width: 210px; margin: 0 0 10px 0; padding: 0;
    text-decoration: none; text-align: center;
    color: #FFF; background-color: #00abee; border: 0; border-radius: 6px;
    line-height: 33px; height: 33px; font-weight: bold; font-size: 0.9em;
    -webkit-appearance: none; -moz-appearance: none; appearance: none;
    transition: background 0.4s;
}

a.glowbutton:hover, input[type="submit"]:hover    {
    background-color: #0085c4; text-decoration: none;
}

.leftbuttons a        { margin-right: 10px !important; }

/*--------------------------------
     Fancy
-------------------------------*/

a    { color: #06C; text-decoration: none; }
a:hover    { text-decoration: underline; }
h2    { font-size: 1.6em; }
h3    { font-size: 1.4em; }
h4    { font-size: 1.1em; color: #666; }
.blue    { color: #06C; }
.orange { color: #F60; }
.code    { font-family: monospace; color: #090; }
.code a    { font-weight: bold; color: #090; }
.warn    {
    background-color: #FC0; padding: 15px 5px; text-align: center;
    border-radius: 5px; font-size: 0.9em; box-shadow: 2px 2px 2px #888;
}

/*--------------------------------
     Forms
-------------------------------*/
textarea                    { width: 99%; height: 200px; font-size: 1.2em; color: #666; }
input, select, textarea                { border: 1px solid #CCC; border-radius: 3px; padding: 3px; }
input:focus, textarea:focus            { background-color: #EEE; }
input[type="checkbox"], input[type="radio"]    { border: 0;}
input[type="submit"], input[type="button"]    { cursor: pointer; float: right; margin: 10px 0 0 0;  }
form table                    { width: 100%; }
form table td:first-child            { width: 50%; }

/*--------------------------------
     Responsive
-------------------------------*/
@media all and (max-width: 790px) {
    main        { width: 100%; margin: 0; padding: 20px 0; border: none; border-radius: 0; }
    nav a        { margin: 0 auto; margin-top: 20px; margin-bottom: 20px; }
    textarea    { width: 97%; }
}

Copiar

Instalação de conexões

Altere o URL no exemplo para o URL da sua conexão. O nosso back-end lê automaticamente o seu arquivo settings.xml e solicita ao utilizador que introduza os dados necessários.

<a href="https://easywebshop.com/software/connections/?install=https://www.webshopdata.com/app/easywebshop-psp">Install</a>

Pode adicionar o logotipo EasyWebshop ao seu site quando a conexão estiver pronta.

Logotipo

Resolução de problemas

Aperfeiçoamos a API EasyWebshop para torná-la o mais fácil possível. Também oferecemos um serviço de suporte técnico de alta qualidade com assistência opcional por um desenvolvedor para questões mais técnicas. O propósito da API é que possa conectar-se a outras plataformas e aplicações. Estas podem não ter uma API fácil de usar nem o nível de suporte que oferecemos. Lembre-se, ao contactar-nos, só podemos fornecer ajuda para o EasyWebshop e não para aplicações externas.

Se precisar de ajuda com linguagens de programação, é melhor ler as suas páginas de documentação. A maioria está muito bem documentada. Possivelmente pode usar IA para gerar o código para a sua conexão, mas por favor não espere que o nosso suporte corrija erros no seu código.

Durante o Verão de design web, desenvolvemos conexões personalizadas para os nossos utilizadores. Estas conexões são feitas por desenvolvedores experientes. Se precisar de uma conexão ou funcionalidade complexa, esta é a forma de proceder.

Estou recebendo o erro: "Hash de integridade de dados inválido"
  • Verifique se o Token de Conexão API (não um Token API regular) está definido no arquivo easywebshop.php
  • Verifique se o URL está corretamente definido
  • Verifique se a conexão está instalada por uma loja online

Links úteis

As tecnologias que a nossa API utiliza foram escolhidas pelas seguintes razões:

  • Fácil de implementar
  • Transferência segura de dados via HTTPS (sem mais conexões FTP inseguras)
  • Comunicação em tempo real
  • Não são necessários servidores adicionais ou bases de dados extras
  • Escalável para volumes maiores de dados
  • Pode ser utilizada com qualquer plataforma, framework e linguagem de programação
  • Sem problemas com firewalls
  • Utiliza padrões e práticas gerais de REST, JSON, JSON-LD, XML e HTTPS
  • Autenticação Bearer com permissões personalizadas
  • Codificação UTF-8

Se quiser usar curl em PHP, precisa instalar a extensão php-curl. Em sistemas baseados em Debian (incluindo Ubuntu), use o seguinte comando:

sudo apt-get install php-curl

Rolar para o topo

Este site não utiliza cookies de rastreamento nem vende dados pessoais.Condições de vendaPolítica de Privacidade 2009 ‑ 2025 EasyWebshop