源码: https://github.com/aspros-luo/Qwerty.Payment/tree/develop
今天开始微信支付
微信支付坑比较多,支付流程也不太一样,微信支付需要先生成预支付单,然后再具体调用
具体参考微信sdk
1:微信支付主体,用于存储键值字典,等相关方法
internal class WxPayData
{
public WxPayData()
{ } //采用排序的Dictionary的好处是方便对数据包进行签名,不用再签名之前再做一次排序
private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>(); /**
* 设置某个字段的值
* @param key 字段名
* @param value 字段值
*/
public void SetValue(string key, object value)
{
m_values[key] = value;
} /**
* 根据字段名获取某个字段的值
* @param key 字段名
* @return key对应的字段值
*/
public object GetValue(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
return o;
} /**
* 判断某个字段是否已设置
* @param key 字段名
* @return 若字段key已被设置,则返回true,否则返回false
*/
public bool IsSet(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
if (null != o)
return true;
else
return false;
} /**
* @将Dictionary转成xml
* @return 经转换得到的xml串
* @throws WxPayException
**/
public string ToXml()
{
//数据为空时不能转化为xml格式
if ( == m_values.Count)
{
throw new Exception("WxPayData数据为空!");
} string xml = "<xml>";
foreach (KeyValuePair<string, object> pair in m_values)
{
//字段值不能为null,会影响后续流程
if (pair.Value == null)
{
throw new Exception("WxPayData内部含有值为null的字段!");
} if (pair.Value.GetType() == typeof(int))
{
xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
}
else if (pair.Value.GetType() == typeof(string))
{
xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
}
else//除了string和int类型不能含有其他数据类型
{ throw new Exception("WxPayData字段数据类型错误!");
}
}
xml += "</xml>";
return xml;
} /**
* @将xml转为WxPayData对象并返回对象内部的数据
* @param string 待转换的xml串
* @return 经转换得到的Dictionary
* @throws WxPayException
*/
public SortedDictionary<string, object> FromXml(string xml)
{
if (string.IsNullOrEmpty(xml))
{
throw new Exception("将空的xml串转换为WxPayData不合法!");
} XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
XmlNodeList nodes = xmlNode.ChildNodes;
foreach (XmlNode xn in nodes)
{
XmlElement xe = (XmlElement)xn;
m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
} try
{
//2015-06-29 错误是没有签名
if (m_values["return_code"].ToString() != "SUCCESS")
{
return m_values;
}
CheckSign();//验证签名,不通过会抛异常
}
catch (Exception ex)
{
throw new Exception(ex.Message);
} return m_values;
} /**
* @Dictionary格式转化成url参数格式
* @ return url格式串, 该串不包含sign字段值
*/
public string ToUrl()
{
string buff = "";
foreach (KeyValuePair<string, object> pair in m_values)
{
if (pair.Value == null)
{
throw new Exception("WxPayData内部含有值为null的字段!");
} if (pair.Key != "sign" && pair.Value.ToString() != "")
{
buff += pair.Key + "=" + pair.Value + "&";
}
}
buff = buff.Trim('&');
return buff;
} /**
* @Dictionary格式化成Json
* @return json串数据
*/
public string ToJson()
{
string jsonStr = JsonConvert.SerializeObject(m_values);
return jsonStr;
} /**
* @values格式化成能在Web页面上显示的结果(因为web页面上不能直接输出xml格式的字符串)
*/
public string ToPrintStr()
{
string str = "";
foreach (KeyValuePair<string, object> pair in m_values)
{
if (pair.Value == null)
{ throw new Exception("WxPayData内部含有值为null的字段!");
} str += string.Format("{0}={1}<br>", pair.Key, pair.Value.ToString());
} return str;
} /**
* @生成签名,详见签名生成算法
* @return 签名, sign字段不参加签名
*/
public string MakeSign()
{
//转url格式
string str = ToUrl();
//在string后加入API KEY
str += "&key=" + WxPayConfig.KEY;
//MD5加密
var md5 = MD5.Create();
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
//所有字符转为大写
return sb.ToString().ToUpper();
} /**
*
* 检测签名是否正确
* 正确返回true,错误抛异常
*/
public bool CheckSign()
{
//如果没有设置签名,则跳过检测
if (!IsSet("sign"))
{ throw new Exception("WxPayData签名存在但不合法!");
}
//如果设置了签名但是签名为空,则抛异常
else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
{ throw new Exception("WxPayData签名存在但不合法!");
} //获取接收到的签名
string return_sign = GetValue("sign").ToString(); //在本地计算新的签名
string cal_sign = MakeSign(); if (cal_sign == return_sign)
{
return true;
} throw new Exception("WxPayData签名验证错误!");
} /**
* @获取Dictionary
*/
public SortedDictionary<string, object> GetValues()
{
return m_values;
}
}
2:微信支付api类,主要用于一些基础方法,生成时间戳,随机字符,快速上报,退款,退款查询等功能,详见代码,
internal class WxPayApi
{
/**
* 提交被扫支付API
* 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台,
* 由商户收银台或者商户后台调用该接口发起支付。
* @param WxPayData inputObj 提交给被扫支付API的参数
* @param int timeOut 超时时间
* @throws WxPayException
* @return 成功时返回调用结果,其他抛异常
*/
public static async Task<WxPayData> Micropay(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/pay/micropay";
//检测必填参数
if (!inputObj.IsSet("body"))
{
throw new Exception("提交被扫支付API接口中,缺少必填参数body!");
}
else if (!inputObj.IsSet("out_trade_no"))
{
throw new Exception("提交被扫支付API接口中,缺少必填参数out_trade_no!");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new Exception("提交被扫支付API接口中,缺少必填参数total_fee!");
}
else if (!inputObj.IsSet("auth_code"))
{
throw new Exception("提交被扫支付API接口中,缺少必填参数auth_code!");
} inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = await HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 查询订单
* @param WxPayData inputObj 提交给查询订单API的参数
* @param int timeOut 超时时间
* @throws WxPayException
* @return 成功时返回订单查询结果,其他抛异常
*/
public static async Task<WxPayData> OrderQuery(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/pay/orderquery";
//检测必填参数
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
{
throw new Exception("订单查询接口中,out_trade_no、transaction_id至少填一个!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now; string response = await HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口提交数据 var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的数据转化为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 撤销订单API接口
* @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个
* @param int timeOut 接口超时时间
* @throws WxPayException
* @return 成功时返回API调用结果,其他抛异常
*/
public static async Task<WxPayData> Reverse(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
//检测必填参数
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
{
throw new Exception("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = await HttpService.Post(xml, url, true, timeOut); var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 申请退款
* @param WxPayData inputObj 提交给申请退款API的参数
* @param int timeOut 超时时间
* @throws WxPayException
* @return 成功时返回接口调用结果,其他抛异常
*/
public static async Task<WxPayData> Refund(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//检测必填参数
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
{
throw new Exception("退款申请接口中,out_trade_no、transaction_id至少填一个!");
}
else if (!inputObj.IsSet("out_refund_no"))
{
throw new Exception("退款申请接口中,缺少必填参数out_refund_no!");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new Exception("退款申请接口中,缺少必填参数total_fee!");
}
else if (!inputObj.IsSet("refund_fee"))
{
throw new Exception("退款申请接口中,缺少必填参数refund_fee!");
}
else if (!inputObj.IsSet("op_user_id"))
{
throw new Exception("退款申请接口中,缺少必填参数op_user_id!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml();
var start = DateTime.Now; string response = await HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 查询退款
* 提交退款申请后,通过该接口查询退款状态。退款有一定延时,
* 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
* out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个
* @param WxPayData inputObj 提交给查询退款API的参数
* @param int timeOut 接口超时时间
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static async Task<WxPayData> RefundQuery(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/pay/refundquery";
//检测必填参数
if (!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") &&
!inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id"))
{
throw new Exception("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = await HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
* 下载对账单
* @param WxPayData inputObj 提交给下载对账单API的参数
* @param int timeOut 接口超时时间
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static async Task<WxPayData> DownloadBill(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/pay/downloadbill";
//检测必填参数
if (!inputObj.IsSet("bill_date"))
{
throw new Exception("对账单接口中,缺少必填参数bill_date!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); string response = await HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API WxPayData result = new WxPayData();
//若接口调用失败会返回xml格式的结果
if (response.Substring(, ) == "<xml>")
{
result.FromXml(response);
}
//接口调用成功则返回非xml格式的数据
else
result.SetValue("result", response); return result;
} /**
*
* 转换短链接
* 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX),
* 减小二维码数据量,提升扫描速度和精确度。
* @param WxPayData inputObj 提交给转换短连接API的参数
* @param int timeOut 接口超时时间
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static async Task<WxPayData> ShortUrl(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/tools/shorturl";
//检测必填参数
if (!inputObj.IsSet("long_url"))
{
throw new Exception("需要转换的URL,签名用原串,传输需URL encode!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = await HttpService.Post(xml, url, false, timeOut); var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 统一下单
* @param WxPaydata inputObj 提交给统一下单API的参数
* @param int timeOut 超时时间
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static async Task<WxPayData> UnifiedOrder(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//检测必填参数
if (!inputObj.IsSet("out_trade_no"))
{
throw new Exception("缺少统一支付接口必填参数out_trade_no!");
}
else if (!inputObj.IsSet("body"))
{
throw new Exception("缺少统一支付接口必填参数body!");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new Exception("缺少统一支付接口必填参数total_fee!");
}
else if (!inputObj.IsSet("trade_type"))
{
throw new Exception("缺少统一支付接口必填参数trade_type!");
} //关联参数
if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
{
throw new Exception("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
}
if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
{
throw new Exception("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
} //异步通知url未设置,则使用配置文件中的url
if (!inputObj.IsSet("notify_url"))
{
inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
//inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 //签名
inputObj.SetValue("sign", inputObj.MakeSign());
string xml = inputObj.ToXml(); var start = DateTime.Now; string response = await HttpService.Post(xml, url, false, timeOut); var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 关闭订单
* @param WxPayData inputObj 提交给关闭订单API的参数
* @param int timeOut 接口超时时间
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static async Task<WxPayData> CloseOrder(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/pay/closeorder";
//检测必填参数
if (!inputObj.IsSet("out_trade_no"))
{
throw new Exception("关闭订单接口中,out_trade_no必填!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = await HttpService.Post(xml, url, false, timeOut); var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData();
result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result;
} /**
*
* 测速上报
* @param string interface_url 接口URL
* @param int timeCost 接口耗时
* @param WxPayData inputObj参数数组
*/
private static async void ReportCostTime(string interfaceUrl, int timeCost, WxPayData inputObj)
{
//如果不需要进行上报 //如果仅失败上报
if (inputObj.IsSet("return_code") && inputObj.GetValue("return_code").ToString() == "SUCCESS" &&
inputObj.IsSet("result_code") && inputObj.GetValue("result_code").ToString() == "SUCCESS")
{
return;
} //上报逻辑
WxPayData data = new WxPayData();
data.SetValue("interface_url", interfaceUrl);
data.SetValue("execute_time_", timeCost);
//返回状态码
if (inputObj.IsSet("return_code"))
{
data.SetValue("return_code", inputObj.GetValue("return_code"));
}
//返回信息
if (inputObj.IsSet("return_msg"))
{
data.SetValue("return_msg", inputObj.GetValue("return_msg"));
}
//业务结果
if (inputObj.IsSet("result_code"))
{
data.SetValue("result_code", inputObj.GetValue("result_code"));
}
//错误代码
if (inputObj.IsSet("err_code"))
{
data.SetValue("err_code", inputObj.GetValue("err_code"));
}
//错误代码描述
if (inputObj.IsSet("err_code_des"))
{
data.SetValue("err_code_des", inputObj.GetValue("err_code_des"));
}
//商户订单号
if (inputObj.IsSet("out_trade_no"))
{
data.SetValue("out_trade_no", inputObj.GetValue("out_trade_no"));
}
//设备号
if (inputObj.IsSet("device_info"))
{
data.SetValue("device_info", inputObj.GetValue("device_info"));
} try
{
await Report(data);
}
catch (Exception)
{
//不做任何处理
}
} /**
*
* 测速上报接口实现
* @param WxPayData inputObj 提交给测速上报接口的参数
* @param int timeOut 测速上报接口超时时间
* @throws WxPayException
* @return 成功时返回测速上报接口返回的结果,其他抛异常
*/
public static async Task<WxPayData> Report(WxPayData inputObj, int timeOut = )
{
string url = "https://api.mch.weixin.qq.com/payitil/report";
//检测必填参数
if (!inputObj.IsSet("interface_url"))
{
throw new Exception("接口URL,缺少必填参数interface_url!");
}
if (!inputObj.IsSet("return_code"))
{
throw new Exception("返回状态码,缺少必填参数return_code!");
}
if (!inputObj.IsSet("result_code"))
{
throw new Exception("业务结果,缺少必填参数result_code!");
}
if (!inputObj.IsSet("user_ip"))
{
throw new Exception("访问接口IP,缺少必填参数user_ip!");
}
if (!inputObj.IsSet("execute_time_"))
{
throw new Exception("接口耗时,缺少必填参数execute_time_!");
} inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("user_ip", WxPayConfig.IP);//终端ip
inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss"));//商户上报时间
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml(); string response = await HttpService.Post(xml, url, false, timeOut); WxPayData result = new WxPayData();
result.FromXml(response);
return result;
} /**
* 根据当前系统时间加随机序列来生成订单号
* @return 订单号
*/
public static string GenerateOutTradeNo()
{
var ran = new Random();
return string.Format("{0}{1}{2}", WxPayConfig.MCHID, DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next());
} /**
* 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数
* @return 时间戳
*/
public static string GenerateTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(, , , , , , );
return Convert.ToInt64(ts.TotalSeconds).ToString();
} /**
* 生成随机串,随机串包含字母或数字
* @return 随机串
*/
public static string GenerateNonceStr()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
}
3:支付业务主体类,这里要优先解决app支付,app支付的坑比较多
internal class AppPay
{
public async Task<WxPayData> Run(string body, string outTradeNo, int totalFee)
{
var data = new WxPayData();
data.SetValue("body", body);//商品描述
//data.SetValue("attach", outTradeIds);//附加数据
data.SetValue("out_trade_no", outTradeNo);//随机字符串
data.SetValue("total_fee", totalFee);//总金额
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
data.SetValue("time_expire", DateTime.Now.AddMinutes().ToString("yyyyMMddHHmmss"));//交易结束时间
//data.SetValue("goods_tag", "jjj");//商品标记
data.SetValue("trade_type", "APP");//交易类型
var result = await WxPayApi.UnifiedOrder(data);//调用统一下单接口
return result;
}
}
创建支付主体类,将支付信息填充进去,调用wxapi统一下单方法,返回数据
因为app支付需要二次加签,所以返回的数据需要解析后,再次加签,将返回的数据给app调用sdk支付
二次加签方法:
public string AppSign(string preJson)
{
var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(preJson);
var data = new WxPayData();
data.SetValue("appid", dic["appid"]);
data.SetValue("partnerid", dic["mch_id"]);
data.SetValue("prepayid", dic["prepay_id"]);
data.SetValue("package", "Sign=WXPay");
data.SetValue("noncestr", WxPayApi.GenerateNonceStr());
data.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
data.SetValue("sign", data.MakeSign());
return data.ToJson();
}
值得注意的地方是:
a.timestamp用当前时间戳在Android端亦是可行,iOS不行,所以这里依然使用wxpayapi里面的获取时间戳方法
b.partnerid对应的是mchid,即商户号
其他支付业务类
/// <summary>
/// 微信公众号支付
/// </summary>
internal class JsApiPay
{
/// <summary>
/// 保存页面对象,因为要在类的方法中使用Page的Request对象
/// </summary>
//private HttpContext page { get; set; } /// <summary>
/// openid用于调用统一下单接口
/// </summary>
//public string openid { get; set; } /// <summary>
/// access_token用于获取收货地址js函数入口参数
/// </summary>
//public string access_token { get; set; } /// <summary>
/// 商品金额,用于统一下单
/// </summary>
//public int total_fee { get; set; } /// <summary>
/// 统一下单接口返回结果
/// </summary>
private WxPayData _unifiedOrderResult { get; set; } //public JsApiPay(HttpContext page)
//{
// this.page = page;
//}
public JsApiPay()
{ } /**
*
* 网页授权获取用户基本信息的全部过程
* 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
* 第一步:利用url跳转获取code
* 第二步:利用code去获取openid和access_token
*
*/
//public void GetOpenidAndAccessToken(string tradeId)
//{
// if (!string.IsNullOrEmpty(page.Request.Form["code"]))
// {
// //获取code码,以获取openid和access_token
// string code = page.Request.Form["code"];
// //Log.Debug(this.GetType().ToString(), "Get code : " + code);
// GetOpenidAndAccessTokenFromCode(code);
// }
// else
// {
// //构造网页授权获取code的URL
// string redirect_uri = WebUtility.UrlEncode("http://m.aiqinhaigou.com/payment/wechat_callback.html?tradeId=" + tradeId);
// WxPayData data = new WxPayData();
// data.SetValue("appid", WxPayConfig.APPID);
// data.SetValue("redirect_uri", redirect_uri);
// data.SetValue("response_type", "code");
// data.SetValue("scope", "snsapi_base");
// data.SetValue("state", "STATE" + "#wechat_redirect");
// string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
// //Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url);
// try
// {
// //触发微信返回code码
// page.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
// }
// catch (Exception ex)
// {
// throw new Exception(ex.ToString());
// }
// }
//} /// <summary>
/// 获取回Openid
/// </summary>
/// <returns></returns>
//public string GetOauthCode(string tradeId)
//{
// //构造网页授权获取code的URL
// string redirect_uri = WebUtility.UrlEncode("http://m.aiqinhaigou.com/payment/wechat_callback.html?tradeId=" + tradeId);
// WxPayData data = new WxPayData();
// data.SetValue("appid", WxPayConfig.APPID);
// data.SetValue("redirect_uri", redirect_uri);
// data.SetValue("response_type", "code");
// data.SetValue("scope", "snsapi_base");
// data.SetValue("state", "STATE" + "#wechat_redirect");
// var url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
// //LogManager.GetLogger(typeof(JsApiPay)).Info("微信支付回调地址:{0}", redirect_uri);
// return url;
//}
/**
*
* 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下:
* {
* "access_token":"ACCESS_TOKEN",
* "expires_in":7200,
* "refresh_token":"REFRESH_TOKEN",
* "openid":"OPENID",
* "scope":"SCOPE",
* "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
* }
* 其中access_token可用于获取共享收货地址
* openid是微信支付jsapi支付接口统一下单时必须的参数
* 更详细的说明请参考网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
* @失败时抛异常WxPayException
*/
//public void GetOpenidAndAccessTokenFromCode(string code)
//{
// try
// {
// //构造获取openid及access_token的url
// WxPayData data = new WxPayData();
// data.SetValue("appid", WxPayConfig.APPID);
// data.SetValue("secret", WxPayConfig.APPSECRET);
// data.SetValue("code", code);
// data.SetValue("grant_type", "authorization_code");
// string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl(); // //请求url以获取数据
// string result = HttpService.Get(url); // //Log.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result); // //保存access_token,用于收货地址获取
// var jd = JObject.Parse(result);
// access_token = (string)jd["access_token"]; // //获取用户openid
// openid = (string)jd["openid"]; // //Log.Debug(this.GetType().ToString(), "Get openid : " + openid);
// //Log.Debug(this.GetType().ToString(), "Get access_token : " + access_token);
// }
// catch (Exception ex)
// {
// //Log.Error(this.GetType().ToString(), ex.ToString());
// throw new Exception(ex.ToString());
// }
//}
/**
* 调用统一下单,获得下单结果
* @return 统一下单结果
* @失败时抛异常WxPayException
*/
public async Task<WxPayData> GetUnifiedOrderResult(string body, string outTradeNo, int totalFee, string openId)
{
//统一下单
var data = new WxPayData();
data.SetValue("body", body);
//data.SetValue("attach", outTradeIds);
data.SetValue("out_trade_no", outTradeNo);
data.SetValue("total_fee", totalFee);
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
data.SetValue("time_expire", DateTime.Now.AddMinutes().ToString("yyyyMMddHHmmss"));
//data.SetValue("goods_tag", remark);
data.SetValue("trade_type", "JSAPI");
data.SetValue("openid", openId); var result = await WxPayApi.UnifiedOrder(data);
if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
{
throw new Exception("UnifiedOrder response error!");
} _unifiedOrderResult = result;
return result;
} /**
*
* 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数,
* 微信浏览器调起JSAPI时的输入参数格式如下:
* {
* "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入
* "timeStamp":" 1395712654", //时间戳,自1970年以来的秒数
* "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串
* "package" : "prepay_id=u802345jgfjsdfgsdg888",
* "signType" : "MD5", //微信签名方式:
* "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
* }
* @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用
* 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
*
*/
public string GetJsApiParameters()
{
WxPayData jsApiParam = new WxPayData();
jsApiParam.SetValue("appId", _unifiedOrderResult.GetValue("appid"));
jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
jsApiParam.SetValue("package", "prepay_id=" + _unifiedOrderResult.GetValue("prepay_id"));
jsApiParam.SetValue("signType", "MD5");
jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string parameters = jsApiParam.ToJson();
return parameters;
}
}
/// <summary>
/// 微信H5支付
/// </summary>
internal class MwebPay
{
public async Task<WxPayData> GetPayUrl(string body, string outTradeNo, int totalFee, string ip)
{
var data = new WxPayData();
data.SetValue("body", body);//商品描述
//data.SetValue("attach", outTradeIds);//附加数据
data.SetValue("out_trade_no", outTradeNo);//随机字符串
data.SetValue("total_fee", totalFee);//总金额
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
data.SetValue("time_expire", DateTime.Now.AddMinutes().ToString("yyyyMMddHHmmss"));//交易结束时间
//data.SetValue("goods_tag", "jjj");//商品标记
data.SetValue("trade_type", "MWEB");//交易类型
data.SetValue("spbill_create_ip", ip);//终端ip var result = await WxPayApi.UnifiedOrder(data);//调用统一下单接口
return result;
} public string GetJsApiParameters(WxPayData unifiedOrderResult)
{
WxPayData jsApiParam = new WxPayData();
jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
jsApiParam.SetValue("signType", "MD5");
jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string parameters = jsApiParam.ToJson();
return parameters;
}
}
/// <summary>
/// 微信扫码支付
/// </summary>
internal class NativePay
{
/**
* 生成扫描支付模式一URL
* @param productId 商品ID
* @return 模式一URL
*/
public string GetPrePayUrl(string productId)
{
//Log.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");
WxPayData data = new WxPayData();
data.SetValue("appid", WxPayConfig.APPID);//公众帐号id
data.SetValue("mch_id", WxPayConfig.MCHID);//商户号
data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
data.SetValue("product_id", productId);//商品ID
data.SetValue("sign", data.MakeSign());//签名
var str = ToUrlParams(data.GetValues());//转换为URL串
var url = "weixin://wxpay/bizpayurl?" + str;
//Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
return url;
} /**
* 生成直接支付url,支付url有效期为2小时,模式二
* @param productId 商品ID
* @return 模式二URL
*/
public async Task<string> GetPayUrl(string body, string outTradeNo, int totalFee, string productId)
{
//Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing..."); var data = new WxPayData();
data.SetValue("body", body);//商品描述
//data.SetValue("attach", outTradeIds);//附加数据
data.SetValue("out_trade_no", outTradeNo);//随机字符串
data.SetValue("total_fee", totalFee);//总金额
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
data.SetValue("time_expire", DateTime.Now.AddMinutes().ToString("yyyyMMddHHmmss"));//交易结束时间
//data.SetValue("goods_tag", "jjj");//商品标记
data.SetValue("trade_type", "NATIVE");//交易类型
data.SetValue("product_id", productId);//商品ID var result = await WxPayApi.UnifiedOrder(data);//调用统一下单接口
string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接 //Log.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
return url;
} /**
* 参数数组转换为url格式
* @param map 参数名与参数值的映射表
* @return URL字符串
*/
private string ToUrlParams(SortedDictionary<string, object> map)
{
string buff = "";
foreach (KeyValuePair<string, object> pair in map)
{
buff += pair.Key + "=" + pair.Value + "&";
}
buff = buff.Trim('&');
return buff;
}
}
4:定义接口
public interface IWxPayService
{
/// <summary>
/// 微信扫码支付,用户发送数据到服务器,返回支付二维码字段
/// </summary>
/// <returns></returns>
Task<Tuple<bool, string>> PagePay(string body, string outTradeNo, int totalFee, string productId);
/// <summary>
/// 微信app支付,移动端发送数据,服务器统一下单,返回数据用于app支付
/// </summary>
/// <returns></returns>
Task<Tuple<bool, string>> AppPay(string body, string outTradeNo, int totalFee);
/// <summary>
/// 微信公众号支付,服务器返回H5调起参数
/// </summary>
/// <returns></returns>
Task<Tuple<bool, string>> JsApiPay(string body, string outTradeNo, int totalFee, string openId);
/// <summary>
/// 微信H5支付
/// </summary>
/// <returns></returns>
Task<Tuple<bool, string>> MwebPay(string body, string outTradeNo, int totalFee, string ip);
/// <summary>
/// 微信申请退款
/// </summary>
/// <returns></returns>
Task<WeChatRefundResponse> WeChatRefund(string transactionId, string outTradeNo, int totalFee, int refundFee, string outRefundNo);
/// <summary>
/// 微信退款查询,用于确认退款是否成功
/// </summary>
/// <returns></returns>
Task<WeChatRefundQueryResponse> WeChatRefundQuery(string refundId, string outRefundNo, string transactionId, string outTradeNo);
/// <summary>
/// 微信回调
/// </summary>
/// <returns></returns>
Task<WeChatNotifyRequest> WeChatNotify(Stream weChatReturnData);
}
5:实现接口方法
public class WxPayService : IWxPayService
{
public async Task<Tuple<bool, string>> PagePay(string body, string outTradeNo, int totalFee, string productId)
{
try
{
var nativePay = new NativePay();
//生成扫码支付模式二url
var url2 = await nativePay.GetPayUrl(body, outTradeNo, totalFee, productId);
//将url生成二维码图片
var writerSvg = new BarcodeWriterSvg
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
ErrorCorrection = ErrorCorrectionLevel.H
}
};
var svgImageData = writerSvg.Write(url2);
return svgImageData == null
? new Tuple<bool, string>(false, "返回数据为空!")
: new Tuple<bool, string>(true, svgImageData.ToString());
}
catch (Exception e)
{
return new Tuple<bool, string>(false, e.Message);
}
} public async Task<Tuple<bool, string>> AppPay(string body, string outTradeNo, int totalFee)
{
try
{
var appId = "XX";
var mchId = "XX";
var key = "XX";
WxPayConfig.Config(appId,mchId,key);
var appPay = new AppPay();
var result = await appPay.Run(body, outTradeNo, totalFee);
return result == null
? new Tuple<bool, string>(false, "返回数据为空!")
: new Tuple<bool, string>(true, AppSign(result.ToJson()));
}
catch (Exception e)
{
return new Tuple<bool, string>(false, e.Message);
}
}
public string AppSign(string preJson)
{
var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(preJson);
var data = new WxPayData();
data.SetValue("appid", dic["appid"]);
data.SetValue("partnerid", dic["mch_id"]);
data.SetValue("prepayid", dic["prepay_id"]);
data.SetValue("package", "Sign=WXPay");
data.SetValue("noncestr", WxPayApi.GenerateNonceStr());
data.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
data.SetValue("sign", data.MakeSign());
return data.ToJson();
}
public async Task<Tuple<bool, string>> JsApiPay(string body, string outTradeNo, int totalFee, string openId)
{
try
{
var jsApiPay = new JsApiPay();
await jsApiPay.GetUnifiedOrderResult(body, outTradeNo, totalFee, openId);
var wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数
return wxJsApiParam == null
? new Tuple<bool, string>(false, "返回数据为空!")
: new Tuple<bool, string>(true, wxJsApiParam);
}
catch (Exception e)
{
return new Tuple<bool, string>(false, e.Message);
}
} public async Task<Tuple<bool, string>> MwebPay(string body, string outTradeNo, int totalFee, string ip)
{
try
{
var mwebPay = new MwebPay();
var data = await mwebPay.GetPayUrl(body, outTradeNo, totalFee, ip);
return data == null
? new Tuple<bool, string>(false, "返回数据为空!")
: new Tuple<bool, string>(true, data.GetValue("mweb_url").ToString());
}
catch (Exception e)
{
return new Tuple<bool, string>(false, e.Message);
}
} public async Task<WeChatRefundResponse> WeChatRefund(string transactionId, string outTradeNo, int totalFee, int refundFee, string outRefundNo)
{
try
{
var result = await WxRefund.Run(transactionId, outTradeNo, totalFee, refundFee, outRefundNo);
var response = JsonConvert.DeserializeObject<WeChatRefundResponse>(result);
return response;
}
catch (Exception e)
{
return new WeChatRefundResponse { result_code = "Fail", return_msg = e.Message };
}
} public async Task<WeChatRefundQueryResponse> WeChatRefundQuery(string refundId, string outRefundNo, string transactionId, string outTradeNo)
{
try
{
var result = await WxRefundQuery.Run(refundId, outRefundNo, transactionId, outTradeNo);
var response = JsonConvert.DeserializeObject<WeChatRefundQueryResponse>(result);
return response;
}
catch (Exception e)
{
return new WeChatRefundQueryResponse { result_code = "Fail", return_msg = e.Message };
}
} public async Task<WeChatNotifyRequest> WeChatNotify(Stream weChatReturnData)
{
//接收从微信后台POST过来的数据
var s = weChatReturnData;
int count;
var buffer = new byte[];
var builder = new StringBuilder();
while ((count = s.Read(buffer, , )) > )
{
builder.Append(Encoding.UTF8.GetString(buffer, , count));
}
s.Flush();
s.Dispose();
var notifyData = new WxPayData();
try
{
notifyData.FromXml(builder.ToString());
}
catch (Exception e)
{
var res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", e.Message);
return new WeChatNotifyRequest { IsVerify = false, PayNo = "", TradeIds = "", PayTime = "", Sign = "", Content = res.ToXml() };
} //检查支付结果中transaction_id是否存在
if (!notifyData.IsSet("transaction_id"))
{
//若transaction_id不存在,则立即返回结果给微信支付后台
var res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "支付结果中微信订单号不存在");
return new WeChatNotifyRequest { IsVerify = false, PayNo = "", TradeIds = "", PayTime = "", Sign = "", Content = res.ToXml() };
} var transactionId = notifyData.GetValue("transaction_id").ToString();
var tradeIds = notifyData.GetValue("out_trade_no").ToString();
var payTime = notifyData.GetValue("time_end").ToString(); //查询订单,判断订单真实性
if (!await QueryOrder(transactionId))
{
//若订单查询失败,则立即返回结果给微信支付后台
var res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "订单查询失败");
return new WeChatNotifyRequest { IsVerify = false, PayNo = "", TradeIds = "", PayTime = "", Sign = "", Content = res.ToXml() };
}
//查询订单成功
else
{
var res = new WxPayData();
res.SetValue("return_code", "SUCCESS");
res.SetValue("return_msg", "OK");
return new WeChatNotifyRequest { IsVerify = true, PayNo = transactionId, TradeIds = tradeIds, PayTime = payTime, Sign = "", Content = res.ToXml() };
}
}
//查询订单
private static async Task<bool> QueryOrder(string transactionId)
{
var req = new WxPayData();
req.SetValue("transaction_id", transactionId);
var res = await WxPayApi.OrderQuery(req);
return res.GetValue("return_code").ToString() == "SUCCESS" && res.GetValue("result_code").ToString() == "SUCCESS";
}
}
6:其他一些网络请求类,相关配置类
internal class HttpService
{
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
//直接确认,否则打不开
return true;
} public static async Task<string> Post(string xml, string url, bool isUseCert, int timeout)
{
if (isUseCert)
{
//商户私钥证书,用于对请求报文进行签名
var tempSignCert = new X509Certificate2(WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD); var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
SslProtocols = SslProtocols.Tls12
};
handler.ClientCertificates.Add(tempSignCert);
handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; using (var client = new HttpClient(handler))
{
var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
else
{
using (var client = new HttpClient())
{
var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
}
}
/**
* 配置账号信息
*/
internal class WxPayConfig
{
//=======【基本信息设置】=====================================
/* 微信公众号信息配置
* APPID:绑定支付的APPID(必须配置)
* MCHID:商户号(必须配置)
* KEY:商户支付密钥,参考开户邮件设置(必须配置)
* APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置)
*/ public static void Config(string appId, string mchid, string key)
{
APPID = appId;
MCHID = mchid;
KEY = key;
SSLCERT_PASSWORD = mchid;
} public static string APPID { get;private set; } = "XXX";
public static string MCHID { get; private set; } = "XXX";
public static string KEY { get; private set; } = "XXX"; public const string APPSECRET = "XXX"; //=======【证书路径设置】=====================================
/* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要)
*/
public const string SSLCERT_PATH = "path";
public static string SSLCERT_PASSWORD { get; set; } = "XXX"; //=======【支付结果通知url】=====================================
/* 支付结果通知回调url,用于商户接收支付结果
*/
public const string NOTIFY_URL = "http://paysdk.weixin.qq.com/example/ResultNotifyPage.aspx"; //=======【商户系统后台机器IP】=====================================
/* 此参数可手动配置也可在程序中自动获取
*/
public const string IP = "8.8.8.8"; //=======【代理服务器设置】===================================
/* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置)
*/
public const string PROXY_URL = "http://10.152.18.220:8080"; //=======【上报信息配置】===================================
/* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报
*/
public const int REPORT_LEVENL = ; //=======【日志级别】===================================
/* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
*/
public const int LOG_LEVENL = ;
}
值得注意的地方
a.微信退款及撤销支付是需要证书的,.net core 调用证书请求可以参考:http://www.cnblogs.com/AsprosL/p/7234141.html,也可以查看具体代码
b.微信配置类需要设置灵活配置,app支付需要开发平台申请,其他支付方式需要微信公众号开通,所以会有多个appid及mchid
----------------------------分割线------------------------------
以上基本就是微信支付的内容了,支付回调,退款及退款查询预留到下一章节吧