添加C#sdk

1.x
tanghc 6 years ago
parent 8fb4a66109
commit 2cff1a7c0b
  1. 236
      sop-sdk/sdk-csharp/.gitignore
  2. 23
      sop-sdk/sdk-csharp/SDKCSharp.sln
  3. 121
      sop-sdk/sdk-csharp/SDKCSharp/Client/OpenClient.cs
  4. 198
      sop-sdk/sdk-csharp/SDKCSharp/Client/OpenHttp.cs
  5. 95
      sop-sdk/sdk-csharp/SDKCSharp/Client/OpenRequest.cs
  6. 14
      sop-sdk/sdk-csharp/SDKCSharp/Common/IgnoreSign.cs
  7. 191
      sop-sdk/sdk-csharp/SDKCSharp/Common/OpenConfig.cs
  8. 40
      sop-sdk/sdk-csharp/SDKCSharp/Common/RequestForm.cs
  9. 23
      sop-sdk/sdk-csharp/SDKCSharp/Common/SdkConfig.cs
  10. 34
      sop-sdk/sdk-csharp/SDKCSharp/Common/SopSignature.cs
  11. 79
      sop-sdk/sdk-csharp/SDKCSharp/Common/UploadFile.cs
  12. BIN
      sop-sdk/sdk-csharp/SDKCSharp/Dll/BouncyCastle.Crypto.dll
  13. BIN
      sop-sdk/sdk-csharp/SDKCSharp/Dll/json/net45/Newtonsoft.Json.dll
  14. 11121
      sop-sdk/sdk-csharp/SDKCSharp/Dll/json/net45/Newtonsoft.Json.xml
  15. 14
      sop-sdk/sdk-csharp/SDKCSharp/Model/GetStoryModel.cs
  16. 36
      sop-sdk/sdk-csharp/SDKCSharp/Properties/AssemblyInfo.cs
  17. 103
      sop-sdk/sdk-csharp/SDKCSharp/Request/BaseRequest.cs
  18. 24
      sop-sdk/sdk-csharp/SDKCSharp/Request/CommonRequest.cs
  19. 14
      sop-sdk/sdk-csharp/SDKCSharp/Request/GetStoryRequest.cs
  20. 53
      sop-sdk/sdk-csharp/SDKCSharp/Response/BaseResponse.cs
  21. 6
      sop-sdk/sdk-csharp/SDKCSharp/Response/CommonResponse.cs
  22. 18
      sop-sdk/sdk-csharp/SDKCSharp/Response/GetStoryResponse.cs
  23. 91
      sop-sdk/sdk-csharp/SDKCSharp/SDKCSharp.csproj
  24. 69
      sop-sdk/sdk-csharp/SDKCSharp/Utility/AESUtil.cs
  25. 75
      sop-sdk/sdk-csharp/SDKCSharp/Utility/ClassUtil.cs
  26. 49
      sop-sdk/sdk-csharp/SDKCSharp/Utility/FileUtil.cs
  27. 52
      sop-sdk/sdk-csharp/SDKCSharp/Utility/JsonUtil.cs
  28. 71
      sop-sdk/sdk-csharp/SDKCSharp/Utility/MD5Util.cs
  29. 210
      sop-sdk/sdk-csharp/SDKCSharp/Utility/RSA.cs
  30. 47
      sop-sdk/sdk-csharp/SDKCSharp/Utility/RSAUtil.cs
  31. 43
      sop-sdk/sdk-csharp/SDKCSharp/Utility/SignUtil.cs
  32. 83
      sop-sdk/sdk-csharp/SDKTest/Program.cs
  33. 26
      sop-sdk/sdk-csharp/SDKTest/Properties/AssemblyInfo.cs
  34. 43
      sop-sdk/sdk-csharp/SDKTest/SDKTest.csproj
  35. 181
      sop-sdk/sdk-csharp/readme.md

@ -0,0 +1,236 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/

@ -0,0 +1,23 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SDKCSharp", "SDKCSharp\SDKCSharp.csproj", "{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SDKTest", "SDKTest\SDKTest.csproj", "{34D6DDAB-895D-4B31-A18F-157BBF6393A1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}.Release|Any CPU.Build.0 = Release|Any CPU
{34D6DDAB-895D-4B31-A18F-157BBF6393A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{34D6DDAB-895D-4B31-A18F-157BBF6393A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34D6DDAB-895D-4B31-A18F-157BBF6393A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34D6DDAB-895D-4B31-A18F-157BBF6393A1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

@ -0,0 +1,121 @@
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading.Tasks;
using SDKCSharp.Common;
using SDKCSharp.Request;
using SDKCSharp.Response;
using SDKCSharp.Utility;
namespace SDKCSharp.Client
{
/// <summary>
/// 客户端
/// </summary>
public class OpenClient
{
private static OpenConfig DEFAULT_CONFIG = new OpenConfig();
private static char DOT = '.';
private static char UNDERLINE = '_';
public static String DATA_SUFFIX = "_response";
private Dictionary<string, string> header = new Dictionary<string, string>();
private String url;
private String appId;
private String privateKey;
private OpenConfig openConfig;
private OpenRequest openRequest;
public OpenClient(string url, string appId, string privateKey) : this(url, appId, privateKey, DEFAULT_CONFIG)
{
}
public OpenClient(string url, string appId, string privateKey, OpenConfig openConfig)
{
this.url = url;
this.appId = appId;
this.privateKey = privateKey;
this.openConfig = openConfig;
this.openRequest = new OpenRequest(openConfig);
}
/// <summary>
/// 发送请求
/// </summary>
/// <typeparam name="T">返回的Response类</typeparam>
/// <param name="request">请求对象</param>
/// <returns>返回Response类</returns>
public virtual T Execute<T>(BaseRequest<T> request) where T : BaseResponse
{
return this.Execute<T>(request, null);
}
/// <summary>
/// 发送请求
/// </summary>
/// <typeparam name="T">返回的Response类</typeparam>
/// <param name="request">请求对象</param>
/// <param name="accessToken">accessToken</param>
/// <returns>返回Response类</returns>
public virtual T Execute<T>(BaseRequest<T> request, string accessToken) where T : BaseResponse
{
RequestForm requestForm = request.CreateRequestForm(this.openConfig);
Dictionary<string, string> form = requestForm.Form;
if (!string.IsNullOrEmpty(accessToken))
{
form[this.openConfig.AccessTokenName] = accessToken;
}
form[this.openConfig.AppKeyName] = this.appId;
string content = SopSignature.getSignContent(form);
string sign = RSAUtil.EncryptByPrivateKey(content, this.privateKey);
form[this.openConfig.SignName] = sign;
string resp = this.doExecute(url, requestForm, header);
return this.parseResponse<T>(resp, request);
}
/// <summary>
/// 执行请求
/// </summary>
/// <param name="url">请求url</param>
/// <param name="requestForm">请求内容</param>
/// <param name="header">请求header</param>
/// <returns>返回服务器响应内容</returns>
protected virtual String doExecute(String url, RequestForm requestForm, Dictionary<string, string> header)
{
return openRequest.Request(this.url, requestForm, header);
}
/// <summary>
/// 解析返回结果
/// </summary>
/// <typeparam name="T">返回的Response</typeparam>
/// <param name="resp">服务器响应内容</param>
/// <param name="request">请求Request</param>
/// <returns>返回Response</returns>
protected virtual T parseResponse<T>(string resp, BaseRequest<T> request) where T: BaseResponse {
string method = request.Method;
string dataName = method.Replace(DOT, UNDERLINE) + DATA_SUFFIX;
Dictionary<string, object> jsonObject = JsonUtil.ParseToDictionary(resp);
object data = jsonObject[dataName];
string jsonData = data == null ? "{}" : data.ToString();
T t = JsonUtil.ParseObject<T>(jsonData);
t.Body = jsonData;
return t;
}
}
}

@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using SDKCSharp.Common;
namespace SDKCSharp.Client
{
public class OpenHttp
{
public const string CONTENT_TYPE_JSON = "application/json";
public const string CONTENT_TYPE_STREAM = "application/octet-stream";
public const string METHOD_POST = "POST";
public CookieContainer cookieContainer = new CookieContainer();
private OpenConfig openConfig;
public OpenHttp(OpenConfig openConfig)
{
this.openConfig = openConfig;
}
public HttpWebRequest CreateWebRequest(string url)
{
return CreateWebRequest(url, null);
}
public HttpWebRequest CreateWebRequest(string url, Dictionary<string, string> header)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieContainer;
request.ContinueTimeout = this.openConfig.ConnectTimeoutSeconds * 1000;
request.ReadWriteTimeout = this.openConfig.ReadTimeoutSeconds * 1000;
bindHeader(request, header);
return request;
}
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string Get(string url, Dictionary<string, string> header)
{
var request = CreateWebRequest(url, header);
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string Get(string url)
{
return Get(url, null);
}
/// <summary>
/// post请求,发送请求体
/// </summary>
/// <param name="url">提交的url</param>
/// <param name="json">json数据</param>
/// <param name="header">header</param>
/// <returns></returns>
public string PostJsonBody(string url, string json, Dictionary<string, string> header)
{
var request = CreateWebRequest(url, header);
request.ContentType = CONTENT_TYPE_JSON;
request.Method = METHOD_POST;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
private void bindHeader(HttpWebRequest request, Dictionary<string, string> header)
{
if (header == null || header.Count == 0)
{
return;
}
ICollection<string> keys = header.Keys;
foreach (string key in keys)
{
request.Headers.Add(key, header[key]);
}
}
/// <summary>
/// post请求,并且文件上传
/// </summary>
/// <param name="url">请求url</param>
/// <param name="form">表单数据</param>
/// <param name="header">请求头</param>
/// <param name="files">文件信息</param>
/// <returns></returns>
public string PostFile(string url, Dictionary<string, string> form, Dictionary<string, string> header, List<UploadFile> files)
{
Encoding ENCODING_UTF8 = Encoding.UTF8;
using (MemoryStream memoryStream = new MemoryStream())
{
// 1.分界线
string boundary = string.Format("----{0}", DateTime.Now.Ticks.ToString("x")), // 分界线可以自定义参数
appendBoundary = string.Format("--{0}\r\n", boundary),
endBoundary = string.Format("\r\n--{0}--\r\n", boundary);
byte[] beginBoundaryBytes = ENCODING_UTF8.GetBytes(appendBoundary),
endBoundaryBytes = ENCODING_UTF8.GetBytes(endBoundary);
StringBuilder payload = new StringBuilder();
// 2.组装 上传文件附加携带的参数 到内存流中
if (form != null && form.Count > 0)
{
ICollection<string> keys = form.Keys;
foreach (string key in keys)
{
string boundaryBlock = string.Format("{0}Content-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", appendBoundary, key, form[key]);
byte[] boundaryBlockBytes = ENCODING_UTF8.GetBytes(boundaryBlock);
memoryStream.Write(boundaryBlockBytes, 0, boundaryBlockBytes.Length);
}
}
// 3.组装文件头数据体 到内存流中
foreach (UploadFile uploadFile in files)
{
string boundaryBlock = string.Format("{0}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n", appendBoundary, uploadFile.Name, uploadFile.FileName);
byte[] boundaryBlockBytes = ENCODING_UTF8.GetBytes(boundaryBlock);
memoryStream.Write(boundaryBlockBytes, 0, boundaryBlockBytes.Length);
memoryStream.Write(uploadFile.FileData, 0, uploadFile.FileData.Length);
}
// 4.组装结束分界线数据体 到内存流中
memoryStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
// 5.获取二进制数据,最终需要发送给服务器的数据
byte[] postBytes = memoryStream.ToArray();
// 6.HttpWebRequest 组装
HttpWebRequest webRequest = CreateWebRequest(url, header);
webRequest.Method = METHOD_POST;
webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
webRequest.ContentLength = postBytes.Length;
bindHeader(webRequest, header);
if (Regex.IsMatch(url, "^https://"))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
}
// 7.写入上传请求数据
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
// 8.获取响应
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), ENCODING_UTF8))
{
string body = reader.ReadToEnd();
return body;
}
}
}
}
static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
}

