Swift Requires Chilkat v11.0.0+
Swift
PayPal: Save a payable invoice QR code as a PNG
See more PayPal Examples
Generate a 300-pixel payment QR code for a sent, payable invoice. Decode the base64 image into a PNG for a printed invoice; the code opens the payment page, and is not proof of payment.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// See Unlock Chilkat before making requests.
// For the merchant's internal backoffice application. Load the sandbox token
// from the merchant's credential store. Keep it out of publicly distributed apps.
// See Get a PayPal access token.
let http = CkoHttp()!
http.authToken = "SANDBOX_ACCESS_TOKEN"
let resp = CkoHttpResponse()!
// Use a sent, payable invoice. Width and height are JSON numbers, in pixels.
http.setUrlVar(name: "id", value: "INVOICE_ID")
let body = CkoJsonObject()!
body.updateInt(jsonPath: "width", value: 300)
body.updateInt(jsonPath: "height", value: 300)
body.updateString(jsonPath: "action", value: "pay")
success = http.httpJson(verb: "POST", url: "https://api-m.sandbox.paypal.com/v2/invoicing/invoices/{$id}/generate-qr-code", json: body, contentType: "application/json", response: resp)
if success != true {
print("No HTTP response: \(http.lastErrorText!)")
return
}
if (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
let errorInfo = CkoJsonObject()!
errorInfo.load(json: resp.bodyStr)
print("HTTP \(resp.statusCode.intValue) \(errorInfo.string(of: "name")!) \(errorInfo.string(of: "details[0].issue")!)")
print("PayPal debug ID: \(errorInfo.string(of: "debug_id")!)")
return
}
let result = CkoJsonObject()!
var parsed: Bool = result.load(json: resp.bodyStr)
if parsed != true {
print("Expected a JSON response; HTTP \(resp.statusCode.intValue)")
return
}
let png = CkoBinData()!
if result.hasMember(jsonPath: "image") != true {
print("QR response did not contain an image.")
return
}
var decoded: Bool = png.appendEncoded(encData: result.string(of: "image"), encoding: "base64")
if decoded != true {
print("Invalid base64 image.")
return
}
var savedImage: Bool = png.writeFile(path: "paypal-invoice-qr.png")
if savedImage != true {
print("Could not write the invoice QR image.")
return
}
print("Saved paypal-invoice-qr.png.")
}