OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Blame | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.preferences;

import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.preferences.JavaPrefPreferencePanel;
import org.openconcerto.ui.preferences.PrefView;
import org.openconcerto.utils.Base64;
import org.openconcerto.utils.JImage;
import org.openconcerto.utils.PrefType;

import java.awt.Desktop;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class PayPalPreferencePanel extends JavaPrefPreferencePanel {

    public static final String PAYPAL_INVOICE = "paypal.invoice";
    public static final String PAYPAL_CLIENTID = "paypal.clientid";
    public static final String PAYPAL_SECRET = "paypal.secret";
    public static final String PAYPAL_INVOICE_X = "paypal.invoice.x";
    public static final String PAYPAL_INVOICE_Y = "paypal.invoice.y";

    // Usage :
    // SQLPreferences prefs = SQLPreferences.getMemCached(comptaConf.getRootSociete());
    // prefs.getBoolean(PayPalPreferencePanel.PAYPAL_INVOICE, false));

    public PayPalPreferencePanel() {
        super("Paypal", null);

        setPrefs(new SQLPreferences(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete()));
        this.removeAll();

        this.setLayout(new GridBagLayout());
        GridBagConstraints c = new DefaultGridBagConstraints();
        // Logo
        c.gridwidth = 3;
        c.weightx = 1;
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.WEST;
        final JImage img = new JImage(PayPalPreferencePanel.class.getResource("logo_paypal_106x29.png"));
        try {
            img.setHyperLink(new URI("https://www.paypal.fr"));
        } catch (URISyntaxException e2) {
            // No hyperlink
        }
        this.add(img, c);
        c.gridy++;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 3;
        this.add(new JLabel("Intégration du lien de paiement PayPal dans les factures PDF"), c);
        c.gridy++;
        this.add(new JLabel("Cette fonctionnalité nécessite la création d'un compte professionnel (gratuit)."), c);
        // Account creation
        final JButton b = new JButton("Créer votre compte maintenant");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (Desktop.isDesktopSupported()) {
                    final String url = "https://www.paypal.com/fr/merchantsignup/create";
                    try {
                        Desktop.getDesktop().browse(new URI(url));
                    } catch (IOException | URISyntaxException e1) {
                        JOptionPane.showMessageDialog(PayPalPreferencePanel.this, url, "Erreur d'ouverture du navigateur", JOptionPane.WARNING_MESSAGE);
                    }
                }

            }
        });
        c.gridy++;
        c.fill = GridBagConstraints.NONE;
        this.add(b, c);

        c.gridy++;
        this.add(new JLabel(" "), c);
        c.gridy++;
        this.add(new JLabelBold("Paramètres de l'API"), c);
        c.gridy++;
        this.add(new JLabel("à créer depuis https://developer.paypal.com"), c);

        // Client ID
        c.gridx = 0;
        c.gridy++;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 1;
        c.weightx = 0;
        this.add(new JLabel("Client ID", SwingConstants.RIGHT), c);
        c.gridwidth = 2;
        c.gridx++;
        c.weightx = 1;
        PrefView<String> clientIdPrefView = new PrefView<>(PrefType.STRING_TYPE, "Client ID", PAYPAL_CLIENTID);
        this.addView(clientIdPrefView);
        this.add(clientIdPrefView.getVW().getComp(), c);

        // Secret
        c.gridx = 0;
        c.gridy++;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 1;
        c.weightx = 0;
        this.add(new JLabel("Secret", SwingConstants.RIGHT), c);
        c.gridwidth = 2;
        c.gridx++;
        c.weightx = 1;
        PrefView<String> secretPrefView = new PrefView<>(PrefType.STRING_TYPE, "Secret", PAYPAL_SECRET);
        this.addView(secretPrefView);
        this.add(secretPrefView.getVW().getComp(), c);

        // Enable
        c.gridx = 0;
        c.gridy++;
        c.fill = GridBagConstraints.NONE;
        c.gridwidth = 3;
        c.weightx = 0;
        c.anchor = GridBagConstraints.EAST;
        final JButton bVerify = new JButton("Vérifier les paramètres");
        this.add(bVerify, c);
        // Enable
        c.gridx = 1;
        c.gridy++;
        c.fill = GridBagConstraints.NONE;
        c.gridwidth = 1;
        c.weightx = 0;
        c.anchor = GridBagConstraints.EAST;
        PrefView<Boolean> enabledPrefView = new PrefView<>(PrefType.BOOLEAN_TYPE, "intégration", PAYPAL_INVOICE);
        this.addView(enabledPrefView);
        final JComponent comp = enabledPrefView.getVW().getComp();
        ((JCheckBox) comp).setText("intégrer le lien de paiement dans les factures PDF");
        this.add(comp, c);

        // Position
        c.gridy++;
        c.fill = GridBagConstraints.HORIZONTAL;
        this.add(new JLabel(" "), c);
        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 3;
        this.add(new JLabelBold("Position du logo sur le PDF"), c);

        c.gridx = 0;
        c.gridy++;
        c.gridwidth = 1;
        c.weightx = 0;
        this.add(new JLabel("X (0 - 440)", SwingConstants.RIGHT), c);
        c.gridx++;
        PrefView<Integer> xPrefView = new PrefView<>(PrefType.INT_TYPE, "X", PAYPAL_INVOICE_X);
        xPrefView.setDefaultValue(10);
        this.addView(xPrefView);
        this.add(xPrefView.getVW().getComp(), c);

        c.gridx = 0;
        c.gridy++;
        c.gridwidth = 1;
        c.weightx = 0;
        this.add(new JLabel("Y (0 - 780)", SwingConstants.RIGHT), c);
        c.gridx++;
        PrefView<Integer> yPrefView = new PrefView<>(PrefType.INT_TYPE, "Y", PAYPAL_INVOICE_Y);
        yPrefView.setDefaultValue(10);
        this.addView(yPrefView);
        this.add(yPrefView.getVW().getComp(), c);
        c.gridy++;
        c.weighty = 1;
        JPanel spacer = new JPanel();
        this.add(spacer, c);

        bVerify.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                boolean ok = false;
                try {
                    ok = sendAuth(clientIdPrefView.getVW().getValue(), secretPrefView.getVW().getValue());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                if (ok) {
                    JOptionPane.showMessageDialog(PayPalPreferencePanel.this, "Paramètres OK", "API Paypal", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(PayPalPreferencePanel.this, "Paramètres incorrects", "API Paypal", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

    }

    @Override
    protected void addViews() {
        // Nothing to do here, panel is built in the constructor
    }

    public static void main(String[] args) throws IOException {
        String id = "Abb2mKqK0TSU6Jgf71CJjFx0u5x6_NmEzHduuvsCXjYCfYxRg9GZ7B6ptx3pijriuq9Apx9Jp-VTFveF";
        String s = "ENR1EyKreAlPbLRI0ofm2NbW6nyk8W5cJUZ7mvaBMgoQ6gB6VBivZpQW6B96toCtLZ3ClCUVutN-Gal2";
        sendAuth(id, s + "");
    }

    static boolean sendAuth(String clientId, String secret) throws IOException {
        final URL url = new URL("https://api.paypal.com/v1/oauth2/token");
        final URLConnection con = url.openConnection();
        final HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST");
        http.setDoOutput(true);
        http.setDefaultUseCaches(false);
        String authString = clientId + ":" + secret;
        String authStringEnc = Base64.encodeBytes(authString.getBytes(), Base64.DONT_BREAK_LINES);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // x-www-form-urlencoded
        final Map<String, String> arguments = new HashMap<>();
        arguments.put("grant_type", "client_credentials");
        final StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet()) {
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;
        http.setFixedLengthStreamingMode(length);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        http.connect();
        try (OutputStream os = http.getOutputStream()) {
            os.write(out);
        }
        if (http.getResponseCode() == 401) {
            return false;
        }

        InputStream is = http.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuilder sb = new StringBuilder();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
        return result.contains("access_token");
    }

}