@ -0,0 +1,95 @@
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SDKCSharp.Common;
using SDKCSharp.Utility;
using SDKCSharp.Response;
namespace SDKCSharp.Client
{
public class OpenRequest
{
private const string AND = "&";
private const string EQ = "=";
private const string UTF8 = "UTF-8";
private const string HTTP_ERROR_CODE = "-400";
private OpenConfig openConfig;
private OpenHttp openHttp;
public OpenRequest(OpenConfig openConfig)
{
this.openConfig = openConfig;
this.openHttp = new OpenHttp(openConfig);
}
/// <summary>
/// 请求服务器
/// </summary>
/// <param name="url">url</param>
/// <param name="requestForm">请求表单信息</param>
/// <param name="header">请求头</param>
/// <returns></returns>
public string Request(string url, RequestForm requestForm, Dictionary<string, string> header)
{
return this.doPost(url, requestForm, header);
}
public string doGet(string url, RequestForm requestForm, Dictionary<string, string> header)
{
StringBuilder queryString = new StringBuilder();
Dictionary<string, string> form = requestForm.Form;
Dictionary<string, string>.KeyCollection keys = form.Keys;
foreach (string keyName in keys)
{
queryString.Append(AND).Append(keyName).Append(EQ)
.Append(HttpUtility.UrlEncode(form[keyName].ToString(), Encoding.UTF8));
}
string requestUrl = url + "?" + queryString.ToString().Substring(1);
return this.openHttp.Get(requestUrl);
}
public string doPost(string url, RequestForm requestForm, Dictionary<string, string> header)
{
Dictionary<string, string> form = requestForm.Form;
List<UploadFile> files = requestForm.Files;
if (files != null && files.Count > 0)
{
return this.openHttp.PostFile(url, form, header, files);
}
else
{
return this.openHttp.PostJsonBody(url, JsonUtil.ToJSONString(form), header);
}
}
public string PostJsonBody(string url, string json)
{
return this.openHttp.PostJsonBody(url, json, null);
}
protected string causeException(Exception e)
{
ErrorResponse result = new ErrorResponse();
result.SubCode = HTTP_ERROR_CODE;
result.SubMsg = e.Message;
result.Code = HTTP_ERROR_CODE;
result.Msg = e.Message;
return JsonUtil.ToJSONString(result);
}
}
class ErrorResponse : BaseResponse
{
}
}

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SDKCSharp.Request
{
/// <summary>
/// 元数据,放在属性上面,表示忽略签名
/// </summary>
sealed class IgnoreSign : Attribute
{
}
}

