苹果内购支付对接

  1. public bool ValidateApplePay()  
  2.        {  
  3.                
  4.            //客户端post过来的参数  
  5.            string appleReceipt = Request.Form["appleReceipt"]; //苹果内购的验证收据  
  6.            string orderId = PayHelper.GetOrderIDByPrefix("AP");  //订单编号  
  7.            string amount = Request.Form["amount"];             //金额  
  8.            string userId = Request.Form["userId"];             //用户UserID  
  9.              
  10.            // 验证参数  
  11.            if (appleReceipt.Length < 20)  
  12.            {  
  13.                return false;  
  14.            }  
  15.   
  16.            string strJosn = string.Format("{{\"receipt-data\":\"{0}\"}}", appleReceipt);  
  17.            // 请求验证  
  18.            string strResult = CreatePostHttpResponse(strJosn, isSandbox);  
  19.            JObject obj = JObject.Parse(strResult);//using Newtonsoft.Json.Linq;  
  20.   
  21.            // 判断是否购买成功  
  22.            if (obj["status"].ToString() == "0")  
  23.            {  
  24.                return true;  
  25.            }  
  26.            else  
  27.            {  
  28.                return false;  
  29.            }  
  30.        }  
  31.    public string CreatePostHttpResponse(string datas, bool isSandbox = false)  
  32.        {  
  33.            //正式购买地址 沙盒购买地址  
  34.            string url_buy = "https://buy.itunes.apple.com/verifyReceipt";  
  35.            string url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";  
  36.            string url = isSandbox ? url_sandbox : url_buy;  
  37.   
  38.            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;  
  39.            request.ProtocolVersion = HttpVersion.Version10;  
  40.            request.Method = "POST";  
  41.            request.ContentType = "application/x-www-form-urlencoded";  
  42.            byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(datas.ToString());  
  43.            using (Stream stream = request.GetRequestStream())  
  44.            {  
  45.                stream.Write(data, 0, data.Length);  
  46.            }  
  47.   
  48.            HttpWebResponse response = request.GetResponse() as HttpWebResponse;  
  49.            Stream responseStream = response.GetResponseStream();   //获取响应的字符串流  
  50.            StreamReader sr = new StreamReader(responseStream); //创建一个stream读取流  
  51.            var str = sr.ReadToEnd();  
  52.            sr.Close();  
  53.            responseStream.Close();  
  54.            return str.ToString();  
  55.        }  
posted @ 2017-12-15 14:07  剑舞江南  阅读(793)  评论(0编辑  收藏  举报