通过Vaadin6中的自定义小部件进行Google电子钱包集成

时间:2013-12-31 10:39:00

标签: javascript vaadin jsni android-pay gwt-widgets

我需要将Google钱包集成到我的Vaadin 6应用程序中,从here下载钱包api / demo。

首先,我试图将这个给定的样本运行到vaadin中,但经过长时间的努力,我现在被困住了。尝试了很多方法/例子,研究了很多关于小部件但是只发现了this例子简单而有效。

我添加了我的代码行,流程顺利进行购买()调用,但当它调用钱包API函数购买()时,浏览器的页面会被清除,什么都没发生好像程序结束了。

如果我的方法有误,请建议我任何例子或任何解决方法。

干杯

script.js

    function proceedMessage(message) {
    alert(message);
    return message;
}

function loadConfig(){
    google.load('payments', '1.0', {
        'packages': ['sandbox_config']
    });
}

var paymentStatus ;
//Success handler
var successHandler = function(status){
    if (window.console != undefined) {
        console.log("Purchase completed successfully: ", status);
        //window.location.reload();
    }
    paymentStatus = "SUCCESS";
}

//Failure handler
var failureHandler = function(status){
    if (window.console != undefined) {
        console.log("Purchase failed ", status);
    }
    paymentStatus = "FAILURE";
}

function result(){
    return paymentStatus;
}

function purchase(item) {
    var generated_jwt;
    if (item == "Item1") {
        generated_jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIxMjgyOTQzNjkwNDgwNzQ5NTkwMiIsImF1ZCI6Ikdvb2dsZSIsInR5cCI6Imdvb2dsZS9wYXltZW50cy9pbmFwcC9pdGVtL3YxIiwiaWF0IjoxMzg4MTM5NDQzLCJleHAiOjEzODgxMzk1MDMsInJlcXVlc3QiOnsibmFtZSI6IlBpZWNlIG9mIENha2UiLCJkZXNjcmlwdGlvbiI6IlZpcnR1YWwgY2hvY29sYXRlIGNha2UgdG8gZmlsbCB5b3VyIHZpcnR1YWwgdHVtbXkiLCJwcmljZSI6IjEwLjUwIiwiY3VycmVuY3lDb2RlIjoiVVNEIiwic2VsbGVyRGF0YSI6InVzZXJfaWQ6MTIyNDI0NSxvZmZlcl9jb2RlOjMwOTg1NzY5ODcsYWZmaWxpYXRlOmFrc2RmYm92dTlqIn19.k8OWXVdemtfNFPu4-PSc-1OIkPS7o0bYA1MMq1dhUXQ";
    }  else {
        return;
    }
        goog.payments.inapp.buy({
            'jwt'     : generated_jwt,
            'success' : successHandler,
            'failure' : failureHandler
        });
    }

客户端组件VGoogleWallet.java

package com.example.testing.client.ui;
import com.example.testing.client.ui.MessageJSNI;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Widget;

/**
 * Client side widget which communicates with the server. Messages from the
 * server are shown as HTML and mouse clicks are sent to the server.
 */
public class VGoogleWallet extends Widget implements Paintable, ClickHandler {

    /** Set the CSS class name to allow styling. */
    public static final String CLASSNAME = "v-googlewallet";

    public static final String CLICK_EVENT_IDENTIFIER = "click";

    /** The client side widget identifier */
    protected String paintableId;

    /** Reference to the server connection object. */
    protected ApplicationConnection client;

    /**
     * The constructor should first call super() to initialize the component and
     * then handle any initialization relevant to Vaadin.
     */
    public VGoogleWallet() {
        // TODO This example code is extending the GWT Widget class so it must set a root element.
        // Change to a proper element or remove this line if extending another widget.

        setElement(Document.get().createDivElement());
        // This method call of the Paintable interface sets the component
        // style name in DOM tree"
        setStyleName(CLASSNAME);

    }

    /**
     * Called whenever an update is received from the server 
     */
    public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
        // This call should be made first. 
        // It handles sizes, captions, tooltips, etc. automatically.
        if (client.updateComponent(this, uidl, true)) {
            // If client.updateComponent returns true there has been no changes and we
            // do not need to update anything.
            return;
        }

        // Save reference to server connection object to be able to send
        // user interaction later
        this.client = client;

        // Save the client side identifier (paintable id) for the widget
        paintableId = uidl.getId();

