C#微信支付(五)—— 申請退款
阿新 • • 發佈:2018-12-09
退款也比較簡單,需要注意的是退款是需要證書的,需要去 微信商戶平臺(pay.weixin.qq.com)–>賬戶中心–>賬戶設定–>API安全–>證書下載, 把證書下載好後代入請求中。相關連結:申請退款
這是WxPayApi.cs的一個方法,其他的方法可以去基礎幫助類裡面看
/**
*
* 申請退款
* @param WxPayData inputObj 提交給申請退款API的引數
* @param int timeOut 超時時間
* @throws WxPayException
* @return 成功時返回介面呼叫結果,其他拋異常
*/
public static WxPayData Refund(WxPayData inputObj, int timeOut = 6)
{
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", Config.AppID);//公眾賬號ID
inputObj.SetValue("mch_id", Config.MchID);//商戶號
inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//隨機字串
//非同步通知url未設定,則使用配置檔案中的url
if (!inputObj.IsSet("notify_url"))
{
inputObj.SetValue("notify_url", Config.NotifyUrl);//非同步通知url
}
inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//簽名型別
inputObj.SetValue("sign", inputObj.MakeSign());//簽名
string xml = inputObj.ToXml();
var start = DateTime.Now;
//Log.Debug("WxPayApi", "Refund request : " + xml);
string response = HttpService.Post(xml, url, true, timeOut);//呼叫HTTP通訊介面提交資料到API
//Log.Debug("WxPayApi", "Refund response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//獲得介面耗時
//將xml格式的結果轉換為物件以返回
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//測速上報
return result;
}
op_user_id 這個是微信支付那配置的子人員的標號,沒有就隨便填就行,主要是用於多個系統的時候只有一個支付號的情況,其他情況沒想到
/// <summary>
/// 申請退款完整業務流程邏輯
/// </summary>
public Hashtable Refund()
{
string transaction_id = GetStr("transaction_id");
string out_trade_no = GetStr("out_trade_no");
//訂單總金額,單位分
int total_fee = GetInt("total_fee");
//退款金額,單位分
int refund_fee = GetInt("refund_fee");
//商戶退款單號
string out_refund_no = GetStr("out_refund_no");
if (string.IsNullOrEmpty(transaction_id) && string.IsNullOrEmpty(out_trade_no))
{
throw new Exception("微信訂單號和商戶訂單號至少填寫一個,微信訂單號優先!");
}
WxPayData data = new WxPayData();
if (!string.IsNullOrEmpty(transaction_id))//微信訂單號存在的條件下,則已微信訂單號為準
{
data.SetValue("transaction_id", transaction_id);
}
else//微信訂單號不存在,才根據商戶訂單號去退款
{
data.SetValue("out_trade_no", out_trade_no);
}
data.SetValue("total_fee", total_fee);
data.SetValue("refund_fee", refund_fee);
data.SetValue("out_refund_no", out_refund_no);
data.SetValue("op_user_id", Config.MchID);//操作員,預設為商戶號
WxPayData result = WxPayApi.Refund(data);//提交退款申請給API,接收返回資料
return result.ToHashtable();
}
沒什麼坑,就記得帶上證書就好。