標籤:
1.首先調用介面,要有一個post資料到指定url並返回資料的函數:
protected string PostXmlToUrl(string url, string postData) { string returnmsg = ""; using (System.Net.WebClient wc = new System.Net.WebClient()) { returnmsg = wc.UploadString(url, "POST", postData); } return returnmsg; }
post的資料格式可以是
url的參數格式(a=1&b=2&c=3....)
xml格式(<xml>....</xml>)
返回的資料格式由介面確定。
2.方法調用:
post_data = wxPayBaseHelper.UnifiedPayOrder(wxobPay, key); requestData = PostXmlToUrl("https://api.mch.weixin.qq.com/pay/unifiedorder", post_data);
這裡post_data是一段xml字串:
<xml> <appid>wx2421b1c4370ec43b</appid> <attach>支付測試</attach> <body>JSAPI支付測試</body> <mch_id>10000100</mch_id> <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str> <notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php</notify_url> <openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid> <out_trade_no>1415659990</out_trade_no> <spbill_create_ip>14.23.150.211</spbill_create_ip> <total_fee>1</total_fee> <trade_type>JSAPI</trade_type> <sign>0CB01533B8C1EF103065174F50BCA001</sign></xml>
返回來的requestData也是一段xml字串:
<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> <appid><![CDATA[wx2421b1c4370ec43b]]></appid> <mch_id><![CDATA[10000100]]></mch_id> <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str> <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign> <result_code><![CDATA[SUCCESS]]></result_code> <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id> <trade_type><![CDATA[JSAPI]]></trade_type></xml>
調用此介面是為了擷取prepay_id,介面返回來的結果包含了prepay_id,接下來把它取出,先要一個把xml字串轉換為SortedDictionary類型的函數:
/// <summary> /// 把XML資料轉換為SortedDictionary<string, string>集合 /// </summary> /// <param name="strxml"></param> /// <returns></returns> public SortedDictionary<string, string> GetInfoFromXml(string xmlstring) { SortedDictionary<string, string> sParams = new SortedDictionary<string, string>(); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlstring); XmlElement root = doc.DocumentElement; int len = root.ChildNodes.Count; for (int i = 0; i < len; i++) { string name = root.ChildNodes[i].Name; if (!sParams.ContainsKey(name)) { sParams.Add(name.Trim(), root.ChildNodes[i].InnerText.Trim()); } } } catch (Exception ex) { //LxCommomHelper.Commom.TraceLog.LogWrite(ex.ToString(), LxCommomHelper.Commom.LogEnum.Pay); } return sParams; }
然後調用方法:
SortedDictionary<string, string> requestXML = wxPayBaseHelper.GetInfoFromXml(requestData); foreach (KeyValuePair<string, string> k in requestXML) { if (k.Key == "prepay_id") { prepay_id = k.Value; break; } }
ok,又擷取到了prepay_id,最後是發起支付了,待續。
c# 讀取XML資料