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

PayPal: Export a day of balance activity to CSV

See more PayPal Examples

Create a UTF-8 ledger export for the previous UTC day. Preserve signed amounts and separate currencies, and leave absent fees blank. The file is written after all pages have been read. Transaction Search can lag by several hours.

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()!
    //  Export yesterday in UTC; choose an earlier date if the report is still refreshing.
    let day = CkoDateTime()!
    day.setFromCurrentSystemTime()
    day.addDays(numDays: -1)
    var utcDate: String? = day.get(asIso8601: "YYYY-MM-DD", bLocal: false)
    let startTime = CkoStringBuilder()!
    startTime.append(value: utcDate)
    startTime.append(value: "T00:00:00Z")
    let endTime = CkoStringBuilder()!
    endTime.append(value: utcDate)
    endTime.append(value: "T23:59:59.999Z")
    let query = CkoJsonObject()!
    query.updateString(jsonPath: "start_date", value: startTime.getAsString())
    query.updateString(jsonPath: "end_date", value: endTime.getAsString())
    query.updateString(jsonPath: "balance_affecting_records_only", value: "Y")
    query.updateString(jsonPath: "fields", value: "transaction_info")
    query.updateInt(jsonPath: "page_size", value: 100)
    let csv = CkoCsv()!
    csv.hasColumnNames = true
    csv.setColumnName(index: 0, columnName: "transaction_id")
    csv.setColumnName(index: 1, columnName: "event_code")
    csv.setColumnName(index: 2, columnName: "status")
    csv.setColumnName(index: 3, columnName: "currency")
    csv.setColumnName(index: 4, columnName: "amount")
    csv.setColumnName(index: 5, columnName: "fee_currency")
    csv.setColumnName(index: 6, columnName: "fee")
    var row: Int = 0
    var page: Int = 1
    var lastPage: Int = 1
    while (page <= lastPage) {
        query.updateInt(jsonPath: "page", value: page)
        success = http.httpParams(verb: "GET", url: "https://api-m.sandbox.paypal.com/v1/reporting/transactions", json: query, 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 parsedResult: Bool = result.load(json: resp.bodyStr)
        if parsedResult != true {
            print("Expected a JSON response; HTTP \(resp.statusCode.intValue)")
            return
        }

        var i: Int = 0
        var count: Int = result.size(ofArray: "transaction_details").intValue
        while (i < count) {
            result.i = i
            csv.setCell(row: row, col: 0, content: result.string(of: "transaction_details[i].transaction_info.transaction_id"))
            csv.setCell(row: row, col: 1, content: result.string(of: "transaction_details[i].transaction_info.transaction_event_code"))
            csv.setCell(row: row, col: 2, content: result.string(of: "transaction_details[i].transaction_info.transaction_status"))
            csv.setCell(row: row, col: 3, content: result.string(of: "transaction_details[i].transaction_info.transaction_amount.currency_code"))
            csv.setCell(row: row, col: 4, content: result.string(of: "transaction_details[i].transaction_info.transaction_amount.value"))
            csv.setCell(row: row, col: 5, content: result.string(of: "transaction_details[i].transaction_info.fee_amount.currency_code"))
            csv.setCell(row: row, col: 6, content: result.string(of: "transaction_details[i].transaction_info.fee_amount.value"))
            row = row + 1
            i = i + 1
        }

        lastPage = result.int(of: "total_pages").intValue
        page = page + 1
    }

    let filename = CkoStringBuilder()!
    filename.append(value: "paypal-activity-")
    filename.append(value: utcDate)
    filename.append(value: ".csv")
    var saved: Bool = csv.saveFile2(path: filename.getAsString(), charset: "utf-8")
    if saved != true {
        print("\(csv.lastErrorText!)")
        return
    }

    print("Exported \(row) rows to \(filename.getAsString()!)")

}