@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SDKCSharp;
namespace SDKCSharp.Common
{
public class OpenConfig
{
private String successCode = SdkConfig.SUCCESS_CODE;
/// <summary>
/// 返回码成功值
/// </summary>
public String SuccessCode
{
get { return successCode; }
set { successCode = value; }
}
private String defaultVersion = SdkConfig.DEFAULT_VERSION;
/// <summary>
/// 默认版本号
/// </summary>
public String DefaultVersion
{
get { return defaultVersion; }
set { defaultVersion = value; }
}
private String methodName = "method";
/// <summary>
/// 接口属性名
/// </summary>
public String MethodName
{
get { return methodName; }
set { methodName = value; }
}
private String versionName = "version";
/// <summary>
/// 版本号名称
/// </summary>
public String VersionName
{
get { return versionName; }
set { versionName = value; }
}
private String charsetName = "charset";
/// <summary>
/// 编码名称
/// </summary>
/// <value>The name of the charset.</value>
public string CharsetName { get => charsetName; set => charsetName = value; }
private String appKeyName = "app_id";
/// <summary>
/// appKey名称
/// </summary>
public String AppKeyName
{
get { return appKeyName; }
set { appKeyName = value; }
}
private String dataName = "biz_content";
/// <summary>
/// data名称
/// </summary>
public String DataName
{
get { return dataName; }
set { dataName = value; }
}
private String timestampName = "timestamp";
/// <summary>
/// 时间戳名称
/// </summary>
public String TimestampName
{
get { return timestampName; }
set { timestampName = value; }
}
private String timestampPattern = "yyyy-MM-dd HH:mm:ss";
/// <summary>
/// 时间戳格式
/// </summary>
public String TimestampPattern
{
get { return timestampPattern; }
set { timestampPattern = value; }
}
private String signName = "sign";
/// <summary>
/// 签名串名称
/// </summary>
public String SignName
{
get { return signName; }
set { signName = value; }
}
private String formatName = "format";
/// <summary>
/// 格式化名称
/// </summary>
public String FormatName
{
get { return formatName; }
set { formatName = value; }
}
private String formatType = "json";
/// <summary>
/// 格式类型
/// </summary>
public String FormatType
{
get { return formatType; }
set { formatType = value; }
}
private String accessTokenName = "app_auth_token";
/// <summary> accessToken名称
/// </summary>
public String AccessTokenName
{
get { return accessTokenName; }
set { accessTokenName = value; }
}
private String locale = "zh-CN";
/// <summary>
/// 国际化语言
/// </summary>
public String Locale
{
get { return locale; }
set { locale = value; }
}
private String responseCodeName = "code";
/// <summary>
/// 响应code名称
/// </summary>
public String ResponseCodeName
{
get { return responseCodeName; }
set { responseCodeName = value; }
}
private int connectTimeoutSeconds = 10;
/// <summary>
/// 请求超时时间
/// </summary>
public int ConnectTimeoutSeconds
{
get { return connectTimeoutSeconds; }
set { connectTimeoutSeconds = value; }
}
private int readTimeoutSeconds = 10;
/// <summary>
/// http读取超时时间
/// </summary>
public int ReadTimeoutSeconds
{
get { return readTimeoutSeconds; }
set { readTimeoutSeconds = value; }
}
private string signTypeName = "sign_type";
/// <summary>
/// 签名类型名称
/// </summary>
/// <value>The name of the sign type.</value>
public string SignTypeName { get => signTypeName; set => signTypeName = value; }
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SDKCSharp.Common
{
public class RequestForm
{
private Dictionary<string, string> form;
/// <summary>
/// 请求表单内容
/// </summary>
public Dictionary<string, string> Form
{
get { return form; }
set { form = value; }
}
private List<UploadFile> files;
/// <summary>
/// 上传文件
/// </summary>
public List<UploadFile> Files
{
get { return files; }
set { files = value; }
}
public RequestForm(Dictionary<string, string> form)
{
this.form = form;
}
}
}

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SDKCSharp.Common
{
public class SdkConfig
{
public static String SUCCESS_CODE = "10000";
public static String DEFAULT_VERSION = "1.0";
public static String FORMAT_TYPE = "json";
public static String TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String CHARSET = "UTF-8";
public static String SIGN_TYPE = "RSA2";
}
}

@ -0,0 +1,34 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace SDKCSharp.Common
{
public class SopSignature
{
public SopSignature()
{
}
public static String getSignContent(Dictionary<string, string> form)
{
StringBuilder content = new StringBuilder();
List<string> keys = new List<string>(form.Keys);
keys.Sort();
int index = 0;
for (int i = 0; i < keys.Count; i++)
{
string key = keys[i];
string value = form[key];
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
content.Append((index == 0 ? "" : "&") + key + "=" + value);
index++;
}
}
return content.ToString();
}
}
}

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using SDKCSharp.Utility;
namespace SDKCSharp.Common
{
public class UploadFile
{
/// <summary>
/// 添加上传文件
/// </summary>
/// <param name="name">表单名称,不能重复</param>
/// <param name="filePath">文件路径</param>
public UploadFile(string name, string filePath)
: this(name, FileUtil.GetFileName(filePath), FileUtil.ReadFile(filePath))
{
}
/// <summary>
/// 添加上传文件
/// </summary>
/// <param name="name">表单名称,不能重复</param>
/// <param name="fileName">文件名称</param>
/// <param name="fileStream">文件流</param>
public UploadFile(string name, string fileName, FileStream fileStream)
: this(name, fileName, FileUtil.ReadFile(fileStream))
{
}
/// <summary>
/// 添加上传文件
/// </summary>
/// <param name="name">表单名称,不能重复</param>
/// <param name="fileName">文件名称</param>
/// <param name="fileData">文件内容</param>
public UploadFile(string name, string fileName, byte[] fileData)
{
this.name = name;
this.fileName = fileName;
this.fileData = fileData;
this.md5 = MD5Util.Encrypt(fileData);
}
private string name;
public string Name
{
get { return name; }
}
private string fileName;
public string FileName
{
get { return fileName; }
}
private byte[] fileData;
public byte[] FileData
{
get { return fileData; }
}
private string md5;
public string Md5
{
get { return md5; }
}
}
}

@ -0,0 +1,14 @@
using Newtonsoft.Json;
namespace SDKCSharp.Model
{
public class GetStoryModel
{
/// <summary>
/// 故事名称
/// </summary>
/// <value>The name.</value>
[JsonProperty("name")]
public string Name { get; set; }
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("SDK-CSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SDK-CSharp")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("ce2f54f7-3281-4680-82e9-71f936b24518")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using SDKCSharp.Common;
using SDKCSharp.Utility;
namespace SDKCSharp.Request
{
/// <summary>
/// 接口请求对象,新建的Request要继承这个类
/// </summary>
/// <typeparam name="T">对应的Response对象</typeparam>
public abstract class BaseRequest<T>
{
private string method;
private string format = SdkConfig.FORMAT_TYPE;
private string charset = SdkConfig.CHARSET;
private string signType = SdkConfig.SIGN_TYPE;
private string timestamp = DateTime.Now.ToString(SdkConfig.TIMESTAMP_PATTERN);
private string version;
private string bizContent;
private object bizModel;
private List<UploadFile> files;
public string Method { get => method; }
public List<UploadFile> Files { set => files = value; }
public string BizContent { set => bizContent = value; }
public object BizModel { set => bizModel = value; }
public string Version { get => version; set => version = value; }
/// <summary>
/// 返回接口名
/// </summary>
/// <returns></returns>
public abstract string GetMethod();
/// <summary>
/// 返回版本号
/// </summary>
/// <returns></returns>
public virtual string GetVersion()
{
return SdkConfig.DEFAULT_VERSION;
}
public BaseRequest()
{
this.method = this.GetMethod();
this.version = this.GetVersion();
}
protected BaseRequest(string name, string version)
{
this.method = name;
this.version = version == null ? SdkConfig.DEFAULT_VERSION : version;
}
/// <summary>
/// 创建请求表单
/// </summary>
/// <returns></returns>
public RequestForm CreateRequestForm(OpenConfig openConfig)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict[openConfig.MethodName] = this.Method;
dict[openConfig.FormatName] = this.format;
dict[openConfig.CharsetName] = this.charset;
dict[openConfig.SignTypeName] = this.signType;
dict[openConfig.TimestampName] = this.timestamp;
dict[openConfig.VersionName] = this.version;
// 业务参数
String biz_content = buildBizContent();
dict[openConfig.DataName] = biz_content;
RequestForm requestForm = new RequestForm(dict);
requestForm.Files = this.files;
return requestForm;
}
protected string buildBizContent()
{
if (bizModel != null)
{
return JsonUtil.ToJSONString(bizModel);
}
else
{
return this.bizContent;
}
}
}
}

@ -0,0 +1,24 @@
using System;
using SDKCSharp.Response;
namespace SDKCSharp.Request
{
public class CommonRequest : BaseRequest<CommonResponse>
{
public CommonRequest(string method): base(method, null)
{
}
public CommonRequest(string method, string version): base(method, version)
{
}
public override string GetMethod()
{
return "";
}
}
}

@ -0,0 +1,14 @@
using System;
using SDKCSharp.Response;
namespace SDKCSharp.Request
{
public class GetStoryRequest : BaseRequest<GetStoryResponse>
{
public override string GetMethod()
{
return "alipay.story.find";
}
}
}

@ -0,0 +1,53 @@
using System;
using Newtonsoft.Json;
namespace SDKCSharp.Response
{
/// <summary>
/// 返回的Response,新建Response要继承这个类
/// </summary>
public abstract class BaseResponse
{
/// <summary>
/// 状态码,0表示成功,其它都是失败
/// </summary>
[JsonProperty("code")]
public string Code { get; set; }
/// <summary>
/// 消息,如果有错误则为错误信息
/// </summary>
[JsonProperty("msg")]
public string Msg { get; set; }
/// <summary>
/// 错误状态码
/// </summary>
/// <value>The sub code.</value>
[JsonProperty("sub_code")]
public string SubCode { get; set; }
/// <summary>
/// 错误消息
/// </summary>
/// <value>The sub message.</value>
[JsonProperty("sub_msg")]
public string SubMsg { get; set; }
/// <summary>
/// 数据
/// </summary>
[JsonProperty("body")]
public string Body { get; set; }
/// <summary>
/// 是否成功
/// </summary>
/// <returns></returns>
public bool IsSuccess()
{
return string.IsNullOrEmpty(SubCode);
}
}
}

@ -0,0 +1,6 @@
namespace SDKCSharp.Response
{
public class CommonResponse : BaseResponse
{
}
}

@ -0,0 +1,18 @@
using System;
using Newtonsoft.Json;
namespace SDKCSharp.Response
{
public class GetStoryResponse: BaseResponse
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("gmt_create")]
public string GmtCreate { get; set; }
}
}

