Keep getting 21002 'java.lang.NullPointerExcep

2019-05-21 11:44发布

问题:

I keep getting 21002 'java.lang.NullPointerException' errors from Apple when I try to test my In-App Purchases in the sandbox. This is what I have done:

  • Set up the In-App Purchase products in iTunes Connect. I can successfully retrieve them via StoreKit.
  • Set up test user in iTunes Connect.
  • Application starts up, downloads the available In-App Purchase products, I trigger the In-App Purchase and Apple responds with the transactionReceipt, which I base64-encode on the iPhone and send to my C#/ASP.NET server.
  • The server puts the received string into JSON (I tried it both with NewtonSoft.Json and manually) and sends the JSON to Apple:

var json = "{ 'receipt-data': '" + receipt + "'}";

OR:

var json = new JObject(new JProperty("receipt-data", receipt)).ToString();

and then:

var webRequest = System.Net.HttpWebRequest.Create("https://sandbox.itunes.apple.com/verifyReceipt");
webRequest.ContentType = "text/plain";
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(receipt);
webRequest.ContentLength = byteArray.Length;
using (var stream = webRequest.GetRequestStream())
{
    stream.Write(byteArray, 0, byteArray.Length);
    stream.Flush();
}

var resp = webRequest.GetResponse();
if (resp != null)
{
    using (var sr = new System.IO.StreamReader(resp.GetResponseStream()))
    {
        var result = sr.ReadToEnd().Trim();
        var iapResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<AppleIapResponse>(result);
        // always getting '21002' 'java.lang.NullPointerException'
    }
}

I tried everything: changing the ContentType, the JSON formatting, the encoding....

Any hints?

回答1:

It's a simple bug in the code, I was writing the receipt into the POST, not the JSON:

byte[] byteArray = Encoding.UTF8.GetBytes(json);
                                          ^^^^

The wall hurts from banging my head against it..