Verify an App Store Transaction Receipt 【苹果服务端 验证一个应用程序商店交易收据有效性】

转自:http://blog.csdn.net/saindy5828/article/details/6414014

1、 从Transaction 的TransactionReceipt属性中得到接收的数据,并以base64编码;

2、创建JSON对象,字典格式,单键值对,键名为“receiptdata”,值为上一次编码的数据,效果:

{"receipt-data":"base64编码之后的数据"}

3、发送HTTP POST请求,将数据发送到App Store ,其地址为:https://buy.itunes.apple.com/verifyReceipt

4、App Store的返回值也是一个JSON格式对象,包括两个键值对:

{
"status" : 0,
"receipt" : { … }
}
说明:

如果status的值为0,就说明该receipt为有效的,否则就是无效的。

 1  
 2 
 3 public int verifyReceipt( byte[] receipt) {
 4        int status = -1;
 5 
 6         //This is the URL of the REST webservice in iTunes App Store
 7         URL url = new URL("https://buy.itunes.apple.com/verifyReceipt");
 8 
 9         //make connection, use post mode
10         HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
11         connection.setRequestMethod("POST");
12         connection.setDoOutput(true);
13         connection.setAllowUserInteraction(false);
14 
15         //Encode the binary receipt data into Base 64
16         //Here I'm using org.apache.commons.codec.binary.Base64 as an encoder, since commons-codec is already in Grails classpath
17         Base64 encoder = new Base64();
18         String encodedReceipt = new String(encoder.encode(receipt));
19 
20         //Create a JSON query object
21         //Here I'm using Grails' org.codehaus.groovy.grails.web.json.JSONObject
22         Map map = new HashMap();
23         map.put("receipt-data", encodedReceipt);
24         JSONObject jsonObject = new JSONObject(map);
25 
26         //Write the JSON query object to the connection output stream
27         PrintStream ps = new PrintStream(connection.getOutputStream());
28         ps.print(jsonObject.toString());
29         ps.close();
30 
31         //Call the service
32         BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
33         //Extract response
34         String str;
35         StringBuffer sb = new StringBuffer();
36         while ((str = br.readLine()) != null) {
37             sb.append(str);
38             sb.append("/n");
39         }
40         br.close();
41         String response = sb.toString();
42 
43         //Deserialize response
44         JSONObject result = new JSONObject(response);
45        status = result.getInt("status");
46         if (status == 0) {
47             //provide content
48         } else {
49             //signal error, throw an exception, do your stuff honey!
50         }
51 
52         return status ;
53 
54 
55     }

验证的方式也可以采用HTTP协议:HttpClient,下载httpcomponents-client,然后导入lib里的几个jar包。

这也是一种方式,不再进行多余的说明了。所谓条条道路通“苹果”。

posted @ 2015-09-01 10:08  艺言弈行  阅读(1060)  评论(0编辑  收藏  举报