PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/Common/AliPay.cs

http://comic-yuuzle.googlecode.com/
C# | 341 lines | 216 code | 28 blank | 97 comment | 26 complexity | df0ff8bb8fe86a01e25288fa60547c66 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Net;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Xml;
  9. namespace YuuzleComic.Common {
  10. /// <summary>
  11. /// ??????
  12. /// </summary>
  13. public class AliPay {
  14. public Dictionary<string, string> Config { set; get; }
  15. private Dictionary<string, string> sPara = new Dictionary<string, string>();
  16. public string PayGetWay { set; get; }
  17. public string NotifyGetWay { set; get; }
  18. public string LogFilePath { get; set; }
  19. public AliPay()
  20. : this("") {
  21. }
  22. public AliPay(string hosturl) {
  23. #region ??????
  24. Config = new Dictionary<string, string>();
  25. Config["partner"] = "2088302492797137";
  26. Config["key"] = "ub1y7vomann13oy3rfpir7wfrplwrp6y";
  27. Config["seller_email"] = "admin@foosun.net";
  28. Config["return_url"] = hosturl + "/user/info/AlipayNotify.aspx";
  29. Config["notify_url"] = hosturl + "/user/info/AlipayNotify.aspx";
  30. Config["show_url"] = hosturl + "/user/info/history.aspx?type=2";
  31. Config["mainname"] = "????????????";
  32. #endregion
  33. #region ??????
  34. Config["_input_charset"] = "utf-8";
  35. Config["sign_type"] = "MD5";
  36. //??????????????
  37. Config["transport"] = "https";
  38. #endregion
  39. #region ????
  40. PayGetWay = "https://www.alipay.com/cooperate/gateway.do";
  41. NotifyGetWay = "http://notify.alipay.com/trade/notify_query.do";
  42. #endregion
  43. }
  44. #region ????
  45. public bool Notify(SortedDictionary<string, string> request) {
  46. if (Config["transport"] == "https") {
  47. NotifyGetWay = PayGetWay;
  48. }
  49. sPara = Para_filter(request);
  50. string preSignStr = DicToQueryString(sPara);
  51. string mysign = Build_mysign(sPara, Config["key"], Config["sign_type"], Config["_input_charset"]);
  52. string responseTxt = Verify(sPara["notify_id"]);
  53. string sWord = "responseTxt=" + responseTxt + "\n notify_url_log:sign=" + request["sign"] + "&mysign=" + mysign + "\n notify??????" + preSignStr;
  54. if (request["sign"] == mysign && responseTxt == "true") {
  55. return true;
  56. }
  57. else {
  58. log_result(LogFilePath, sWord);
  59. return false;
  60. }
  61. }
  62. /// <summary>
  63. /// ????????????????
  64. /// </summary>
  65. /// <returns>????</returns>
  66. private string Verify(string notify_id) {
  67. UriBuilder veryfy = new UriBuilder(NotifyGetWay);
  68. string query = "";
  69. if (Config["transport"] == "https") {
  70. query = "service=notify_verify&";
  71. }
  72. veryfy.Query = query + "partner=" + Config["partner"] + "&notify_id=" + notify_id;
  73. return Get_Http(veryfy.Uri.ToString(), 120000);
  74. }
  75. /// <summary>
  76. /// ???????ATN??
  77. /// </summary>
  78. /// <param name="strUrl">??URL????</param>
  79. /// <param name="timeout">??????</param>
  80. /// <returns>???ATN??</returns>
  81. private string Get_Http(string strUrl, int timeout) {
  82. string strResult;
  83. try {
  84. HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
  85. myReq.Timeout = timeout;
  86. HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
  87. Stream myStream = HttpWResp.GetResponseStream();
  88. StreamReader sr = new StreamReader(myStream, Encoding.Default);
  89. StringBuilder strBuilder = new StringBuilder();
  90. while (-1 != sr.Peek()) {
  91. strBuilder.Append(sr.ReadLine());
  92. }
  93. strResult = strBuilder.ToString();
  94. }
  95. catch (Exception exp) {
  96. strResult = "???" + exp.Message;
  97. }
  98. return strResult;
  99. }
  100. #endregion
  101. #region ????
  102. /// <summary>
  103. /// ??????HTML
  104. /// </summary>
  105. /// <param name="sendType">???????GET?POST?????</param>
  106. /// <returns>?? ????HTML??</returns>
  107. public string Build_Form(string sendType) {
  108. StringBuilder sbHtml = new StringBuilder();
  109. sendType = sendType.ToLower();
  110. if (sendType != "post") {
  111. sendType = "get";
  112. }
  113. sbHtml.Append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + PayGetWay + "_input_charset=" + Config["_input_charset"] + "\" method=\"" + sendType.ToLower() + "\">");
  114. foreach (KeyValuePair<string, string> temp in sPara) {
  115. sbHtml.Append("<input type=\"hidden\" name=\"" + temp.Key + "\" value=\"" + temp.Value + "\"/>");
  116. }
  117. sbHtml.Append("<input type=\"hidden\" name=\"sign\" value=\"" + sPara["sign"] + "\"/>");
  118. sbHtml.Append("<input type=\"hidden\" name=\"sign_type\" value=\"" + sPara["sign_type"] + "\"/>");
  119. //submit?????????name??
  120. sbHtml.Append("<input type=\"submit\" value=\"???????\"></form>");
  121. sbHtml.Append("<script>document.forms['alipaysubmit'].submit();</script>");
  122. return sbHtml.ToString();
  123. }
  124. /// <summary>
  125. /// ?????????URL?????
  126. /// </summary>
  127. /// <returns>?????URL????????</returns>
  128. public string Build_GetUrl() {
  129. UriBuilder urlBuilder = new UriBuilder(PayGetWay);
  130. urlBuilder.Query = DicToQueryString(sPara);
  131. return urlBuilder.Uri.ToString();
  132. }
  133. /// <summary>
  134. /// ??????????
  135. /// </summary>
  136. /// <param name="out_trade_no">???</param>
  137. /// <param name="subject">??</param>
  138. /// <param name="body">??</param>
  139. /// <param name="total_fee">??</param>
  140. public void CreateDirectPayByUser(string out_trade_no, string subject, string body, string total_fee) {
  141. var para = GetConfig();
  142. para.Add("service", "create_direct_pay_by_user");
  143. para.Add("payment_type", "1");
  144. para.Add("out_trade_no", out_trade_no);
  145. para.Add("subject", subject);
  146. para.Add("body", body);
  147. para.Add("total_fee", total_fee);
  148. //param.Add("paymethod", paymethod);
  149. //param.Add("defaultbank", defaultbank);
  150. //param.Add("anti_phishing_key", anti_phishing_key);
  151. //param.Add("exter_invoke_ip", exter_invoke_ip);
  152. //param.Add("extra_common_param", extra_common_param);
  153. //param.Add("buyer_email", buyer_email);
  154. //param.Add("royalty_type", royalty_type);
  155. //param.Add("royalty_parameters", royalty_parameters);
  156. sPara = Para_filter(para);
  157. sPara.Add("sign", Build_mysign(sPara, para["key"], para["sign_type"], para["_input_charset"]));
  158. sPara.Add("sign_type", Config["sign_type"]);
  159. }
  160. /// <summary>
  161. /// ??????????
  162. /// </summary>
  163. /// <param name="out_trade_no">???</param>
  164. /// <param name="subject">??</param>
  165. /// <param name="body">??</param>
  166. /// <param name="price">??</param>
  167. public void CreatePartnerTradeByBuyer(string out_trade_no, string subject, string body, string price) {
  168. var para = GetConfig();
  169. para.Add("service", "create_partner_trade_by_buyer");
  170. para.Add("payment_type", "1");
  171. para.Add("out_trade_no", out_trade_no);
  172. para.Add("subject", subject);
  173. para.Add("body", body);
  174. para.Add("price", price);
  175. sPara = Para_filter(para);
  176. sPara.Add("sign", Build_mysign(sPara, para["key"], para["sign_type"], para["_input_charset"]));
  177. sPara.Add("sign_type", Config["sign_type"]);
  178. }
  179. /// <summary>
  180. /// ?????????
  181. /// </summary>
  182. /// <param name="out_trade_no">???</param>
  183. /// <param name="subject">??</param>
  184. /// <param name="body">??</param>
  185. /// <param name="price">??</param>
  186. public void TradeCreateByBuyer(string out_trade_no, string subject, string body, string price) {
  187. var para = GetConfig();
  188. para.Add("service", "trade_create_by_buyer");
  189. para.Add("payment_type", "1");
  190. para.Add("out_trade_no", out_trade_no);
  191. para.Add("subject", subject);
  192. para.Add("body", body);
  193. para.Add("price", price);
  194. sPara = Para_filter(para);
  195. sPara.Add("sign", Build_mysign(sPara, para["key"], para["sign_type"], para["_input_charset"]));
  196. sPara.Add("sign_type", Config["sign_type"]);
  197. }
  198. #endregion
  199. #region ????
  200. /// <summary>
  201. /// ?????????
  202. /// </summary>
  203. /// <param name="request">??</param>
  204. /// <returns>??????</returns>
  205. public SortedDictionary<string, string> RequestToDic(NameValueCollection request) {
  206. SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
  207. String[] requestItem = request.AllKeys;
  208. for (int i = 0; i < requestItem.Length; i++) {
  209. sArray.Add(requestItem[i], request[requestItem[i]]);
  210. }
  211. return sArray;
  212. }
  213. /// <summary>
  214. /// ?????????
  215. /// </summary>
  216. /// <returns>????????</returns>
  217. public SortedDictionary<string, string> GetConfig() {
  218. SortedDictionary<string, string> param = new SortedDictionary<string, string>();
  219. foreach (var item in Config) {
  220. param.Add(item.Key, item.Value);
  221. }
  222. return param;
  223. }
  224. /// <summary>
  225. /// ??????????“??=???”????“&”????????
  226. /// </summary>
  227. /// <param name="dicArray">???????</param>
  228. /// <returns>??????????</returns>
  229. public string DicToQueryString(Dictionary<string, string> dicArray) {
  230. StringBuilder queryBuilder = new StringBuilder();
  231. foreach (KeyValuePair<string, string> temp in dicArray) {
  232. queryBuilder.Append(temp.Key + "=" + temp.Value + "&");
  233. }
  234. string queryString = queryBuilder.ToString();
  235. return queryString.Substring(0, queryString.Length - 1);
  236. }
  237. /// <summary>
  238. /// ?????????????
  239. /// </summary>
  240. /// <param name="dicArrayPre">???????</param>
  241. /// <returns>???????</returns>
  242. public Dictionary<string, string> Para_filter(SortedDictionary<string, string> dicArrayPre) {
  243. Dictionary<string, string> dicArray = new Dictionary<string, string>();
  244. foreach (KeyValuePair<string, string> temp in dicArrayPre) {
  245. if (temp.Key.ToLower() != "sign"
  246. && temp.Key.ToLower() != "key"
  247. && temp.Key.ToLower() != "sign_type"
  248. && temp.Key.ToLower() != "transport"
  249. && !string.IsNullOrEmpty(temp.Value)) {
  250. dicArray.Add(temp.Key.ToLower(), temp.Value);
  251. }
  252. }
  253. return dicArray;
  254. }
  255. /// <summary>
  256. /// ??????
  257. /// </summary>
  258. /// <param name="sArray">??????</param>
  259. /// <param name="key">?????</param>
  260. /// <param name="sign_type">????</param>
  261. /// <param name="_input_charset">????</param>
  262. /// <returns>???????</returns>
  263. public string Build_mysign(Dictionary<string, string> dicArray, string key, string sign_type, string _input_charset) {
  264. string prestr = DicToQueryString(dicArray); //??????????“??=???”????“&”????????
  265. prestr = prestr + key; //?????????????????????
  266. string mysign = Sign(prestr, sign_type, _input_charset); //????????????????
  267. return mysign;
  268. }
  269. /// <summary>
  270. /// ?????
  271. /// </summary>
  272. /// <param name="prestr">????????</param>
  273. /// <param name="sign_type">????</param>
  274. /// <param name="_input_charset">????</param>
  275. /// <returns>????</returns>
  276. public static string Sign(string prestr, string sign_type, string _input_charset) {
  277. StringBuilder sb = new StringBuilder(32);
  278. if (sign_type.ToUpper() == "MD5") {
  279. MD5 md5 = new MD5CryptoServiceProvider();
  280. byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr));
  281. for (int i = 0; i < t.Length; i++) {
  282. sb.Append(t[i].ToString("x").PadLeft(2, '0'));
  283. }
  284. }
  285. return sb.ToString();
  286. }
  287. /// <summary>
  288. /// ?????????????????????????????
  289. /// </summary>
  290. /// <param name="sPath">?????????</param>
  291. /// <param name="sWord">???????????</param>
  292. public void log_result(string sPath, string sWord) {
  293. StreamWriter fs = new StreamWriter(sPath, false, System.Text.Encoding.Default);
  294. fs.Write(sWord);
  295. fs.Close();
  296. }
  297. /// <summary>
  298. /// ??????????query_timestamp???????????
  299. /// ???????XML????IIS???????
  300. /// </summary>
  301. /// <returns>??????</returns>
  302. public string Query_timestamp() {
  303. string url = "https://mapi.alipay.com/gateway.do?service=query_timestamp&partner=" + Config["partner"];
  304. string encrypt_key = "";
  305. XmlTextReader Reader = new XmlTextReader(url);
  306. XmlDocument xmlDoc = new XmlDocument();
  307. xmlDoc.Load(Reader);
  308. encrypt_key = xmlDoc.SelectSingleNode("/alipay/response/timestamp/encrypt_key").InnerText;
  309. return encrypt_key;
  310. }
  311. #endregion
  312. }
  313. }