Last active
December 13, 2022 16:10
-
-
Save apptects/1540e8d5ba9c3edec61d049798d77844 to your computer and use it in GitHub Desktop.
Receipt validation on server side
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"github.com/gorilla/mux" | |
"log" | |
"net/http" | |
) | |
// ReceiptData contains receipt data received from client | |
type ReceiptData struct { | |
ReceiptBase64 string `json:"receipt"` | |
IsSandBox bool `json:"sandbox"` | |
} | |
// AppStoreReceiptData contains receipt data sent to App Store | |
type AppStoreReceiptData struct { | |
ReceiptData string `json:"receipt-data"` | |
} | |
// ReceiptValidationResult contains validation result returned to client | |
type ReceiptValidationResult struct { | |
Result int | |
Environment string | |
} | |
func main() { | |
router := mux.NewRouter() | |
router.HandleFunc("/validatereceipt", func(writer http.ResponseWriter, r *http.Request) { | |
var receipt ReceiptData | |
// Read request body | |
decoder := json.NewDecoder(r.Body) | |
error := decoder.Decode(&receipt) | |
if error != nil { | |
http.Error(writer, error.Error(), http.StatusBadRequest) | |
return | |
} | |
// Decide which App Store URL to use (Sandbox or Production) | |
var appStoreURL string | |
if receipt.IsSandBox { | |
appStoreURL = "https://sandbox.itunes.apple.com/verifyReceipt" | |
} else { | |
appStoreURL = "https://buy.itunes.apple.com/verifyReceipt" | |
} | |
// Encode json data for App Store | |
buffer := new(bytes.Buffer) | |
appStoreReceiptData := AppStoreReceiptData{ReceiptData:receipt.ReceiptBase64} | |
error = json.NewEncoder(buffer).Encode(appStoreReceiptData) | |
// Send receipt to App Store | |
response, error := http.Post(appStoreURL, "application/json", buffer) | |
if error != nil { | |
log.Fatalln(error) | |
} | |
// Decode App Store response | |
var receiptValidationResult ReceiptValidationResult | |
json.NewDecoder(response.Body).Decode(&receiptValidationResult) | |
fmt.Printf("Receipt validated with result %d for environment: %s", receiptValidationResult.Result, receiptValidationResult.Environment) | |
// Return result to client | |
writer.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(writer).Encode(receiptValidationResult) | |
}).Methods("POST") | |
error := http.ListenAndServe("localhost:8080", router) | |
if error != nil { | |
fmt.Print(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment