📜  JS 创建瑞士 QR-Bill API - 任何代码示例

📅  最后修改于: 2022-03-11 14:55:34.348000             🧑  作者: Mango

代码示例1
//service and docs
https://qr.livingtech.ch

// Configuration
let myConfiguration  = { 
    "Account" : "CH4431999123000889012",
    "CreditorName" : "Muster AG",
    "CreditorAddress1" : "Hauptstrasse 1",
    "CreditorAddress2" : "8000 Zürich",
    "CreditorCountryCode" : "CH",
    "DebtorName" : "LivingTech GmbH",
    "DebtorAddress1" : "Dörflistrasse 10",
    "DebtorAddress2" : "8057 Zürich",
    "DebtorCountryCode" : "CH",
    "Amount" : "1.50",
    "ReferenceNr" : "21000000000313947143000901",
    "UnstructuredMessage" : "Mitteilung zur Rechnung",
    "Currency" : "CHF",
    "IsQrOnly" : "false",
    "Format" : "PDF",
    "Language" : "DE"
}

// Call function to create invoice
let myFile = generateQrInvoice(myConfiguration);

// Work with binary data
if(myFile != null) {
    // ...
}

function generateQrInvoice(myRequestConfiguration) {
    // Main configuration
    let myEndpointUrl = "http://qrbillservice.livingtech.ch";
    let myEndpointPath = "/api/qrinvoice/create/";
    let myApiKey = "mySecretApiKey";

    // GET parameters
    let myGetParams = new URLSearchParams(myRequestConfiguration);

    // Perform request
    fetch(myEndpointUrl + myEndpointPath + "?" + myGetParams, {
        method: "GET", 
        mode: "cors", 
        cache: "no-cache", 
        headers: {
            "APIKEY": myApiKey, 
            "Accept": "application/json"
        }
    }).then(function (myResponse) {
        try {
            // Check status
            if(myResponse.status == 200) {
                // Read and parse JSON
                let myJsonObject  = JSON.parse(myResponse);

                // Check if error
                if(myJsonObject["isSuccessed"] == "true") {
                    if("base64Image" in myJsonObject && myJsonObject["base64Image"].trim() != "") {
                        // E.g. send file to client
                        let myBlob = new Blob(atob(myJsonObject["base64Image"]), {type: "application/pdf"});
                        let myBlobUrl = URL.createObjectURL(myBlob);
                        window.open(myBlobUrl);

                        // Return data
                        return atob(myJsonObject["base64Image"]);
                    } else {
                        throw "no data provided";
                    }
                } else {
                    throw myJsonObject["Message"];
                }
            } else {
                throw "status code " . myResponse.status;
            }
        }
        catch(e) {
            // Handle exception
            console.warn("Error: " + e.message, e);
            return null;
        }
    }).catch(function (err) {
        // Handle exception
        console.warn("Error: " + err.message, err);
        return null;
    });
}