//buy demo inside, read the code and talk.classIaptestviewcontroller:uiviewcontroller, skproductsrequestdelegate, skpaymenttransactionobserver{let VERIFY_ Receipt_url="Https://buy.itunes.apple.com/verifyReceipt"Let itms_sandbox_verify_receipt_url="Https://sandbox.itunes.apple.com/verifyReceipt"var productdict:nsmutabledictionary!Overridefunc viewdidload () {super.viewdidload () Skpaymentqueue.defaultqueue (). Addtransactionobserver (self) Requestproducts ()//Request Product List information} deinit{Skpaymentqueue.defaultqueue (). Removetransactionobserver (self)}Overridefunc didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resources the can be recreated. } //Click on the trigger after purchasing the productfunc onselectrechargepackages (productid:string) {//decide whether to support internal purchase first if(Skpaymentqueue.canmakepayments ()) {buyproduct (Productdict[productid) as!skproduct)} Else{println ("============ does not support the internal purchase function") } } //ask the Apple server what products it can sellfunc requestproducts () {varSet= Nsset (array: ["Your product id1","Product Id2".... More]) Let request= Skproductsrequest (productidentifiers:Set asSet<nsobject>) request.Delegate=Self ; Request.start ()}//callback function for the above queryFunc productsrequest (request:skproductsrequest!, Didreceiveresponse response:skproductsresponse!) { if(Productdict = =Nil) {productdict=nsmutabledictionary (capacity:response.products.count)} forProductinchResponse.products as![skproduct] {//The corresponding Sales action button is activated, which is equivalent to the store's product shelves allowing salesprintln"=======product id=======\ (product.productidentifier)") println ("= = = Product Title ==========\ (product.localizedtitle)") println ("= = = Product Description Information ==========\ (product.localizeddescription)") println ("===== Price: =========\ (Product.price)") //Populate commodity dictionariesproductdict.setobject (Product, ForKey:product.productIdentifier)}} //purchase the corresponding productfunc buyproduct (product:skproduct) {var payment=skpayment (product:product) Skpaymentqueue.defaultqueue (). Addpayment (Payment)} func paymentqueue (queue: Skpaymentqueue!, updatedtransactions transactions: [anyobject]!){ //Debug forTransactioninchTransactions {//If the status of the small ticket is purchased complete if(skpaymenttransactionstate.purchased = =transaction.transactionstate) {//update the interface or data to give users the goods they have purchasedprintln"payment becomes ==================.") //Verifying purchase Credentialsself.verifypruchase ()//remove a transaction from the transaction queueSkpaymentqueue.defaultqueue (). Finishtransaction (transaction as!skpaymenttransaction)} Else if(skpaymenttransactionstate.failed = =transaction.transactionstate) {println ("Payment Failure ==================") Skpaymentqueue.defaultqueue (). Finishtransaction (Transaction as!skpaymenttransaction)} Else if(skpaymenttransactionstate.restored = = transaction.transactionstate) {//Restore Purchase//update the interface or data to give users the goods they have purchased// ... //remove a transaction from the transaction queueSkpaymentqueue.defaultqueue (). Finishtransaction (transaction as!skpaymenttransaction)} }} func Verifypruchase () {//verify credentials, get the trading credentials returned to Apple//Appstorereceipturl iOS7.0 added, after the purchase transaction is completed, the credentials will be stored at that addressLet Receipturl =Nsbundle.mainbundle (). Appstorereceipturl//get the purchase credentials from the sandboxLet Receiptdata = NSData (contentsofurl:receipturl!) //send a network POST request to verify the purchase credentialsLet URL = Nsurl (string: Itms_sandbox_verify_receipt_url)//Domestic Visit Apple server is slow, timeoutinterval need a bit longerLet request = Nsmutableurlrequest (url:url!, CachePolicy:NSURLRequestCachePolicy.UseProtocolCachePolicy, timeOutInterval:10.0) Request. HttpMethod="POST" //transferring data over a network, mostly in the case of a string rather than binary data//The BASE64 encoded string is transmitted. /** BASE64 commonly used coding scheme, usually for data transmission, and the basic algorithm of encryption algorithm, transmission process can guarantee the stability of data transmission BASE64 can be encoded and decoded*/Let encodestr= Receiptdata?. Base64encodedstringwithoptions (nsdatabase64encodingoptions.encodingendlinewithlinefeed) let payload
= NSString (string:"{\ "receipt-data\": \ ""+ encodestr! +"\"}") println (payload) Let Payloaddata=payload.datausingencoding (nsutf8stringencoding) request. Httpbody=Payloaddata; //submit a validation request and get the official validation json resultLet result =nsurlconnection.sendsynchronousrequest (Request, Returningresponse:nil, Error:nil)//official verification result is empty if(Result = =Nil) { //validation Failedprintln"validation Failed") return} var dict:anyobject? = Nsjsonserialization.jsonobjectwithdata (result!, Options:NSJSONReadingOptions.AllowFragments, Error:nil)if(Dict! =Nil) { //The following information in the dictionary is basically a guarantee of data security//bundle_id&application_version&product_id&transaction_id//Validation Successfulprintln (dict)}} Func restorepurchase () {skpaymentqueue.defaultqueue (). Restorecompletedtransactions ()}}
PS: Problems encountered in the process
1. Click buy no popup Enter account password box, the solution is to phone settings inside the itunes Store and the APP store to write off your original account
2. Each time a skpaymentqueue.defaultqueue (). Addtransactionobserver (self) State listener is added, a number of payment failures are invoked, because after the previous debug failure, no Skpaymentqueue.defaultqueue (). Finishtransaction (Transaction as! skpaymenttransaction), so each time the system automatically asks you for the last failed operation, the result continues to fail.
[Ios]swift in-version purchase