Giter Site home page Giter Site logo

ozon-api-client's Introduction

Ozon Seller API Client

A Ozon Seller API client written in Golang

Coverage Status example workflow

Ozon is a marketplace for small and medium enterprises to launch and grow their businesses in Russia.

Read full documentation

You can check list of supported endpoints

How to start

API

Get Client-Id and Api-Key in your seller profile here

Just add dependency to your project and you're ready to go.

go get github.com/diphantxm/ozon-api-client

A simple example on how to use this library:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"github.com/diphantxm/ozon-api-client/ozon"
)

func main() {
	// Create a client with your Client-Id and Api-Key
	// [Documentation]: https://docs.ozon.ru/api/seller/en/#tag/Auth
	opts := []ozon.ClientOption{
		ozon.WithAPIKey("api-key"),
		ozon.WithClientId("client-id"),
	}
	c := ozon.NewClient(opts...)

	// Send request with parameters
	resp, err := client.Products().GetProductDetails(context.Background(), &ozon.GetProductDetailsParams{
		ProductId: 123456789,
	})
	if err != nil || resp.StatusCode != http.StatusOK {
		log.Fatalf("error when getting product details: %s", err)
	}

	// Do some stuff
	for _, d := range resp.Result.Barcodes {
		fmt.Printf("Barcode %s\n", d)
	}
}

Notifications

Ozon can send push-notifications to your REST server. There is an implementation of REST server that handles notifications in this library.

Official documentation

How to use:

package main

import (
	"log"

	"github.com/diphantxm/ozon-api-client/ozon/notifications"
)

func main() {
	// Create server
	port := 5000
	server := notifications.NewNotificationServer(port)

	// Register handlers passing message type and handler itself
	server.Register(notifications.ChatClosedType, func(req interface{}) error {
		notification := req.(*notifications.ChatClosed)

		// Do something with the notification here...
		log.Printf("chat %s has been closed\n", notification.ChatId)

		return nil
	})

	// Run server
	if err := server.Run(); err != nil {
		log.Printf("error while running notification server: %s", err)
	}
}

Contribution

If you need some endpoints ASAP, create an issue and list all the endpoints. I will add them to library soon.

Or you can implement them and contribute to the project. Contribution to the project is welcome.

ozon-api-client's People

Contributors

antares-me avatar diphantxm avatar zloyleshiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ozon-api-client's Issues

invalid readme signature

привет! обновляю либу и в инит клиента добавился интересный момент, не описанный в ридми
image

сигнатура отличается от того что в readme

лечится так
client := ozon.NewClient(http.DefaultClient, "my-client-id", "my-api-key")

паправьте плз или readme или инициализацию клиента так, чтобы не надо было в него подкладывать дефолтный клиент (тк это выглядит как минимум странно)

Define all struct types in Responses

Now we have anonymous structs in all responses:

type ListCertifiedBrandsResponse struct {
	core.CommonResponse

	// Method result
	Result struct {
		// Certified brands details
		BrandCertification []struct {
			...
		} `json:"brand_certification"`

		// Total number of brands
		Total int64 `json:"total"`
	} `json:"result"`
}

This is not very convenient, because all real data is inside Result struct and it would be wise to pass specific XxxResult into functions:

func DoSomething(res XxxResult) {
...
}

func main() {
        resp, _ := client.Finance().GetTotalTransactionsSum(...)
        DoSomething(resp.Result)
}

And we cannot do that rn because XxxResult is anonymous type

CreateOrUpdateProduct execute successfully but Ozon says Key fields missing reopen plz

