之前没有做过IOS 内购服务器验证这块,所以找了不少参考资料,网上大多php和java版本,然后自己搞了一个C#版本,希望能给大家一些参考,下面步入正题
在客户端向苹果购买成功之后,我们需要进行二次验证。
IOS在沙箱环境下购买成功之后,向苹果进行二次验证,确认用户是否购买成功。
当应用向Apple服务器请求购买,成功之后,Apple会返回以下四个数据给应用
public bool ValidateApplePay() {
//客户端post过来的参数 string appleReceipt = Request.Form["appleReceipt"]; //苹果内购的验证收据 string orderId = PayHelper.GetOrderIDByPrefix("AP"); //订单编号 string amount = Request.Form["amount"]; //金额 string userId = Request.Form["userId"]; //用户UserID
// 验证参数 if (appleReceipt.Length < 20) { return false; }
string strJosn = string.Format("{{\"receipt-data\":\"{0}\"}}", appleReceipt); // 请求验证 string strResult = CreatePostHttpResponse(strJosn, isSandbox); JObject obj = JObject.Parse(strResult);//using Newtonsoft.Json.Linq;
// 判断是否购买成功 if (obj["status"].ToString() == "0") { return true; } else { return false; } } public string CreatePostHttpResponse(string datas, bool isSandbox = false) { //正式购买地址 沙盒购买地址 string url_buy = "https://buy.itunes.apple.com/verifyReceipt"; string url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt"; string url = isSandbox ? url_sandbox : url_buy;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(datas.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); }
HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); //获取响应的字符串流 StreamReader sr = new StreamReader(responseStream); //创建一个stream读取流 var str = sr.ReadToEnd(); sr.Close(); responseStream.Close(); return str.ToString(); }
|
请发表评论