gin框架对接快递100 查询快递跟踪记录 Golang实现快递查询

参考ui效果:
https://www.kuaidi100.com/?from=openv

gin框架:

请求地址 http://localhost:8822/kd100/auto_com_num?num=73119782411952
请求地址 http://localhost:8822/kd100/query_num_detail?num=73119782411952&comCode=zhongtong

//路由
router.GET("/kd100/auto_com_num", controller.AutoComNum) //获取快递公司类型
router.GET("/kd100/query_num_detail", controller.QueryNumDetail) //获取快递跟踪信息

//获取快递公司类型
func AutoComNum(ctx *gin.Context) {
	//fmt.Println("AutoComNum...")
	text := ctx.Query("num") //单号
	url := "https://www.kuaidi100.com/autonumber/autoComNum?resultv2=1&text=" + text
	paramData := gin.H{}
	headerData := make(map[string]string, 1)
	headerData["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0"
	resp := SendPostWithHeard(url, paramData, headerData)
	type resAuto struct {
		ComCode   string `json:"comCode"`
		LengthPre int    `json:"lengthPre"`
		NoCount   int    `json:"noCount"`
		NoPre     string `json:"noPre"`
		Name      string `json:"name"`
	}

	type respData struct {
		Num     string     `json:"num"`
		ComCode string     `json:"comCode"`
		Auto    []*resAuto `json:"auto"`
	}
	var resdata *respData
	if err := json.Unmarshal([]byte(resp), &resdata); err != nil {
		fmt.Println("Unmarshal resdata fail,", err)
		httpext.Error(ctx, e.ERROR)
		return
	}
	for _, v := range resdata.Auto {
		kdName, ok := KD100Flags[v.ComCode]
		if ok {
			v.Name = kdName
		} else {
			v.Name = "未知快递"
		}
	}
	httpext.SuccessExt(ctx, resdata)
}


//获取快递跟踪信息
func QueryNumDetail(ctx *gin.Context) {
	//fmt.Println("AutoComNum...")
	num := ctx.Query("num")        //单号
	kdtype := ctx.Query("comCode") //快递类型

	key := "XXXXXXXX"                          //客户授权key
	customer := "XXXXXXXXXXXXXXXXXXXXXXX" //查询公司编号

	posturl := "http://poll.kuaidi100.com/poll/query.do" //实时查询请求地址

	paramData := make(map[string]string)
	paramData["com"] = kdtype //快递公司编码
	paramData["num"] = num    //快递单号
	
	paramDataSlice, _ := json.Marshal(paramData)
	paramjson := string(paramDataSlice)

	sign := strings.ToUpper(crypto.GetMd5String(paramjson + key + customer))
	fmt.Println("p=====>", customer)

	//POST请求需要三个参数,分别为customer(CustomerId)和sign(签名)和param(参数)
	postRes, postErr := http.PostForm(posturl, url.Values{"customer": {customer}, "sign": {sign}, "param": {paramjson}})
	if postErr != nil {
		fmt.Println("查询失败" + postErr.Error())
		httpext.ErrorExt(ctx, e.ERROR, "查询失败"+postErr.Error())
		return
	}
	postBody, err := ioutil.ReadAll(postRes.Body)
	if err != nil {
		fmt.Println("查询失败,请至快递公司官网自行查询" + err.Error())
		httpext.ErrorExt(ctx, e.ERROR, "查询失败,请至快递公司官网自行查询"+err.Error())
		return
	}
	fmt.Println(string(postBody))
	resp := make(map[string]interface{})
	err = json.Unmarshal(postBody, &resp)
	if err != nil {
		fmt.Println("json.Unmarshal error", err.Error())
		httpext.ErrorExt(ctx, e.ERROR, "查询失败,请至快递公司官网自行查询"+err.Error())
		return
	}

	httpext.SuccessExt(ctx, resp)
}

// SendPostWithHeard ...   发送POST请求 ...
// url:         请求地址
// data:        POST请求提交的数据
// hearderParam  设置header头信息
// contentType: 请求体格式,如:json
// content:     请求放回的内容
//func SendPostWithHeard(url string, data interface{}, hearderParam map[string]string, contentType string) string {
func SendPostWithHeard(url string, data interface{}, hearderParam map[string]string) string {
	bytesData, err := json.Marshal(data)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error()
	}

	reader := bytes.NewReader(bytesData)
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error()
	}
	//增加header选项 添加请求头
	if len(hearderParam) > 0 {
		for k, v := range hearderParam {
			request.Header.Set(k, v)
		}
	}
	//request.Header.Set("Content-Type", contentTypeParam[contentType])

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error()
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	fmt.Println(1111111)
	fmt.Println(respBytes)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error()
	}

	return string(respBytes)
}




