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,最后是发起微信支付了,待续。