首页 > 其他分享 >有赞 调用 api 接口(有赞开放平台)

有赞 调用 api 接口(有赞开放平台)

时间:2023-06-01 14:12:03浏览次数:87  
标签:String 有赞 final 开放平台 api static new import public

ps:先注册有赞账号

有赞

https://www.youzan.com/

有赞开放平台

http://open.youzan.com/

有赞开发者后台

http://open.youzan.com/developer/app/index

接入说明:

http://open.youzan.com/doc

API文档:

http://open.youzan.com/api

*************************************************************

平台介绍
第三方应用接入说明
更新通知
订阅更新
授权方式
免签名通讯协议
签名通讯协议
Oauth2.0授权说明
基础支持
全局错误返回码说明
微信openid
网页授权获取信息
规则与协议
接口需求
*********************************************************
授权方式选择第二种,签名通讯协议。
第一种需要申请应用,第二种则不需要。
第二种针对个人开发者。
下载SDK JAVA 版
三个文件:
KdtApiProtocol.java
package cn.zno.youzan;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class KdtApiProtocol {
    public static final String APP_ID_KEY = "app_id";
    public static final String METHOD_KEY = "method";
    public static final String TIMESTAMP_KEY = "timestamp";
    public static final String FORMAT_KEY = "format";
    public static final String VERSION_KEY = "v";
    public static final String SIGN_KEY = "sign";
    public static final String SIGN_METHOD_KEY = "sign_method";

    public static final int ALLOWED_DEVIATE_SECONDS = 600;

    public static final int ERR_SYSTEM = -1;
    public static final int ERR_INVALID_APP_ID = 40001;
    public static final int ERR_INVALID_APP = 40002;
    public static final int ERR_INVALID_TIMESTAMP = 40003;
    public static final int ERR_EMPTY_SIGNATURE = 40004;
    public static final int ERR_INVALID_SIGNATURE = 40005;
    public static final int ERR_INVALID_METHOD_NAME = 40006;
    public static final int ERR_INVALID_METHOD = 40007;
    public static final int ERR_INVALID_TEAM = 40008;
    public static final int ERR_PARAMETER = 41000;
    public static final int ERR_LOGIC = 50000;

    public static String sign(String appSecret, HashMap<String,String> parames){
        Object[] keyArray = parames.keySet().toArray();
        List<String> keyList = new ArrayList<String>();
        for(int i = 0; i < keyArray.length; i++){
            keyList.add((String)keyArray[i]);
        }
        Collections.sort(keyList);
        String signContent = appSecret;

        for (String key : keyList) {
            signContent += (key + parames.get(key));
        }
        signContent += appSecret;
        return hash(signContent);
    }
    
    private static String hash(String signContent){
        String hashResult = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            try {
                md.update(signContent.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte byteData[] = md.digest();
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < byteData.length; i++){
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            hashResult = sb.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
        }
        
        return hashResult;
    }
}
View Code

KdtApiClient.java

package cn.zno.youzan;


import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class KdtApiClient {
    private static final String Version = "1.0";

    private static final String apiEntry = "https://open.koudaitong.com/api/entry?";

    private static final String format = "json";

    private static final String signMethod = "md5";
    
    private static final String DefaultUserAgent = "KdtApiSdk Client v0.1";

    private String appId;
    private String appSecret;

    public KdtApiClient(String appId, String appSecret) throws Exception{
        if ("".equals(appId) || "".equals(appSecret)){
            throw new Exception("appId 和 appSecret 不能为空");
        }
        
        this.appId = appId;
        this.appSecret = appSecret;
    }
    
    public HttpResponse get(String method, HashMap<String,String> parames) throws Exception{
        String url = apiEntry + getParamStr(method, parames);
        
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        request.addHeader("User-Agent", DefaultUserAgent);
 
        HttpResponse response = client.execute(request);
        return response;
    }
    
    public HttpResponse post(String method, HashMap<String, String> parames, List<String> filePaths, String fileKey) throws Exception{
        String url = apiEntry + getParamStr(method, parames);
        
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("User-Agent", DefaultUserAgent);
        
        if(null != filePaths && filePaths.size() > 0 && null != fileKey && !"".equals(fileKey)){
            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for(int i = 0; i < filePaths.size(); i++){
                File file = new File(filePaths.get(i));
                ContentBody cbFile = new FileBody(file);
                mpEntity.addPart(fileKey, cbFile);
            }
            
            httppost.setEntity(mpEntity);
        }
        
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = client.execute(httppost);
        
        return response;
    }
    
    public String getParamStr(String method, HashMap<String, String> parames){
        String str = "";
        try {
            str = URLEncoder.encode(buildParamStr(buildCompleteParams(method, parames)), "UTF-8")
                    .replace("%3A", ":")
                    .replace("%2F", "/")
                    .replace("%26", "&")
                    .replace("%3D", "=")
                    .replace("%3F", "?");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }
    
    private String buildParamStr(HashMap<String, String> param){
        String paramStr = "";
        Object[] keyArray = param.keySet().toArray();
        for(int i = 0; i < keyArray.length; i++){
            String key = (String)keyArray[i];

            if(0 == i){
                paramStr += (key + "=" + param.get(key));
            }
            else{
                paramStr += ("&" + key + "=" + param.get(key));
            }
        }

        return paramStr;
    }


    private HashMap<String, String> buildCompleteParams(String method, HashMap<String, String> parames) throws Exception{
        HashMap<String, String> commonParams = getCommonParams(method);
        for (String key : parames.keySet()) {
            if(commonParams.containsKey(key)){
                throw new Exception("参数名冲突");
            }
            
            commonParams.put(key, parames.get(key));
        }
        
        commonParams.put(KdtApiProtocol.SIGN_KEY, KdtApiProtocol.sign(appSecret, commonParams));
        return commonParams;
    }

    private HashMap<String, String> getCommonParams(String method){
       HashMap<String, String> parames = new HashMap<String, String>();
        parames.put(KdtApiProtocol.APP_ID_KEY, appId);
        parames.put(KdtApiProtocol.METHOD_KEY, method);
        parames.put(KdtApiProtocol.TIMESTAMP_KEY, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        parames.put(KdtApiProtocol.FORMAT_KEY, format);
        parames.put(KdtApiProtocol.SIGN_METHOD_KEY, signMethod);
        parames.put(KdtApiProtocol.VERSION_KEY, Version);
        return parames;
    }
}
View Code

KDTApiTest.java

package cn.zno.youzan;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;


/*
 * 这是个例子
 */
public class KDTApiTest {
    private static final String APP_ID = "yourappid"; //这里换成你的app_id
    private static final String APP_SECRET = "yourappsecret"; //这里换成你的app_secret
    
    public static void main(String[] args){
        sendGet();
//        sendPost();
    }
    
    /*
     * 测试获取单个商品信息
     */
    private static void sendGet(){
        String method = "kdt.ump.coupons.unfinished.all";
        HashMap<String, String> params = new HashMap<String, String>();
//        params.put("num_iid", "2651514");
        
        KdtApiClient kdtApiClient;
        HttpResponse response;
        
        try {
            kdtApiClient = new KdtApiClient(APP_ID, APP_SECRET);
            response = kdtApiClient.get(method, params);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /*
     * 测试获取添加商品
     */
    private static void sendPost(){
        String method = "kdt.item.add";
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("price", "999.01");
        params.put("title", "测试商品");
        params.put("desc", "这是一个号商铺");
        params.put("is_virtual", "0");
        params.put("post_fee", "10.01");
        params.put("sku_properties", "");
        params.put("sku_quantities", "");
        params.put("sku_prices", "");
        params.put("sku_outer_ids", "");
        String fileKey = "images[]";
        List<String> filePaths = new ArrayList<String>();
        filePaths.add("/Users/xuexiaozhe/Desktop/1.png");
        filePaths.add("/Users/xuexiaozhe/Desktop/2.png");
        
        KdtApiClient kdtApiClient;
        HttpResponse response;
        
        try {
            kdtApiClient = new KdtApiClient(APP_ID, APP_SECRET);
            response = kdtApiClient.post(method, params, filePaths, fileKey);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

 

问:AppID 和 AppSecert 如何获取?

答:签名通讯协议链接,或者 营销 - 有赞API - 有赞API信息

调用 kdt.ump.coupons.unfinished.all 结果举例:

{
    "response": {
        "coupons": [
            {
                "group_id": "1365546",
                "coupon_type": "PROMOCODE",
                "range_type": "ALL",
                "title": "张三搞活动",
                "value": "0.10",
                "is_random": 0,
                "value_random_to": "0.00",
                "need_user_level": 0,
                "user_level_name": "",
                "quota": 1,
                "is_at_least": 1,
                "at_least": "1.00",
                "total": 10,
                "stock": 10,
                "start_at": "2016-07-26 11:08:50",
                "end_at": "2016-07-31 11:07:41",
                "expire_notice": 0,
                "description": "这是张三的活动优惠码",
                "is_forbid_preference": 0,
                "is_sync_weixin": 0,
                "weixin_card_id": "",
                "status": 0,
                "is_share": 1,
                "fetch_url": "https://wap.koudaitong.com/v2/showcase/promocode/fetch?alias=a8fdmtq2",
                "stat_fetch_user_num": 0,
                "stat_fetch_num": 0,
                "stat_use_num": 0,
                "created": "2016-07-26 11:11:04"
            }
        ]
    }
}

 

优惠劵优惠码接口举例说明:

kdt.ump.coupon.consume.verifylogs.get 获取优惠券/优惠码核销记录
kdt.ump.coupon.consume.get 根据核销码获取优惠券/优惠码

或者获取所有未开始和正在进行的优惠劵/优惠码

kdt.ump.coupons.unfinished.all

 

标签:String,有赞,final,开放平台,api,static,new,import,public
From: https://www.cnblogs.com/zno2/p/5707221.html

相关文章

  • NodeManager REST API’s
    NodeManagerRESTAPI’sOverviewEnablingCORSsupportNodeManagerInformationAPIApplicationsAPIApplicationAPIContainersAPIContainerAPIOverviewTheNodeManagerRESTAPI’sallowtheusertogetstatusonthenodeandinformationaboutapplicationsandcont......
  • 网络设备NAPI能力
    voidnetif_napi_add(structnet_device*dev,structnapi_struct*napi,int(*poll)(structnapi_struct*,int),intweight){INIT_LIST_HEAD(&napi->poll_list);hrtimer_init(&napi->timer,CLOCK_MONOTONIC,HRTIMER_MODE_REL_PINNED);napi->......
  • 博学谷学习记录】超强总结,用心分享 | 常用api
    【博学谷IT技术支持】常用APIMath类的常用方法方法名说明publicstaticintabs(inta)返回参数的绝对值publicstaticdoubleceil(doublea)向上取整publicstaticdoublefloor(doublea)向下取整publicstaticintround(floata)四舍五入publicstaticintmax(......
  • Canvas API初步学习
    1.字体 在canvas中最常见的字体表现形式有填充字体和漏空字体。   漏空字体用方法:strokeText(Text,left,top,[maxlength]);  填充字体用方法:fillText(Text,left,top,[maxlength]);上面的两个方法的最后一个参数是可选的,四个参数的含义分为是:需绘制的字符串,绘制到画布中时......
  • 使用OpenAI API进行Model Fine-tuning
    目录1基本信息2操作示例2.1准备数据2.2模型训练2.3模型推理1基本信息参考资料:官方指南:https://platform.openai.com/docs/guides/fine-tuning微调接口:https://platform.openai.com/docs/api-reference/fine-tunes数据接口:https://platform.openai.com/docs/api-refere......
  • kaggle API 命令下载数据集
    1.kaggle介绍Kaggle(官网:https://www.kaggle.com/)是由AnthonyGoldbloom和BenHamner于2010年创立的一个数据科学社区。它为数据科学家和机器学习工程师提供了一个平台,可以在该平台上进行数据分析和建模活动,同时进行竞赛式的数据分析等活动。Kaggle除了提供竞赛外,还有数据......
  • Elasticsearch专题精讲—— REST APIs —— Document APIs —— 索引API
    RESTAPIs——DocumentAPIs——索引APIhttps://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-index_.html#docs-index_ AddsaJSONdocumenttothespecifieddatastreamorindexandmakesitsearchable.Ifthetargetisanindexandth......
  • 最佳实践:如何设计 RESTful API ?
    良好的API设计是一个经常被提及的话题,特别是对于那些试图完善其API策略的团队来说。一个设计良好的API的好处包括:改进开发者体验、更快速地编写文档以及更高效地推广你的API。但是,到底什么才构成了良好API设计呢?在这篇博客文章中,我将详细介绍几个为RESTfulAPIs设计最佳......
  • Intel Media SDK and Intel® oneAPI Video Processing Library (oneVPL)
    TheIntelMediaSoftwareDevelopmentKit(IntelMediaSDK)isacross-platformapplicationprogramminginterface(API)fordevelopingmediaapplicationsonWindowsandLinux. Itismainlyusedforhardware-acceleratedvideoencoding,decoding,andprocess......
  • Vue+.net core 7 api跨域
    nginx的不说,直接说在项目中配置的。重点:前端要配代理,后端要设置返回的头文件信息。双管齐下1、前端在项目中的vue.config.js配置中进行设置module.exports={publicPath:'/',outputDir:'dist',//发布输入文件assetsDir:'static',//需要/demo目录下放打包后......