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字符串:
wx2421b1c4370ec43b 支付测试 JSAPI支付测试10000100 1add1a30ac87aa2db72f57a2375d8fec http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php oUpF8uMuAJO_M2pxb1Q9zNjWeS6o 1415659990 14.23.150.211 1 JSAPI 0CB01533B8C1EF103065174F50BCA001
返回来的requestData也是一段xml字符串:
调用此接口是为了获取prepay_id,接口返回来的结果包含了prepay_id,接下来把它取出,先要一个把xml字符串转换为SortedDictionary类型的函数:
////// 把XML数据转换为SortedDictionary /// ///集合 /// public SortedDictionary GetInfoFromXml(string xmlstring) { SortedDictionary sParams = new SortedDictionary (); 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; }
然后调用方法:
SortedDictionaryrequestXML = wxPayBaseHelper.GetInfoFromXml(requestData); foreach (KeyValuePair k in requestXML) { if (k.Key == "prepay_id") { prepay_id = k.Value; break; } }
ok,又获取到了prepay_id,最后是发起微信支付了,待续。