send a whole CreateOrUpdateProductParams object :
{Items:[{"attributes":[{"complex_id":0,"id":4384,"values":[{"dictrionary_value_id":0,"value":"Упаковка, комплект ламп, гарантийний талон."}]},{"complex_id":0,"id":8229,"values":[{"dictrionary_value_id":367249974,"value":"Лампа автомобильная"}]},{"complex_id":0,"id":7236,"values":[{"dictrionary_value_id":0,"value":"LZ8ULTRA"}]},{"complex_id":0,"id":8383,"values":[{"dictrionary_value_id":0,"value":"13000"}]},{"complex_id":0,"id":9024,"values":[{"dictrionary_value_id":0,"value":"91132"}]},{"complex_id":0,"id":9048,"values":[{"dictrionary_value_id":0,"value":"Z8 ULTRA NANO-LED"}]},{"complex_id":0,"id":7199,"values":[{"dictrionary_value_id":61753,"value":"Алюминий"}]},{"complex_id":0,"id":4180,"values":[{"dictrionary_value_id":0,"value":"LED лампа Z8 Ultra nano-led с тройной системой охлаждения/100w/5000k/комплект, для автомобильных фар/ HB4"}]},{"complex_id":0,"id":22241,"values":[{"dictrionary_value_id":971405507,"value":"Для ближнего/дальнего света"}]},{"complex_id":0,"id":4191,"values":[{"dictrionary_value_id":0,"value":"Ручная сборка LED-лампы, высокотехнологичные диоды, инновационная система охлаждения.\u003cbr/\u003e\u003cbr/\u003eМодель Z8 имеет тройную систему охлаждения \u003cbr/\u003e\u003cbr/\u003e-Модель: Z8\u003cbr/\u003e\u003cbr/\u003e-Мощность: 100W\u003cbr/\u003e\u003cbr/\u003e-Световой поток: 13000lumens\u003cbr/\u003e\u003cbr/\u003e-Цветовая температура: 5000K\u003cbr/\u003e\u003cbr/\u003e-Чип: CSP+USA\u003cbr/\u003e\u003cbr/\u003e-Материал: Авиационный алюминий\u003cbr/\u003e\u003cbr/\u003e-Влагозащита: IP68\u003cbr/\u003e\u003cbr/\u003e-Гарантия: 24 месяца\u003cbr/\u003e\u003cbr/\u003eПодключение: штатное\u003cbr/\u003e\u003cbr/\u003eЦена за комплект\u003cbr/\u003e\u003cbr/\u003eПремиум сегмент\u003cbr/\u003e\u003cbr/\u003e- Прирост света на 90%;\u003cbr/\u003e\u003cbr/\u003e- Штатная установка;\u003cbr/\u003e\u003cbr/\u003e- Подходит для установки ближнего, дальнего;\u003cbr/\u003e\u003cbr/\u003e- Минимальное нагревание за счет тройного охлаждения;\u003cbr/\u003e\u003cbr/\u003e- Мы предоставляем гарантию 2 года, по сравнению с другими компаниями;\u003cbr/\u003e\u003cbr/\u003e- Модель Z8 от производителя "LEDOVЫЙ" имеет более качественную сборку, что дает возможность служить гораздо дольше, чем бюджетный аналог.\u003cbr/\u003e\u003cbr/\u003eВнимание! При использовании ламп в фарах без крышек (если предусмотрено заводом изготовителем), гарантия не распространяется.\u003cbr/\u003e\u003cbr/\u003eОбратите внимание, что мы не гарантируем 100% совместимость ламп с вашим автомобилем. В редком случае лампы могут работать некорректно. Встроенная обманка не способна обойти все бортовые компьютеры. Это не является гарантийным событием и лампы можно вернуть в магазин как не подошедший товар. Также для обхода требовательного БК мы рекомендуем оснащать лампы специальной обманкой\u003cbr/\u003e\u003cbr/\u003eВ Головной свет применяется кулерные модели (активное охлаждение)\u003cbr/\u003e\u003cbr/\u003eДля противотуманных фар радиаторные модели (пассивное охлаждение)\u003cbr/\u003e\u003cbr/\u003eLED Лампа нового поколения Z8 Ultra благодаря своему исполнению в плане конструктива и инженерных решений это лучший вариант качественных ламп с оправданной ценой в отличии от именитых конкурентов. Срок службы светодиодной лампы может составлять до 10 лет, а его энергопотребление во много раз ниже «классики»\u003cbr/\u003e\u003cbr/\u003eВ автомобилях все эти преимущества особенно актуальны, так как чем ниже потребление тока, тем заметней снижается нагрузка на аккумулятор. Да и менять перегоревшие лампы придётся гораздо реже.\u003cbr/\u003e\u003cbr/\u003eПостоянный прирост на 100+ % за счёт диодных ламп Z8 Ultra, почему именно постоянные? Потому что наша led лампа обладает 3-ой системой охлаждения, первое — это активный кулер, который крутится внутри радиатора, второе - 2 алюминиевые трубки (по всей длине диодной платы), в которых циркулирует жидкость, охлаждая дорожку, на которой расположены диоды. И третье охлаждение — это алюминий, который отводит тепло от диодов. Все эти свойства обеспечивают диоду постоянную рабочую температуру за счёт чего он не нагревается и не теряет своих свойств, светит ярче и работают дольше. У нашей модели Z8 Ultra максимальная гарантия - 2 года. \u003cbr/\u003e\u003cbr/\u003eДиодные лампы для авто под разные автомобили имеют свои цоколя, к примеру лед лампы h7\u003cbr/\u003e\u003cbr/\u003eили лед лампы h4. У нас вы найдёте практический весь спектр цоколей на все представленные модели.\u003cbr/\u003e\u003cbr/\u003eЛампа автомобильная может располагаться и в головном свете, дальний и ближний.\u003cbr/\u003e\u003cbr/\u003eЛампочки светодиодные так же устанавливаются в салонном освещении, в багажнике, в освещении номерных знаков и так далее.\u003cbr/\u003e\u003cbr/\u003eВ нашем магазине LEDOVЫЙ вы найдёте любой тип led ламп от головного света до, к примеру линзованные лед лампы, переходник для led ламп, колпачки для фар, би модули, линзы и любые лампочки в фары."}]},{"complex_id":0,"id":7206,"values":[{"dictrionary_value_id":41233,"value":"Легковые автомобили"},{"dictrionary_value_id":41240,"value":"Внедорожники"},{"dictrionary_value_id":41230,"value":"Грузовые автомобили и автобусы"},{"dictrionary_value_id":41232,"value":"Коммерческий транспорт"},{"dictrionary_value_id":41237,"value":"Снегоходы"},{"dictrionary_value_id":41234,"value":"Мотоциклы"},{"dictrionary_value_id":41231,"value":"Квадроциклы"}]},{"complex_id":0,"id":4385,"values":[{"dictrionary_value_id":0,"value":"24"}]},{"complex_id":0,"id":4400,"values":[{"dictrionary_value_id":40875,"value":"12 В"}]},{"complex_id":0,"id":6317,"values":[{"dictrionary_value_id":1896,"value":"Светодиодная"}]},{"complex_id":0,"id":6318,"values":[{"dictrionary_value_id":0,"value":"2"}]},{"complex_id":0,"id":4389,"values":[{"dictrionary_value_id":90296,"value":"Китай"}]},{"complex_id":0,"id":85,"values":[{"dictrionary_value_id":970888017,"value":"LEDOVЫЙ"}]},{"complex_id":0,"id":6319,"values":[{"dictrionary_value_id":0,"value":"100"}]},{"complex_id":0,"id":8386,"values":[{"dictrionary_value_id":0,"value":"5000"}]},{"complex_id":0,"id":11650,"values":[{"dictrionary_value_id":0,"value":"1"}]},{"complex_id":0,"id":10100,"values":[{"dictrionary_value_id":0,"value":"false"}]},{"complex_id":0,"id":11794,"values":[{"dictrionary_value_id":970860783,"value":"safe"}]},{"complex_id":0,"id":22074,"values":[{"dictrionary_value_id":0,"value":"false"}]},{"complex_id":0,"id":9790,"values":[{"dictrionary_value_id":0,"value":"false"}]},{"complex_id":0,"id":22232,"values":[{"dictrionary_value_id":971400201,"value":"8539520009 - Лампы светодиодные (led), прочие"}]},{"complex_id":0,"id":22387,"values":[{"dictrionary_value_id":971461138,"value":"Auto\u0026Moto/Авто и мото запчасти/Автомобильная оптика/Лампы и комплектующие"}]},{"complex_id":0,"id":22806,"values":[{"dictrionary_value_id":971400201,"value":"8539520009 - Лампы светодиодные (led), прочие"}]},{"complex_id":0,"id":9461,"values":[{"dictrionary_value_id":349823813,"value":"Лампы и комплектующие"}]},{"complex_id":0,"id":12978,"values":[{"dictrionary_value_id":970978730,"value":"HB4"}]},{"complex_id":0,"id":10015,"values":[{"dictrionary_value_id":0,"value":"false"}]}],"barcode":"","description_category_id":17028756,"color_image":"","complex_attributes":[{"attributes":[{"complex_id":100001,"id":21840,"values":[{"dictrionary_value_id":0,"value":"01G9C3B7R6DTV02TKV3XB51SZX"}]},{"complex_id":100001,"id":21838,"values":[{"dictrionary_value_id":0,"value":"https://cdn1.ozone.ru/s3/video/cover/01G9C3B7R6DTV02TKV3XB51SZX.jpg"}]},{"complex_id":100001,"id":21839,"values":[{"dictrionary_value_id":0,"value":"https://v.ozone.ru/vod/video-2/01G9C3B7R6DTV02TKV3XB51SZX/master.m3u8"}]},{"complex_id":100001,"id":21841,"values":[{"dictrionary_value_id":0,"value":"https://v.ozone.ru/vod/video-2/01G9C3B7R6DTV02TKV3XB51SZX/asset_2.mp4"}]},{"complex_id":100001,"id":21837,"values":[{"dictrionary_value_id":0,"value":"Обзор"}]}]},{"attributes":[{"complex_id":100002,"id":21843,"values":[{"dictrionary_value_id":0,"value":"https://v.ozone.ru/vod/video-15/01GYZ36FV4SM54WY86RV71DFHZ/asset_2_h264.mp4"}]},{"complex_id":100002,"id":21844,"values":[{"dictrionary_value_id":0,"value":"01GYZ36FV4SM54WY86RV71DFHZ"}]},{"complex_id":100002,"id":21845,"values":[{"dictrionary_value_id":0,"value":"https://v.ozone.ru/vod/video-15/01GYZ36FV4SM54WY86RV71DFHZ/asset_2_h264.mp4"}]},{"complex_id":100002,"id":21846,"values":[{"dictrionary_value_id":0,"value":"https://v.ozone.ru/vod/video-15/01GYZ36FV4SM54WY86RV71DFHZ/master.m3u8"}]},{"complex_id":100002,"id":21842,"values":[{"dictrionary_value_id":0,"value":"https://cdn1.ozone.ru/s3/video-15/01GYZ36FV4SM54WY86RV71DFHZ/cover/cover.jpg"}]}]},{"attributes":[{"complex_id":100003,"id":22917,"values":[{"dictrionary_value_id":971491651,"value":"Golf, VI (2008 - 2012) Хэтчбек 3 дв."}]},{"complex_id":100003,"id":22918,"values":[{"dictrionary_value_id":971520309,"value":"MultiFuel 1.6 MT (102 л.с.) BSE,BSF,CCSA,CMXA"}]},{"complex_id":100003,"id":22916,"values":[{"dictrionary_value_id":58175,"value":"Volkswagen"}]}]}],"depth":120,"dimension_unit":"mm","geo_names":[],"height":50,"images":["https://cdn1.ozone.ru/s3/multimedia-9/6532430541.jpg","https://cdn1.ozone.ru/s3/multimedia-a/6532430542.jpg","https://cdn1.ozone.ru/s3/multimedia-8/6532430540.jpg","https://cdn1.ozone.ru/s3/multimedia-7/6532430539.jpg","https://cdn1.ozone.ru/s3/multimedia-b/6532430543.jpg","https://cdn1.ozone.ru/s3/multimedia-f/6532409451.jpg"],"primary_image":"https://cdn1.ozone.ru/s3/multimedia-p/6715190221.jpg","images_360":[],"name":"LED лампа Z8 Ultra nano-led с тройной системой охлаждения/100w/5000k/комплект, для автомобильных фар/ HB4","offer_id":"91132","currency_code":"CNY","old_price":"100","pdf_list":[],"premium_price":"70","price":"80","service_type":"IS_CODE_SERVICE","vat":"0.0","weight":350,"weight_unit":"g","width":175}]}

