1. 程式人生 > >C#POST 支付寶/微信回撥介面

C#POST 支付寶/微信回撥介面

一般支付寶/微信的回撥介面都會返回xml格式,下面是呼叫類似這種介面的辦法:


public async Task<string> GetData()
{
            string requestUrl = "http://localhost:xxx/xx/xxxx/xxx/xxxx";//請求的介面URL
            string contentType = "application/x-www-form-urlencoded";//請求文字型別
            string result = string.Empty;//返回結果,xml格式的字串
            using (var client = new HttpClient())
            {
                object data = null;
                string str = JsonHelper.Instance.Serialize(data);//一般這種介面的請求引數都是空的,也就是不需要請求引數
                var content = new StringContent(str)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue(contentType) }
                };
                HttpResponseMessage resp = await client.PostAsync(requestUrl, content);
                resp.EnsureSuccessStatusCode();//返回http響應狀態碼

                result = resp.Content.ReadAsStringAsync().Result;//<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>

                return result;
            }
}

下面介紹基本介面POST的辦法,文字格式一般是JSON格式去請求:

public async Task<Result> GetData()
{
            string requestUrl = "http://xxxxxxxx/xxxx/xxx/xxx/xxx";//請求的介面URL
            string signData = "lrfVUpo8uCHvhPXEd6PsUH82XEkc+kUyQYDssRlop1AcbY5WXH0kWAWhAioQCwl5N+lZGDijqH67aaBcICa7LJOAN1r7z0H8ghNKOROW2ugGX6x7dZKeZA0GmfJsuNK30eONDu6GdTTnZGgEJsPepxh/AIFJZYdN6RVseIDJAwQ=";
            string data = "eyJJc1N1Y2Nlc3MiOnRydWUsIkNvZGUiOiIwMDUyMDE4MTAyNDI1NDkyODIiLCJEZXNjcmlwdGlvbiI6IuaTjeS9nOaIkOWKnyJ9";
            object obj = new { SignData = signData, Data = data };//使用匿名類構造object
            string result = string.Empty;
            using (var client = new HttpClient())
            {
                string str = JsonHelper.Instance.Serialize(obj);
                var content = new StringContent(str)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("Application/json") }
                };
                HttpResponseMessage resp = await client.PostAsync(requestUrl, content);

                if (resp.IsSuccessStatusCode)
                {
                    result = resp.Content.ReadAsStringAsync().Result;
                }

                return JsonHelper.Instance.Deserialize<Result>(result);//這裡返回的是字串,JSON格式資料
            }            
}

後續可以序列化字串為物件