@ -0,0 +1,91 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SDKCSharp</RootNamespace>
<AssemblyName>SDKCSharp</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Crypto, Version=1.8.2.0, Culture=neutral, PublicKeyToken=0e99375e54769942">
<SpecificVersion>False</SpecificVersion>
<HintPath>Dll\BouncyCastle.Crypto.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json">
<HintPath>Dll\json\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Client\OpenHttp.cs" />
<Compile Include="Client\OpenRequest.cs" />
<Compile Include="Common\OpenConfig.cs" />
<Compile Include="Common\RequestForm.cs" />
<Compile Include="Common\UploadFile.cs" />
<Compile Include="Request\BaseRequest.cs" />
<Compile Include="Request\CommonRequest.cs" />
<Compile Include="Common\IgnoreSign.cs" />
<Compile Include="Client\OpenClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Common\SdkConfig.cs" />
<Compile Include="Response\BaseResponse.cs" />
<Compile Include="Response\CommonResponse.cs" />
<Compile Include="Utility\AESUtil.cs" />
<Compile Include="Utility\ClassUtil.cs" />
<Compile Include="Utility\FileUtil.cs" />
<Compile Include="Utility\JsonUtil.cs" />
<Compile Include="Utility\MD5Util.cs" />
<Compile Include="Utility\RSA.cs" />
<Compile Include="Utility\RSAUtil.cs" />
<Compile Include="Utility\SignUtil.cs" />
<Compile Include="Common\SopSignature.cs" />
<Compile Include="Model\GetStoryModel.cs" />
<Compile Include="Request\GetStoryRequest.cs" />
<Compile Include="Response\GetStoryResponse.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Dll\BouncyCastle.Crypto.dll" />
</ItemGroup>
<ItemGroup>
<Folder Include="Dll\json\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace SDKCSharp.Utility
{
/// <summary>
/// AES加解密.
/// 字符集:UTF-8
/// 算法模式:ECB
/// 补码方式:PKCS7Padding
/// 加密结果编码方式:Base64
/// </summary>
public class AESUtil
{
private static Encoding ENCODING_UTF8 = Encoding.UTF8;
/// <summary>
/// AES 加密
/// </summary>
/// <param name="data">明文(待加密)</param>
/// <param name="password">密文</param>
/// <returns>返回Base64字符串</returns>
public static string EncryptToBase64String(string data, string password)
{
if (string.IsNullOrEmpty(data)) return null;
Byte[] toEncryptArray = ENCODING_UTF8.GetBytes(data);
RijndaelManaged rm = new RijndaelManaged
{
Key = ENCODING_UTF8.GetBytes(password),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="data">密文(待解密)</param>
/// <param name="password">密码</param>
/// <returns>返回明文</returns>
public static string DecryptFromBase64String(string data, string password)
{
if (string.IsNullOrEmpty(data)) return null;
Byte[] toEncryptArray = Convert.FromBase64String(data);
RijndaelManaged rm = new RijndaelManaged
{
Key = ENCODING_UTF8.GetBytes(password),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return ENCODING_UTF8.GetString(resultArray);
}
}
}

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using System.Threading.Tasks;
using SDKCSharp.Request;
namespace SDKCSharp.Utility
{
public class ClassUtil
{
/// <summary>
/// 将普通对象转换成Dictionary
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static Dictionary<string, object> ConvertObjectToDictionary(object obj)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
if (obj == null)
{
return dict;
}
// 得到请求对象的所有属性
PropertyInfo[] properties = obj.GetType().GetProperties();
if (properties.Length <= 0)
{
return dict;
}
foreach (PropertyInfo propertyInfo in properties)
{
if (IsIgnoreSignProperty(propertyInfo))
{
continue;
}
string name = propertyInfo.Name.ToLower();
object value = propertyInfo.GetValue(obj, null);
// Console.WriteLine("{0}:{1}", name, value);
dict.Add(name, value);
}
return dict;
}
/// <summary>
/// 被[IgnoreSign]标记的字段名,如果被标记的话就不加入到签名算法中
/// </summary>
/// <param name="propertyInfo"></param>
/// <returns></returns>
private static bool IsIgnoreSignProperty(PropertyInfo propertyInfo)
{
Type ignoreSignType = typeof(IgnoreSign);
// 获取这个字段的元数据
object[] attrs = propertyInfo.GetCustomAttributes(false);
foreach (object attr in attrs)
{
if (attr.GetType().Equals(ignoreSignType))
{
return true;
}
}
return false;
}
}
}

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace SDKCSharp.Utility
{
public class FileUtil
{
/// <summary>
/// 获取文件名,带后缀
/// </summary>
/// <param name="filePath">文件全路径</param>
/// <returns>返回文件名</returns>
public static string GetFileName(string filePath)
{
return Path.GetFileName(filePath);
}
/// <summary>
/// 读取文件,将文件内容转成byte数组
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static byte[] ReadFile(string filePath)
{
return File.ReadAllBytes(filePath);
}
/// <summary>
/// 将FileStream内容转成byte数组
/// </summary>
/// <param name="fs">FileStream</param>
/// <returns></returns>
public static byte[] ReadFile(FileStream fs)
{
byte[] buffer = new byte[fs.Length];
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(buffer);
}
return buffer;
}
}
}

@ -0,0 +1,52 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SDKCSharp.Utility
{
/// <summary>
/// JSON序列化/反序列化工具
/// 使用Newtonsoft.Json组件,详见:https://www.newtonsoft.com/json
/// </summary>
public class JsonUtil
{
public const string EMPTY_JSON = "{}";
/// <summary>
/// JSON字符串转化成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T ParseObject<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);// //反序列化
}
/// <summary>
/// json字符串转换成Dictionary
/// </summary>
/// <returns>The to dictionary.</returns>
/// <param name="json">Json.</param>
public static Dictionary<string, object> ParseToDictionary(string json)
{
return JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
/// <summary>
/// 对象转换成json字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJSONString(object obj) {
if (obj == null)
{
return EMPTY_JSON;
}
return JsonConvert.SerializeObject(obj);
}
}
}

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace SDKCSharp.Utility
{
public class MD5Util
{
/// <summary>
/// MD5加密,全部大写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncryptToUpper(string input)
{
return Encrypt(input).ToUpper();
}
/// <summary>
/// 返回长度16串,小写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static String Encrypt16(String input)
{
return Encrypt(input).Substring(8, 16);
}
/// <summary>
/// MD5加密,全部小写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Encrypt(string input)
{
return Encrypt(Encoding.UTF8.GetBytes(input));
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="inputData"></param>
/// <returns>返回小写字母</returns>
public static string Encrypt(byte[] inputData)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(inputData);
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
}

@ -0,0 +1,210 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;
namespace SDKCSharp.Utility
{
public class RSA
{
private static Encoding Encoding_UTF8 = Encoding.UTF8;
/// <summary>
/// KEY 结构体
/// </summary>
public struct RSAKEY
{
/// <summary>
/// 公钥
/// </summary>
public string PublicKey
{
get;
set;
}
/// <summary>
/// 私钥
/// </summary>
public string PrivateKey
{
get;
set;
}
}
public RSAKEY GetKey()
{
//RSA密钥对的构造器
RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
//RSA密钥构造器的参数
RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
Org.BouncyCastle.Math.BigInteger.ValueOf(3),
new Org.BouncyCastle.Security.SecureRandom(),
1024, //密钥长度
25);
//用参数初始化密钥构造器
keyGenerator.Init(param);
//产生密钥对
AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
//获取公钥和密钥
AsymmetricKeyParameter publicKey = keyPair.Public;
AsymmetricKeyParameter privateKey = keyPair.Private;
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");
RSAKEY item = new RSAKEY()
{
PublicKey = Convert.ToBase64String(publicInfoByte),
PrivateKey = Convert.ToBase64String(privateInfoByte)
};
return item;
}
private AsymmetricKeyParameter GetPublicKeyParameter(string keyBase64)
{
keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
byte[] publicInfoByte = Convert.FromBase64String(keyBase64);
Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入
AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
return pubKey;
}
private AsymmetricKeyParameter GetPrivateKeyParameter(string keyBase64)
{
keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
byte[] privateInfoByte = Convert.FromBase64String(keyBase64);
// Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入
// PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
return priKey;
}
/// <summary>
/// 私钥加密
/// </summary>
/// <param name="data">加密内容</param>
/// <param name="privateKey">私钥(Base64后的)</param>
/// <returns>返回Base64内容</returns>
public string EncryptByPrivateKey(string data, string privateKey)
{
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//加密
try
{
engine.Init(true, GetPrivateKeyParameter(privateKey));
byte[] byteData = Encoding_UTF8.GetBytes(data);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return Convert.ToBase64String(ResultData);
//Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 私钥解密
/// </summary>
/// <param name="data">待解密的内容</param>
/// <param name="privateKey">私钥(Base64编码后的)</param>
/// <returns>返回明文</returns>
public string DecryptByPrivateKey(string data, string privateKey)
{
data = data.Replace("\r", "").Replace("\n", "").Replace(" ", "");
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//解密
try
{
engine.Init(false, GetPrivateKeyParameter(privateKey));
byte[] byteData = Convert.FromBase64String(data);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return Encoding_UTF8.GetString(ResultData);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 公钥加密
/// </summary>
/// <param name="data">加密内容</param>
/// <param name="publicKey">公钥(Base64编码后的)</param>
/// <returns>返回Base64内容</returns>
public string EncryptByPublicKey(string data, string publicKey)
{
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//加密
try
{
engine.Init(true, GetPublicKeyParameter(publicKey));
byte[] byteData = Encoding_UTF8.GetBytes(data);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return Convert.ToBase64String(ResultData);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 公钥解密
/// </summary>
/// <param name="data">待解密的内容</param>
/// <param name="publicKey">公钥(Base64编码后的)</param>
/// <returns>返回明文</returns>
public string DecryptByPublicKey(string data, string publicKey)
{
data = data.Replace("\r", "").Replace("\n", "").Replace(" ", "");
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//解密
try
{
engine.Init(false, GetPublicKeyParameter(publicKey));
byte[] byteData = Convert.FromBase64String(data);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return Encoding_UTF8.GetString(ResultData);
}
catch (Exception ex)
{
throw ex;
}
}
}
}

@ -0,0 +1,47 @@
using System;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;
namespace SDKCSharp.Utility
{
public class RSAUtil
{
static Encoding UTF8 = Encoding.UTF8;
static RSA rsa = new RSA();
/// <summary>
/// 私钥加密
/// </summary>
/// <returns>The by private key.</returns>
/// <param name="data">内容.</param>
/// <param name="privateKey">私钥.</param>
public static string EncryptByPrivateKey(string data, string privateKey)
{
return rsa.EncryptByPrivateKey(data, privateKey);
}
}
}

@ -0,0 +1,43 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SDKCSharp.Utility
{
/// <summary>
/// 签名工具类
/// </summary>
public class SignUtil
{
/// <summary>
/// 参数签名
/// </summary>
/// <param name="paramsMap">参数</param>
/// <param name="secret">秘钥</param>
/// <returns>返回sign</returns>
public static String CreateSign(Dictionary<string, object> paramsMap, string secret)
{
StringBuilder sb = new StringBuilder();
ArrayList paramNames = new ArrayList(paramsMap.Keys);
paramNames.Sort();
sb.Append(secret);
foreach (string paramName in paramNames)
{
sb.Append(paramName).Append(paramsMap[paramName]);
}
sb.Append(secret);
string source = sb.ToString();
return MD5Util.EncryptToUpper(source);
}
}
}

@ -0,0 +1,83 @@
using System;
using System.Collections;
using System.Collections.Generic;
using SDKCSharp.Client;
using SDKCSharp.Model;
using SDKCSharp.Request;
using SDKCSharp.Response;
using SDKCSharp.Utility;
namespace SDKTest
{
class MainClass
{
static string url = "http://localhost:8081/api"; // zuul
static string appId = "2019032617262200001";
// 支付宝私钥
static string privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXJv1pQFqWNA/++OYEV7WYXwexZK/J8LY1OWlP9X0T6wHFOvxNKRvMkJ5544SbgsJpVcvRDPrcxmhPbi/sAhdO4x2PiPKIz9Yni2OtYCCeaiE056B+e1O2jXoLeXbfi9fPivJZkxH/tb4xfLkH3bA8ZAQnQsoXA0SguykMRZntF0TndUfvDrLqwhlR8r5iRdZLB6F8o8qXH6UPDfNEnf/K8wX5T4EB1b8x8QJ7Ua4GcIUqeUxGHdQpzNbJdaQvoi06lgccmL+PHzminkFYON7alj1CjDN833j7QMHdPtS9l7B67fOU/p2LAAkPMtoVBfxQt9aFj7B8rEhGCz02iJIBAgMBAAECggEARqOuIpY0v6WtJBfmR3lGIOOokLrhfJrGTLF8CiZMQha+SRJ7/wOLPlsH9SbjPlopyViTXCuYwbzn2tdABigkBHYXxpDV6CJZjzmRZ+FY3S/0POlTFElGojYUJ3CooWiVfyUMhdg5vSuOq0oCny53woFrf32zPHYGiKdvU5Djku1onbDU0Lw8w+5tguuEZ76kZ/lUcccGy5978FFmYpzY/65RHCpvLiLqYyWTtaNT1aQ/9pw4jX9HO9NfdJ9gYFK8r/2f36ZE4hxluAfeOXQfRC/WhPmiw/ReUhxPznG/WgKaa/OaRtAx3inbQ+JuCND7uuKeRe4osP2jLPHPP6AUwQKBgQDUNu3BkLoKaimjGOjCTAwtp71g1oo+k5/uEInAo7lyEwpV0EuUMwLA/HCqUgR4K9pyYV+Oyb8d6f0+Hz0BMD92I2pqlXrD7xV2WzDvyXM3s63NvorRooKcyfd9i6ccMjAyTR2qfLkxv0hlbBbsPHz4BbU63xhTJp3Ghi0/ey/1HQKBgQC2VsgqC6ykfSidZUNLmQZe3J0p/Qf9VLkfrQ+xaHapOs6AzDU2H2osuysqXTLJHsGfrwVaTs00ER2z8ljTJPBUtNtOLrwNRlvgdnzyVAKHfOgDBGwJgiwpeE9voB1oAV/mXqSaUWNnuwlOIhvQEBwekqNyWvhLqC7nCAIhj3yvNQKBgQCqYbeec56LAhWP903Zwcj9VvG7sESqXUhIkUqoOkuIBTWFFIm54QLTA1tJxDQGb98heoCIWf5x/A3xNI98RsqNBX5JON6qNWjb7/dobitti3t99v/ptDp9u8JTMC7penoryLKK0Ty3bkan95Kn9SC42YxaSghzqkt+uvfVQgiNGQKBgGxU6P2aDAt6VNwWosHSe+d2WWXt8IZBhO9d6dn0f7ORvcjmCqNKTNGgrkewMZEuVcliueJquR47IROdY8qmwqcBAN7Vg2K7r7CPlTKAWTRYMJxCT1Hi5gwJb+CZF3+IeYqsJk2NF2s0w5WJTE70k1BSvQsfIzAIDz2yE1oPHvwVAoGAA6e+xQkVH4fMEph55RJIZ5goI4Y76BSvt2N5OKZKd4HtaV+eIhM3SDsVYRLIm9ZquJHMiZQGyUGnsvrKL6AAVNK7eQZCRDk9KQz+0GKOGqku0nOZjUbAu6A2/vtXAaAuFSFx1rUQVVjFulLexkXR3KcztL1Qu2k5pB6Si0K/uwQ=";
// 声明一个就行
static OpenClient client = new OpenClient(url, appId, privateKey);
public static void Main(string[] args)
{
TestGet();
}
// 标准用法
private static void TestGet()
{
// 创建请求对象
GetStoryRequest request = new GetStoryRequest();
// 请求参数
GetStoryModel model = new GetStoryModel();
model.Name = "白雪公主";
request.BizModel = model;
// 发送请求
GetStoryResponse response = client.Execute(request);
if (response.IsSuccess())
{
// 返回结果
Console.WriteLine("故事名称:{0}", response.Name);
}
else
{
Console.WriteLine("错误, code:{0}, msg:{1}, subCode:{2}, subMsg:{3}",
response.Code, response.Msg, response.SubCode, response.SubMsg);
}
}
// 懒人版,如果不想添加Request,Response,Model。可以用这种方式,返回全部是String,后续自己处理json
private static void TestCommon()
{
// 创建请求对象
CommonRequest request = new CommonRequest("alipay.story.find");
// 请求参数
Dictionary<string, string> bizModel = new Dictionary<string, string>
{
["name"] = "白雪公主"
};
request.BizModel = bizModel;
// 发送请求
CommonResponse response = client.Execute(request);
if (response.IsSuccess())
{
// 返回结果
string body = response.Body;
Dictionary<string, object> dict = JsonUtil.ParseToDictionary(body);
Console.WriteLine(dict.ToString());
}
else
{
Console.WriteLine("错误, code:{0}, msg:{1}, subCode:{2}, subMsg:{3}",
response.Code, response.Msg, response.SubCode, response.SubMsg);
}
}
}
}

@ -0,0 +1,26 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("SDKTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{34D6DDAB-895D-4B31-A18F-157BBF6393A1}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>SDKTest</RootNamespace>
<AssemblyName>SDKTest</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ExternalConsole>true</ExternalConsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ExternalConsole>true</ExternalConsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SDKCSharp\SDKCSharp.csproj">
<Project>{5461AAE5-F701-4A39-9D81-22BC6A80CFF9}</Project>
<Name>SDKCSharp</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,181 @@
# sdk-csharp
C#对应的SDK
- SDKCSharp: SDK源码,在此基础上添加接口
- SDKTest: 测试用例
## 接口封装步骤
比如获取故事信息接口
- 接口名:alipay.story.find
- 版本号:1.0
- 参数:name 故事名称
- 返回信息
```
{
"alipay_story_find_response": {
"msg": "Success",
"code": "10000",
"name": "白雪公主",
"id": 1,
"gmtCreate": 1554193987378
},
"sign": "xxxxx"
}
```
针对这个接口,封装步骤如下:
1.在`Model`包下新建一个类,定义业务参数
```
namespace SDKCSharp.Model
{
public class GetStoryModel
{
/// <summary>
/// 故事名称
/// </summary>
/// <value>The name.</value>
[JsonProperty("name")]
public string Name { get; set; }
}
}
```
`[JsonProperty("name")]`是Newtonsoft.Json组件中的类,用于Json序列化,括号中的是参数名称。
类似于Java中的注解,`@JSONField(name = "xx")`
2.在`Response`包下新建一个返回类GetStoryResponse,继承`BaseResponse`
里面填写返回的字段
```
namespace SDKCSharp.Response
{
public class GetStoryResponse: BaseResponse
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("gmt_create")]
public string GmtCreate { get; set; }
}
}
```
3.在`Request`文件夹下新建一个请求类,继承`BaseRequest`
BaseRequest中有个泛型参数,填`GetStoryResponse`类,表示这个请求对应的返回类。
重写`GetMethod()`方法,填接口名。
如果要指定版本号,可重写`GetVersion()`方法,或者后续使用`request.Version = version`进行设置
```
namespace SDKCSharp.Request
{
public class GetStoryRequest : BaseRequest<GetStoryResponse>
{
public override string GetMethod()
{
return "alipay.story.find";
}
}
}
```
## 使用方式
```
class MainClass
{
static string url = "http://localhost:8081/api"; // zuul
static string appId = "2019032617262200001";
// 支付宝私钥
static string privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXJv1pQFqWNA/++OYEV7WYXwexZK/J8LY1OWlP9X0T6wHFOvxNKRvMkJ5544SbgsJpVcvRDPrcxmhPbi/sAhdO4x2PiPKIz9Yni2OtYCCeaiE056B+e1O2jXoLeXbfi9fPivJZkxH/tb4xfLkH3bA8ZAQnQsoXA0SguykMRZntF0TndUfvDrLqwhlR8r5iRdZLB6F8o8qXH6UPDfNEnf/K8wX5T4EB1b8x8QJ7Ua4GcIUqeUxGHdQpzNbJdaQvoi06lgccmL+PHzminkFYON7alj1CjDN833j7QMHdPtS9l7B67fOU/p2LAAkPMtoVBfxQt9aFj7B8rEhGCz02iJIBAgMBAAECggEARqOuIpY0v6WtJBfmR3lGIOOokLrhfJrGTLF8CiZMQha+SRJ7/wOLPlsH9SbjPlopyViTXCuYwbzn2tdABigkBHYXxpDV6CJZjzmRZ+FY3S/0POlTFElGojYUJ3CooWiVfyUMhdg5vSuOq0oCny53woFrf32zPHYGiKdvU5Djku1onbDU0Lw8w+5tguuEZ76kZ/lUcccGy5978FFmYpzY/65RHCpvLiLqYyWTtaNT1aQ/9pw4jX9HO9NfdJ9gYFK8r/2f36ZE4hxluAfeOXQfRC/WhPmiw/ReUhxPznG/WgKaa/OaRtAx3inbQ+JuCND7uuKeRe4osP2jLPHPP6AUwQKBgQDUNu3BkLoKaimjGOjCTAwtp71g1oo+k5/uEInAo7lyEwpV0EuUMwLA/HCqUgR4K9pyYV+Oyb8d6f0+Hz0BMD92I2pqlXrD7xV2WzDvyXM3s63NvorRooKcyfd9i6ccMjAyTR2qfLkxv0hlbBbsPHz4BbU63xhTJp3Ghi0/ey/1HQKBgQC2VsgqC6ykfSidZUNLmQZe3J0p/Qf9VLkfrQ+xaHapOs6AzDU2H2osuysqXTLJHsGfrwVaTs00ER2z8ljTJPBUtNtOLrwNRlvgdnzyVAKHfOgDBGwJgiwpeE9voB1oAV/mXqSaUWNnuwlOIhvQEBwekqNyWvhLqC7nCAIhj3yvNQKBgQCqYbeec56LAhWP903Zwcj9VvG7sESqXUhIkUqoOkuIBTWFFIm54QLTA1tJxDQGb98heoCIWf5x/A3xNI98RsqNBX5JON6qNWjb7/dobitti3t99v/ptDp9u8JTMC7penoryLKK0Ty3bkan95Kn9SC42YxaSghzqkt+uvfVQgiNGQKBgGxU6P2aDAt6VNwWosHSe+d2WWXt8IZBhO9d6dn0f7ORvcjmCqNKTNGgrkewMZEuVcliueJquR47IROdY8qmwqcBAN7Vg2K7r7CPlTKAWTRYMJxCT1Hi5gwJb+CZF3+IeYqsJk2NF2s0w5WJTE70k1BSvQsfIzAIDz2yE1oPHvwVAoGAA6e+xQkVH4fMEph55RJIZ5goI4Y76BSvt2N5OKZKd4HtaV+eIhM3SDsVYRLIm9ZquJHMiZQGyUGnsvrKL6AAVNK7eQZCRDk9KQz+0GKOGqku0nOZjUbAu6A2/vtXAaAuFSFx1rUQVVjFulLexkXR3KcztL1Qu2k5pB6Si0K/uwQ=";
// 声明一个就行
static OpenClient client = new OpenClient(url, appId, privateKey);
public static void Main(string[] args)
{
TestGet();
}
// 标准用法
private static void TestGet()
{
// 创建请求对象
GetStoryRequest request = new GetStoryRequest();
// 请求参数
GetStoryModel model = new GetStoryModel();
model.Name = "白雪公主";
request.BizModel = model;
// 发送请求
GetStoryResponse response = client.Execute(request);
if (response.IsSuccess())
{
// 返回结果
Console.WriteLine("故事名称:{0}", response.Name);
}
else
{
Console.WriteLine("错误, code:{0}, msg:{1}, subCode:{2}, subMsg:{3}",
response.Code, response.Msg, response.SubCode, response.SubMsg);
}
}
}
```
# 使用方式2(懒人版)
如果不想添加Request,Response,Model。可以用这种方式,返回data部分是Dictionary<string, object>,后续自己处理
```
// 懒人版,如果不想添加Request,Response,Model。可以用这种方式,返回全部是String,后续自己处理json
private static void TestCommon()
{
// 创建请求对象
CommonRequest request = new CommonRequest("alipay.story.find");
// 请求参数
Dictionary<string, string> bizModel = new Dictionary<string, string>
{
["name"] = "白雪公主"
};
request.BizModel = bizModel;
// 发送请求
CommonResponse response = client.Execute(request);
if (response.IsSuccess())
{
// 返回结果
string body = response.Body;
Dictionary<string, object> dict = JsonUtil.ParseToDictionary(body);
Console.WriteLine(dict.ToString());
}
else
{
Console.WriteLine("错误, code:{0}, msg:{1}, subCode:{2}, subMsg:{3}",
response.Code, response.Msg, response.SubCode, response.SubMsg);
}
}
```
Loading…
Cancel
Save