文档中心 > Lazada Open Platform

Lazada Push Mechanism

更新时间:2023/01/05 访问次数:1961

What is Lazada Push Mechanism(LPM) and Why we need it.

Consider a situation that you are fetching new orders, before LPM, you are calling GetOrders API thousand times an hour(You may get throttled if your step over the limit.). Even you do that, you are not able to get your order once it occurred.


Now with LPM, lazop will send you a notification once new order is created, which enables you get your new orders in milliseconds.


Sounds good ? onboard today !

Getting started with Lazada Push Mechanism

Step1 : Prepare your callback url to receive notifications from Lazop.

Step2: Understand push mechanism details include authorization, retry, etc.. and finish your coding.

Step3: Fill your url in and verify it.

Step4: Subscribe the messages.


This work-through document will take order notification as example.

Step1 : Prepare your callback url to receive notifications from Lazop.

It must be a https with CA certs.

  1. Certification muse be authorized by CA. Self-signed certs are not acceptable.
  2. Certs must be OV or EV. DV is not working.(know more about certs level : https://www.digicert.com/difference-between-dv-ov-and-ev-ssl-certificates).

Step2 : Understand push mechanism details include authorization, retry, etc.. and finish your coding.

After have your call back url, you need to know what a notification looks like. For example, order msg have two types of messages : trade order message and reverse order message. Trade order message triggered when trade order actions happens. trade order actions includes all you can do to a order except return and refund. When customer decide to return, refund, a reverse order message will be sent.


#Header:Only you need to know is the 'Authorization' tag since that is the signature. 
#More details about it will be covered later.

#1.trade order message sample(trade order actions includes order create,paid,shipped..etc)
POST /example/uri HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 1238
Authorization: 34f7b258df045d4ed9341850ca85b866f34828fd7d51862f11137216294a894c
#body
{
   "seller_id":"1234567",  #seller id
 "message_type":0,
   "data":{
      "order_status":"unpaid", #Order status
      "status_update_time":1603698638, #timestamp of the order status update
      "trade_order_id":"260422900198363", #trade order id which mapping to the order_id in API
      "trade_order_line_id":"260422900298363" #sub order id.
   },
   "timestamp":1603766859530, #timestamp of push
   "site":"lazada_vn" # site info
}


#2.reverse order message sample (reverse order actions includes return, refund etc..)
POST /example/uri HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 1238
Authorization: 34f7b258df045d4ed9341850ca85b866f34828fd7d51862f11137216294a894c
#body
{
   "seller_id":"1000114855", 
   "message_type":0,
   "data":{
      "order_status":"canceled",
      "reverse_order_id":"501977696648153",    #reverse order id
      "reverse_order_line_id":"502491640048153", #reverse sub-order id
      "status_update_time":1603703663,
      "trade_order_id":"252883361348153", #related trade order id
      "trade_order_line_id":"252883361948153" #related trade order sub id
   },
   "timestamp":1603715010436,
   "site":"lazada_vn"
}

Questions you may have :

  1. Is trade_order_id mapping to order_id ? Yes
  2. What is a sub-order id ? Use trade order id to query the api.

Authorization:

To make sure the request is sent from Lazop and the request data is complete, Lazop will generate a signature and put it into request header. Client can reproduce the signature and compare it to the one receieved in message before consuming.


Signature is generated by Hex-encoded HMAC-SHA256.

/*
Base = {your_app_key} + "{message_body_you_receieved}"
Secret = {your_app_Secret};
*/
Authorization = HEX_ENCODE(HMAC-SHA256(Base, Secret));

Sample Java Code to reproduce the signature :



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * 签名工具类
 * @author Jeremy
 * @date 2020/12/01
 */
public class SignatureUtil {
    private static final String HMAC_SHA256 = "HmacSHA256";

    private static final Logger LOGGER = LoggerFactory.getLogger(SignatureUtil.class);

    /**
     * Hmac-SHA256
     * @param base {AppKey} + {messageBody}
     * @param secret {AppSecret}
     * E.g.: AppKey = 123456, AppSecret = 3412gyo124goi3124
     * messageBody :{"seller_id":"1234567", "message_type":0, "data":{...}..}
     *
     * base = "123456" + "{\"seller_id\":\"1234567\", \"message_type\":0, "data":{...}..}"
     * secret = 3412gyo124goi3124
     * signature = getSignature(base, secret);
     * signature =  f3d2ca947f16a50b577c036adecd18bec126ea19cadedd59816e255d3b6104ab
     * @return 签名
     */
    public static String getSignature(String base, String secret) {
        try {
            Mac sha256Hmac = Mac.getInstance(HMAC_SHA256);
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA256);
            sha256Hmac.init(secretKey);
            return byteArraytoHexString(sha256Hmac.doFinal(base.getBytes()));
        } catch (Exception e) {
            LOGGER.error("Failed to generate signature");
        }
        return null;

    }

    /**
     * Hex Encode
     * @param bytes
     * @return
     */
    private static String byteArraytoHexString(byte[] bytes) {
        if(bytes == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        String stmp;
        for (byte aByte : bytes) {
            stmp = Integer.toHexString(aByte & 0XFF);
            if (stmp.length() == 1) {
                sb.append('0');
            }
            sb.append(stmp);
        }
        return sb.toString().toLowerCase();
    }
}


Sucess acknowledage and retry :

  1. You need to ack with Http status code 200 with in 500ms
  2. If you fail to do 1, server will retry sending the message after 30 mins.
  3. If retry fails again, server will retry in another 30 mins.
  4. if you fail more than 12 times or you sucessfuly do 1 before 12 times, server will stop retrying.

Step3: App Console self-test, self-access.

Log in to open.lazada.com, and enter the Message Service tab after logging in.

image

1. Fill in the callback address and click Verify. Verify will automatically send a test message to the filled address, if the return meets expectations, it will prompt success.

Note: The access person should manually enter the background to confirm the test message, including confirming the test content, confirming the signature, etc. The signature here is true.

2. After the verification is successful, select the message type to subscribe, and click Save in the upper right corner.


Note: The data of all ISVs that have been manually accessed before will be automatically synchronized here, and you do not need to perform the above automatic access operations.

The following actions will not take effect immediately before March 15th and will be delayed until March 15th:

1. The newly connected ISV uses automatic access to save the online address.

2. The ISV that was previously manually accessed uses automatic access to change the online address.

Step4: Go production and best practice

After onboarded, below is a recommend way of consuming the message.

A way of consuming push message is :

OrderMessage -----------> /order/get ------------>/order/items/get -> business logic

trade_order_id trade_order_id

How to switch the consuming pattern from `pulling only` to `consume push, but pull with low frequency to protect from missing` ?

Strategy 1 :

Keep pulling frequency unchanged, but add consuming push logic. And gradually lowing the frequency of pulling.

Strategy 2:

Whitelisting some sellers, use the new startegy. And gradually adding sellers to whitelist.

FAQ:

I need the IPs of push servers to do ip white-listing, can you guys provide the ips ?

Lazop recommends to use signature on authorization header to check the origin of pushes. No further supports on IPs from lazop.


Some sellers message are missing.

Server will check the authorization between sellerId and appkey. If the auth is revoked or expired, server will abort the pushing. You can verify the authorization by checking the token that you use for calling the API.


Would there be more message types beside order message ?

Only order message is online now. Product, promotions, stock message is under developing.


How to get the orders if all retries failed ?

You need to use /orders/get API to get them. The recommend way of consuming the message is : Consume the order messages, and pull the orders periodically to check if there is any missing. So called "consume push, but pull with low frequency to protect from missing"


Duplicate message pushed for same order?

Firstly, small amount of duplicate message is normal. Message design is 'at least once push'. Idempotently consuming is required.

Secondly, if you got huge amount duplicate, please pay attention to the field 'trade_order_line_id'. If two messages have same trade_order_id but different trade_order_line_id, server will treat it as different messages.

FAQ

关于此文档暂时还没有FAQ
返回
顶部