var KD100Flags = map[string]string{
	"ane66":          "安能快递",
	"debangwuliu":    "德邦物流",
	"debangkuaidi":   "德邦快递",
	"ems":            "EMS",
	"guotongkuaidi":  "国通快递",
	"huitongkuaidi":  "百世快递",
	"jd":             "京东物流",
	"kuayue":         "跨越速运",
	"pjbest":         "品骏快递",
	"shentong":       "申通快递",
	"shunfeng":       "顺丰速运",
	"suer":           "速尔快递",
	"xinfengwuliu":   "信丰物流",
	"youshuwuliu":    "优速物流",
	"youzhengguonei": "邮政快递包裹",
	"yuantong":       "圆通速递",
	"yuantongguoji":  "圆通国际",
	"yunda":          "韵达快递",
	"zhaijisong":     "宅急送",
	"zhongtong":      "中通快递",
	"ewe":            "EWE全球快递",
	"quanyikuaidi":   "全一快递",
	"tiantian":       "天天快递",
	"sxjdfreight":    "顺心捷达",
	"dhl":            "DHL-中国件",
	"tnt":            "TNT",
	"other":          "其它快递",
}

获取快递公司类型 返回参:

    {
        "data": {
            "num": "1009414746833",
            "comCode": "",
            "auto": [
                {
                    "comCode": "ems",
                    "lengthPre": 13,
                    "noCount": 32,
                    "noPre": "100941",
                    "name": "EMS"
                },
                {
                    "comCode": "youzhengguonei",
                    "lengthPre": 13,
                    "noCount": 1,
                    "noPre": "100941",
                    "name": "邮政快递包裹"
                }
            ]
        },
        "errmsg": "ok",
        "errno": 200
    }

获取快递跟踪信息 反参

    {
        "data": {
            "com": "zhongtong",
            "condition": "00",
            "data": [
                {
                    "context": "订单已由【菜鸟驿站】代收,感谢您在京东购物,欢迎您再次光临!",
                    "ftime": "2020-04-05 11:47:12",
                    "location": "",
                    "time": "2020-04-05 11:47:12"
                },
                {
                    "context": "配送员开始配送,请您准备收货,配送员,方辉,手机号,15807710153",
                    "ftime": "2020-04-05 08:15:18",
                    "location": "",
                    "time": "2020-04-05 08:15:18"
                },
                {
                    "context": "货物已分配,等待配送",
                    "ftime": "2020-04-05 07:48:13",
                    "location": "",
                    "time": "2020-04-05 07:48:13"
                },
                {
                    "context": "货物已到达【南宁良庆营业部】",
                    "ftime": "2020-04-05 07:48:12",
                    "location": "",
                    "time": "2020-04-05 07:48:12"
                },
                {
                    "context": "货物已完成分拣,离开【南宁分拨中心】",
                    "ftime": "2020-04-04 23:50:33",
                    "location": "",
                    "time": "2020-04-04 23:50:33"
                },
                {
                    "context": "货物已完成分拣,离开【南宁分拨中心】",
                    "ftime": "2020-04-04 21:46:25",
                    "location": "",
                    "time": "2020-04-04 21:46:25"
                },
                {
                    "context": "货物已到达【南宁分拨中心】",
                    "ftime": "2020-04-04 21:44:52",
                    "location": "",
                    "time": "2020-04-04 21:44:52"
                },
                {
                    "context": "货物已完成分拣,离开【南宁分拨中心】",
                    "ftime": "2020-04-04 18:51:02",
                    "location": "",
                    "time": "2020-04-04 18:51:02"
                },
                {
                    "context": "货物已交付京东物流",
                    "ftime": "2020-04-04 17:47:17",
                    "location": "",
                    "time": "2020-04-04 17:47:17"
                }
            ],
            "ischeck": "0",
            "message": "ok",
            "nu": "73119782411952",
            "state": "0",
            "status": "200"
        },
        "errmsg": "ok",
        "errno": 200
    }
posted @ 2020-04-08 11:47  HaimaBlog  阅读(3987)  评论(0编辑  收藏  举报