        // Process attributes/variables from the server
        // The attribute names are the same as we used in 
        // paintContent on the server-side

        String message = uidl.getStringAttribute("message");
        String paymentStatus = uidl.getStringVariable("paymentStatus");
        getElement().setInnerHTML(MessageJSNI.proceedMessage(message));
        MessageJSNI.loadConfig();
        MessageJSNI.purchase();
        paymentStatus = MessageJSNI.getResult();

        client.updateVariable(paintableId, "paymentStatus", "PAID", true);
    }

}

服务器端组件GoogleWallet.java

package com.example.testing;

import java.util.Map;

import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.ui.AbstractComponent;

/**
 * Server side component for the VGoogleWallet widget.
 */
@com.vaadin.ui.ClientWidget(com.example.testing.client.ui.VGoogleWallet.class)
public class GoogleWallet extends AbstractComponent {

    private String message = "default message";
    private String paymentStatus ;

    public GoogleWallet(String message){
        this.message = message;
    }

    @Override
    public void paintContent(PaintTarget target) throws PaintException {
        super.paintContent(target);

        // Paint any component specific content by setting attributes
        // These attributes can be read in updateFromUIDL in the widget
        target.addAttribute("message", message);
        target.addVariable(this, "paymentStatus", "UNPAID");

    }

//  /**
//   * Receive and handle events and other variable changes from the client.
//   * 
//   * {@inheritDoc}
//   */
    @Override
    public void changeVariables(Object source, Map<String, Object> variables) {
        super.changeVariables(source, variables);
//
//       Variable set by the widget are returned in the "variables" map.
//
        if (variables.containsKey("paymentStatus")) {
//
            // When the user has clicked the component we increase the 
            // click count, update the message and request a repaint so 
            // the changes are sent back to the client.
            paymentStatus = (String) variables.get("paymentStatus");
            System.out.println(paymentStatus);
            requestRepaint();
        }
    }

}

JavaScript Native Interface类MessageJSNI.java

package com.example.testing.client.ui;

public class MessageJSNI {

    protected MessageJSNI() {
    }

    public native static String proceedMessage(String message) /*-{
        return $wnd.proceedMessage(message);
    }-*/;

    public native static void loadConfig()/*-{
    $wnd.loadConfig();
  }-*/;

    public native static void purchase()/*-{
    $wnd.purchase('Item1');
  }-*/;


    public native static String getResult()/*-{
    return $wnd.result();
    }-*/;


}

TestingWidgetset.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module>
    <inherits name="com.vaadin.terminal.gwt.DefaultWidgetSet" />

    <script src="script.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 

    <script src="http://www.google.com/jsapi"></script>
    <!--
     Uncomment the following to compile the widgetset for one browser only.
     This can reduce the GWT compilation time significantly when debugging.
     The line should be commented out before deployment to production
     environments.

     Multiple browsers can be specified for GWT 1.7 as a comma separated
     list. The supported user agents at the moment of writing were:
     ie6,ie8,gecko,gecko1_8,safari,opera

     The value gecko1_8 is used for Firefox 3 and later and safari is used for
     webkit based browsers including Google Chrome.
    -->
    <!-- <set-property name="user.agent" value="gecko1_8"/> -->

    <!--
     To enable SuperDevMode, uncomment this line and use the
     Super Dev Mode for Vaadin 6 add-on.

     SuperDevMode enables debugging of the client side of a Vaadin
     application using the JavaScript debugger of a browser. Java code is
     shown and debugging can take place on the Java level when using a browser
     that support source maps (currently Chrome, implementation under work
     for Firefox).

     See https://vaadin.com/directory#addon/super-dev-mode-for-vaadin-6 for
     more information and instructions.
    -->
    <!-- <set-configuration-property name="devModeRedirectEnabled" value="true" /> -->

</module>

1 个答案:

答案 0 :(得分:0)

至少花了几个小时后,我在我的Vaadin 6应用程序中运行了这个演示,虽然现在我在服务器生成的JWT中遇到了一些问题,但是这个演示正在运行。

以下是代码中的更改

的script.js

