在Asp.Net MVC中利用快递100接口实现订阅物流轨迹功能
前言
分享一篇关于在电商系统中同步物流轨迹到本地服务器的文章,当前方案使用了快递100做为数据来源接口,这个接口是收费的,不过提供的功能还是非常强大的,有专门的售后维护团队。也有免费的方案,类似于快递鸟,不过数据出现问题就凉凉了
正文
实现思路大概分为三大步:
第一步:提交订阅信息到快递100的接口
第二步:快递100收到请求后会对回调地址进行跟踪,将快递信息推送给回调接口
第三步:回调接口收到Post推送的数据后,进行逻辑处理
注意:回调的地址建议单独部署一个API项目,不要放在主程序下面;或者在提交订阅时要求对回调进行签名验证。
下面附上详细代码:
Subscribe类
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WoT.Infrastructure.Helper.Xml;
using WoT.Model.Inventory;
using WoT.ViewModel.Dtos.Inventory; namespace WoT.SyscTraceSys
{
/// <summary>
/// 订阅物流轨迹
/// </summary>
public class Subscribe
{
//拿到授权的Key
private static string key = ConfigurationManager.AppSettings["SubscribeKey"]; //请求的url
private static string reqUrl = "http://www.kuaidi100.com/poll"; //回调url
private static string callbackurl = "http://你的域名/api/kd100/callback"; /// <summary>
/// 发送订阅指令
/// </summary>
/// <param name="invoce">发货单</param>
/// <param name="shipperCode">快递公司</param>
/// <returns></returns>
public static KD100Result SendPost(Invoice invoce, string shipperCode = "SF")
{
StringBuilder param = new StringBuilder();
KD100Result kdResult = new KD100Result(); param.Append("<?xml version='1.0' encoding='UTF-8'?>")
.AppendFormat("<orderRequest>")
.AppendFormat("<company>{0}</company>", GetCom(shipperCode))
.AppendFormat("<number>{0}</number>", invoce.LogisticCode)
.AppendFormat("<from></from>")
.AppendFormat("<to></to>")
.AppendFormat("<key>{0}</key>", key)
.AppendFormat("<parameters><callbackurl>{0}</callbackurl><resultv2>1</resultv2></parameters>", callbackurl)
.Append("</orderRequest>"); NameValueCollection postvals = new NameValueCollection();
postvals.Add("schema", "xml");
postvals.Add("param", param.ToString());
try
{
using (WebClient wc = new WebClient())
{
string rlt = System.Text.Encoding.UTF8.GetString(wc.UploadValues(reqUrl, "POST", postvals));
kdResult = XmlExpand.DESerializer<KD100Result>(rlt);
}
}
catch (Exception ex)
{
return new KD100Result() { result = false, returnCode = , message = ex.Message };
}
return kdResult;
} /// <summary>
/// 获取com
/// </summary>
/// <param name="shipperCode"></param>
/// <returns></returns>
private static string GetCom(string shipperCode)
{
string com = "shunfeng";
switch (shipperCode)
{
case "EMS":
com = "ems";
break;
case "SF":
com = "shunfeng";
break;
case "STO":
com = "shentong";
break;
case "YD":
com = "yunda";
break;
case "YTO":
com = "yuantong";
break;
case "YZPY":
com = "youzhengguonei";
break;
case "ZJS":
com = "zhaijisong";
break;
case "ZTO":
com = "zhongtong";
break;
case "DBL":
com = "debangwuliu";
break;
case "JD":
com = "debangwuliu";
break;
default:
break;
}
return com;
}
}
}
Subscribe
GetCom()方法是获取获取快递公司的标示编号,我在数据库中只存了快递简称,所以需要通过这种方式获取,如果是存在数据库的就可以直接从数据库获取了。
DESerializer()方法将xml字符串转化为实体对象,关于实现的详情在前面C#操作Xml树的扩展类一节中有讲到。
ConfigurationManager.AppSettings["SubscribeKey"];是读取配置文件,获取快递100对商户授权的Key,配置代码如下:
在appSettings节点下添加
KD100Result类
/// <summary>
/// 快递100返回结果
/// </summary>
[Serializable]
[XmlType("orderResponse")]
public class KD100Result
{
/// <summary>
///
/// </summary>
[XmlElement("result")]
public bool result { get; set; } /// <summary>
///
/// </summary>
[XmlElement("returnCode")]
public int returnCode { get; set; } /// <summary>
///
/// </summary>
[XmlElement("message")]
public string message { get; set; }
}
回调接口Action
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("callback")]
public void callback()
{
StringBuilder sb = new StringBuilder();
DateTime now = DateTime.Now;
pushResponse push = new pushResponse()
{
Result = false,
ReturnCode = ,
Message = "没有拉取到相关数据"
}; HttpContext context = HttpContext.Current;
if (!context.Request.RequestType.ToUpper().Equals("POST"))
{
context.Response.Write(string.Format("<?xml version='1.0' encoding='UTF-8'?><pushResponse><result>{0}</result><returnCode>{1}</returnCode><message>{2}</message></pushResponse>", false, , "请使用POST提交"));
context.Response.End();
return;
} try
{
sb.Clear();
var stream = context.Request.InputStream;
string param = ReadStream(stream); if (string.IsNullOrEmpty(param))
{
context.Response.Write(string.Format("<?xml version='1.0' encoding='UTF-8'?><pushResponse><result>{0}</result><returnCode>{1}</returnCode><message>{2}ee</message></pushResponse>", push.Result, push.ReturnCode, push.Message));
context.Response.End();
return;
} Dictionary<string, string> dic = new Dictionary<string, string>(); string[] sp1 = param.Split('&');
foreach (string s in sp1)
{
int splIdx = s.IndexOf('=');
string key = s.Substring(, splIdx);
string value = s.Substring(splIdx + ); dic.Add(key.Trim(), value.Trim());
}
string cbxml = HttpUtility.UrlDecode(dic["param"], Encoding.UTF8); using (ILogisticsTraceService _Service = CoreServiceFactory.Used.Build<ILogisticsTraceService>())
{
push = _Service.PushLogisticsTrace(cbxml);
} sb.Append("<?xml version='1.0' encoding='UTF-8'?>")
.AppendFormat("<pushResponse><result>{0}</result>", push.Result)
.AppendFormat("<returnCode>{0}</returnCode>", push.ReturnCode)
.AppendFormat("<message>{0}</message>", push.Message)
.Append("</pushResponse>"); stream.Close();
context.Response.Write(sb.ToString());
context.Response.End();
}
catch (Exception)
{
context.Response.Write(string.Format("<?xml version='1.0' encoding='UTF-8'?><pushResponse><result>{0}</result><returnCode>{1}</returnCode><message>{2}</message></pushResponse>", false, , "服务器处理错误"));
} }
callback
有需要源码的朋友可以扫描下方二维码加入QQ群,我会把源码分享在QQ群里
在Asp.Net MVC中利用快递100接口实现订阅物流轨迹功能的更多相关文章
- Asp.net Mvc中利用ValidationAttribute实现xss过滤
在网站开发中,需要注意的一个问题就是防范XSS攻击,Asp.net mvc中已经自动为我们提供了这个功能.用户提交数据时时,在生成Action参数的过程中asp.net会对用户提交的数据进行验证,一旦 ...
- php利用快递100接口获取物流信息
PHP使用CURL调用快递100接口查询运单信息 类代码如下: <?php/** * 快递100接口调用类 * @author 齐云海 * date: 2019/05/29 */ class E ...
- ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理
话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐 ...
- ASP.NET MVC 中的IResolver<T> 接口
在ASP.NET MVC 的源码一些实体对象(比如 ControllerBuilder,ControllerFactory, Filters, ViewEngines 等)不再直接通过关键字new来创 ...
- 在ASP.NET MVC中利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。
正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的'好'东西记 ...
- 在MVC中利用uploadify插件实现上传文件的功能
趁着近段的空闲时间,开发任务不是很重,就一直想把以前在仓促时间里所写的多文件上传功能改一下,在网上找了很多例子,觉得uploadify还可以,就想用它来试试.实现自己想要的功能.根据官网的开发文档,同 ...
- Asp.net MVC WebApi项目的自动接口文档及测试功能打开方法
https://blog.csdn.net/foren_whb/article/details/78866133
- ASP.NET MVC:利用ASP.NET MVC4的IBundleTransform集成LESS
ASP.NET MVC:利用ASP.NET MVC4的IBundleTransform集成LESS 背景 LESS确实不错,只是每次写完LESS都要手工编译一下有点麻烦(VS插件一直没有安装好),昨天 ...
- 【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查
ASP.NET MVC系列文章 [01]浅谈Google Chrome浏览器(理论篇) [02]浅谈Google Chrome浏览器(操作篇)(上) [03]浅谈Google Chrome浏览器(操作 ...
随机推荐
- ubuntu14简介/安装/菜鸟使用手册
Linux拥有众多的发行版,可以分为两大类商业版和开源社区免费版.商业版以Radhat为代表,开源社区版以debian为代表. 简单的比较ubuntu与centos. Ubuntu 优点:丰富的 ...
- 《Django By Example》第一章 学习笔记
首先看了下目录,在这章里 将会学到 安装Django并创建你的第一个项目 设计模型(models)并且生成模型(model)数据库迁移 给你的模型(models)创建一个管理站点 使用查询集(Quer ...
- svn checkout单个文件
http://www.letuknowit.com/archives/svn-checkout-single-file/ 有时候需要在svn版本仓库中某个比较上层的目录中(比如根目录)checkout ...
- 三连击(NOIP1998)
题目链接:三连击 典型的打表题,但cgg今天不是教你怎么打表的,而是教你正解. 这题方法多样,比如递归求解也行,反正数据也不大. 在这里我提供另一种思路,我们枚举第一个数,即最小的一个数,然后分解它以 ...
- 2016-2017-2 20155312 实验三敏捷开发与XP实践实验报告
1.研究code菜单 Move Line/statement Down/Up:将某行.表达式向下.向上移动一行 suround with:用 try-catch,for,if等包裹语句 comment ...
- GUI的优化操作/添加背景图片等
一.背景图片的添加这是JAVA中添加背景图片的方式,基本思路先建立一个Label标签,然后建立一个层次的布局,将label标签添加到最下面去. ImageIcon image=new ImageIco ...
- idea创建spring boot+mybatis(oracle)+themeleaf项目
1.新建项目 选择idea已经有的spring initializr next,然后填写项目命名,包名 然后next,选择所需要的依赖 然后一路next,finish,项目新建成功,然后可以删除下面的 ...
- Vue + Element UI 实现权限管理系统
Vue + Element UI 实现权限管理系统 前端篇(一):搭建开发环境 https://www.cnblogs.com/xifengxiaoma/p/9533018.html
- goole Advance client 离线安装
1.下载插件:Advanced Rest Client 2.最新版的Chrome不支持本地安装插件,所以我们要使能开发者模式 3.把插件后缀名crx改为zip 4.解压,点击‘加载正在开发的扩展程序’ ...
- typecho开启pjax,ajax,无刷新
1.引入jquery和pjax 检查你的网站是否引入1.7.0版本以上的jquery.js,如果没有请全局引入 https://files.cnblogs.com/files/fan-bk/pjax. ...