task status can be "imported" ,but in ozon backend, there is an error message:
serious
Please correct the error, otherwise the product will not be updated. Showing cards without recent changes on Ozon
Model Name - Required attribute is not filled in. Occasionally we update required attributes or add new ones. Please edit the product or upload a new XLS template with the current attributes.
Part Number (Manufacturer's Article Number) - Required attribute is not filled in. Occasionally we update required attributes or add new ones. Please edit the product or upload a new XLS template with the current attributes.
Brand - Required attribute is not filled in. Occasionally we update required attributes or add new ones. Please edit the product or upload a new XLS template with the current attributes.
Type - Required attribute is not filled in. Occasionally we update required attributes or add new ones. Please edit the product or upload a new XLS template with the current attributes.

spelling mistake

You have a spelling mistake here:

type CreateOrUpdateAttributeValue struct {
// Directory identifier
DictionaryValueId int64 json:"dictrionary_value_id"

// Value from the directory
Value string `json:"value"`
}

it should be dictionary_value_id not dictrionary_value_id

Empty structure in `GetReportsListResultReport`

There is an empty structure in GetReportsListResultReport - Param

	// Array with the filters specified when the seller created the report
	Params struct {
	} `json:"params"`

Is it on purpose? If not, fill with fields

Replace time.Time with new TimeFormat in all requests with correct layout

We decided to use custom structure to handle time in requests as Ozon Seller API require time in specific format which is not always RFC3339. For these purposes custom structure will marshal time to JSON with layout you specify while creating with NewTimeFormat.

For example, there is Filter field in request, which requires YYYY-MM-DD format for time. Need to replace this time.Time to *core.TimeFormat. In tests for these methods, need to create TimeFormat with that layout.

Also need to replace all time.Time in responses which require format other than RFC3339.

Documentation to look up the information: https://docs.ozon.ru/api/seller/en/

Golang version to 19 and not required fields

хотел сделать МР - сказало прав нет
поэтому вот
mr.zip

хотел 2 коммита
update go version to 1.19
because client.go at 44 line usage url.JoinPath(...) - method was added in GO 1.19 version

и

make products GetStocksInfoFilter fields as pointer
because this fields is not required and default GO value for int64 is 0 for ProductId - make error from ozone server response

пысы скорее всего много полей потребуется делать линками - чтобы не получать ошибки от сервера озона, тк они не обязательные, а метод
func getDefaultValues(v interface{}) (map[string]string, error)
int и подобные будет делать нулями, что не верно

More endpoints

Ozon has a lot of endpoints that cannot be implemented all by one person.

If you'd like to contribute, you can take an endpoint from the list and implement by analogy with other endpoints.

Do not forget to add tests and mark it done in the list

Утилиты для поиска данных

Привет!
В продолжение фидбэка из почты :-)
Кейс
Получили список например товаров и список остатков на складах и до кучи данные по аналитике
Теперь всю эту инфу надо соотнести друг с другом
Решение:
Создаём map[string]Response
Пишем цикл перебора списка данных
Загоняем key как sku или id
Загоняем соответствующие данные в value

Было бы здорово иметь подобные утилиты из коробки (всё равно данные в ответах искать)

Implement Content Type in requests

There are some endpoints that require Content-Type other than application/json. Now all methods sends and received application/json.
This is what I found in documentation:

  • /v2/posting/fbs/package-label - application/pdf
  • /v1/posting/fbs/package-label/create - application/pdf
  • /v1/posting/fbs/package-label/get - application/pdf
  • /v1/product/certificate/create - multipart/form-data

unable to change default http client and context

Now method NewClient of ozon and core package uses context.Background() and http.DefaultClient

Want this methods to get last param like configs ...Configuration to configure core httpclient

type Configuration func(o *Client)

func WithHttpClient(client HttpClient) Configuration {
return func(c *Client) {
c.client = client
}
}

func WithContext(ctx context.Context) Configuration {
return func(c *Client) {
c.ctx = ctx
}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.