通过Twisted服务器验证Apple商店收据

时间:2011-10-22 06:37:08

标签: iphone python https in-app-purchase twisted

我正在尝试使用来自我的Twisted服务器的Apple商店服务器验证来自inApp购买的交易收据。我已将(SKPaymentTransaction *)transaction.transactionReceipt从我的应用程序发送到我的服务器。

但是现在,将JSON对象发送到Apple服务器,我从Agent.request()延迟收到一个未处理的错误。我怀疑这是因为我没有在443端口收听来自Apple商店的响应,但我不希望我的应用程序也通过端口443与我的Twisted服务器通信。这是我的代码:

from twisted.application import internet, service
from twisted.internet import protocol, reactor
from zope.interface import implements
from twisted.web.iweb import IBodyProducer

from twisted.internet import defer
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
import json
import base64

class StringProducer(object):
    implements(IBodyProducer)

    def __init__(self, body):
        self.body = body
        self.length = len(body)

    def startProducing(self, consumer):
        consumer.write(self.body)
        return succeed(None)

    def pauseProducing(self):
        pass

    def stopProducing(self):
        pass

def printResponse(response):
    print response       # just testing to see what I have

def httpRequest(url, values, headers={}, method='POST'):
    agent = Agent(reactor)
    d = agent.request(method,
                      url,
                      Headers(headers),
                      StringProducer(values)
                      )
    d.addCallback(printResponse)

class storeServer(protocol.Protocol):

    def dataReceived(self, data):
        receiptBase64 = base64.standard_b64encode(data)
        jsonReceipt = json.dumps({'receipt-data':receiptBase64})
        print jsonReceipt     # verified that my data is correct

        d = httpRequest(
            "https://buy.itunes.apple.com/verifyReceipt",
            jsonReceipt,
            {'Content-Type': ['application/x-www-form-urlencoded']}
            )

factory = protocol.Factory()
factory.protocol = storeServer
tcpServer = internet.TCPServer(30000, factory)
tcpServer.setServiceParent(application)

如何修复此错误?我是否必须在端口443上创建另一个服务?如果是这样,我如何将连接到我的应用的服务与通过https连接的服务进行通信?

1 个答案:

答案 0 :(得分:1)

代码示例中的注释样式不正确。 Python使用#作为评论,而不是//.

在修复并通过pyflakes运行代码片段之后,我看到了这些错误:

program.py:1: 'service' imported but unused
program.py:6: 'defer' imported but unused
program.py:21: undefined name 'succeed'
program.py:48: local variable 'd' is assigned to but never used
program.py:57: undefined name 'application'

第21行的未定义名称似乎是您遇到的NameError的原因。 NameError是Python如何发出这种错误的信号:

x = y

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined