Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

PayPal: Record an external refund against an invoice

See more PayPal Examples

Record USD 5 already returned by bank transfer for a paid invoice. This call does not move money. To refund a PayPal capture, use the Payments v2 capture refund example instead.

PayPal documentation

Chilkat Swift Downloads

Swift

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()!

    //  Record only money already returned outside PayPal. Reconcile first if a previous
    //  attempt timed out.

    http.setUrlVar(name: "id", value: "INVOICE_ID")
    let body = CkoJsonObject()!
    body.updateString(jsonPath: "method", value: "BANK_TRANSFER")
    body.updateString(jsonPath: "amount.currency_code", value: "USD")
    body.updateString(jsonPath: "amount.value", value: "5.00")

    //  Use the actual date of the transfer; this example records one made today.
    let date = CkoDateTime()!
    date.setFromCurrentSystemTime()
    body.updateString(jsonPath: "refund_date", value: date.get(asIso8601: "YYYY-MM-DD", bLocal: false))

    success = http.httpJson(verb: "POST", url: "https://api-m.sandbox.paypal.com/v2/invoicing/invoices/{$id}/refunds", 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
    }

    print("Record ID: \(result.string(of: "refund_id")!)")

}