function buy(){
    google.payments.inapp.buy({
    'jwt'     : "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIxMDk3OTc5MTY0NTUxNTM4MDY2OSIsImF1ZCI6Ikdvb2dsZSIsInR5cCI6Imdvb2dsZS9wYXltZW50cy9pbmFwcC9pdGVtL3YxIiwiaWF0IjoxMzg4NDcwMzM5LCJleHAiOjEzODg0NzAzOTksInJlcXVlc3QiOnsibmFtZSI6IkNsb3VkU3RyZWFtMTUiLCJkZXNjcmlwdGlvbiI6IkNsb3VkU3RyZWFtIE9uZSBtb250aCBwYWNrYWdlIGZvciAxNSB1c2VycyIsInByaWNlIjoiMjUwLjAwIiwiY3VycmVuY3lDb2RlIjoiVVNEIiwic2VsbGVyRGF0YSI6InVzZXJfaWQ6MTIyNDI0NSxvZmZlcl9jb2RlOjMwOTg1NzY5ODcsYWZmaWxpYXRlOmFrc2RmYm92dTlqIn19.JoUUTcVilz8nBSPjbCVuESi-QUS7fN6f9PeEseE7CSY",
    'success' : function(status){if (window.console != undefined) {console.log("Purchase completed successfully: ", status);}},
    'failure' : function(status){if (window.console != undefined) {console.log("Purchase failed ", status);}}
});
}

客户端小部件VGoogleWallet.java

package com.example.testing.client.ui;

import com.example.testing.client.ui.MessageJSNI;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Widget;

/**
 * Client side widget which communicates with the server. Messages from the
 * server are shown as HTML and mouse clicks are sent to the server.
 */
public class VGoogleWallet extends Widget implements Paintable, ClickHandler {

    /** Set the CSS class name to allow styling. */
    public static final String CLASSNAME = "v-googlewallet";

    /** The client side widget identifier */
    protected String paintableId;

    /** Reference to the server connection object. */
    protected ApplicationConnection client;

    /**
     * The constructor should first call super() to initialize the component and
     * then handle any initialization relevant to Vaadin.
     */
    public VGoogleWallet() {
        // TODO This example code is extending the GWT Widget class so it must set a root element.
        // Change to a proper element or remove this line if extending another widget.

        setElement(Document.get().createDivElement());
        // This method call of the Paintable interface sets the component
        // style name in DOM tree"
        setStyleName(CLASSNAME);

    }

    /**
     * Called whenever an update is received from the server 
     */
    public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
        // This call should be made first. 
        // It handles sizes, captions, tooltips, etc. automatically.
        if (client.updateComponent(this, uidl, true)) {
            // If client.updateComponent returns true there has been no changes and we
            // do not need to update anything.
            return;
        }

        // Save reference to server connection object to be able to send
        // user interaction later
        this.client = client;

        // Save the client side identifier (paintable id) for the widget
        paintableId = uidl.getId();

            MessageJSNI.buy();
    }


}

TestingWidgetset.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module>
    <inherits name="com.vaadin.terminal.gwt.DefaultWidgetSet" />

    <script src="script.js"></script>

    <script src="https://sandbox.google.com/checkout/inapp/lib/buy.js"></script> 
    <!--
     Uncomment the following to compile the widgetset for one browser only.
     This can reduce the GWT compilation time significantly when debugging.
     The line should be commented out before deployment to production
     environments.

     Multiple browsers can be specified for GWT 1.7 as a comma separated
     list. The supported user agents at the moment of writing were:
     ie6,ie8,gecko,gecko1_8,safari,opera

     The value gecko1_8 is used for Firefox 3 and later and safari is used for
     webkit based browsers including Google Chrome.
    -->
    <!-- <set-property name="user.agent" value="gecko1_8"/> -->

    <!--
     To enable SuperDevMode, uncomment this line and use the
     Super Dev Mode for Vaadin 6 add-on.

     SuperDevMode enables debugging of the client side of a Vaadin
     application using the JavaScript debugger of a browser. Java code is
     shown and debugging can take place on the Java level when using a browser
     that support source maps (currently Chrome, implementation under work
     for Firefox).

     See https://vaadin.com/directory#addon/super-dev-mode-for-vaadin-6 for
     more information and instructions.
    -->
    <!-- <set-configuration-property name="devModeRedirectEnabled" value="true" /> -->

</module>

MessageJSNI.java

package com.example.testing.client.ui;

public class MessageJSNI {

    protected MessageJSNI() {
    }

    public native static void buy()/*-{
    $wnd.buy();
  }-*/;

}