Получение транзакций из WebView с проверкой учетных данных (Plaid) - PullRequest
0 голосов
/ 09 мая 2018

Как получить транзакции из WebView с проверкой учетных данных на Android?

Это мой код:

public class PlaidViewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_plaid_view);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Initialize Link
    HashMap<String, String> linkInitializeOptions = new HashMap<String,String>();
    linkInitializeOptions.put("key", "56632c5b63db7b7a155000b7c9507649");
    linkInitializeOptions.put("product", "transact`enter code here`ions,auth");
    linkInitializeOptions.put("apiVersion", "v2"); // set this to "v1" if using the legacy Plaid API
    linkInitializeOptions.put("env", "sandbox");
    linkInitializeOptions.put("clientName", "Test App");
    linkInitializeOptions.put("selectAccount", "true");
    linkInitializeOptions.put("webhook", "http://requestb.in");
    linkInitializeOptions.put("baseUrl", "https://cdn.plaid.com/link/v2/stable/link.html");
    // If initializing Link in PATCH / update mode, also provide the public_token
    // linkInitializeOptions.put("public_token", "PUBLIC_TOKEN")

    // Generate the Link initialization URL based off of the configuration options.
    final Uri linkInitializationUrl = generateLinkInitializationUrl(linkInitializeOptions);

    // Modify Webview settings - all of these settings may not be applicable
    // or necesscary for your integration.
    final WebView plaidLinkWebview = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = plaidLinkWebview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    WebView.setWebContentsDebuggingEnabled(true);

    // Initialize Link by loading the Link initiaization URL in the Webview
    plaidLinkWebview.loadUrl(linkInitializationUrl.toString());

    // Override the Webview's handler for redirects
    // Link communicates success and failure (analogous to the web's onSuccess and onExit
    // callbacks) via redirects.
    plaidLinkWebview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Parse the URL to determine if it's a special Plaid Link redirect or a request
            // for a standard URL (typically a forgotten password or account not setup link).
            // Handle Plaid Link redirects and open traditional pages directly in the  user's
            // preferred browser.
            Uri parsedUri = Uri.parse(url);
            if (parsedUri.getScheme().equals("plaidlink")) {
                String action = parsedUri.getHost();
                HashMap<String, String> linkData = parseLinkUriData(parsedUri);

                if (action.equals("connected")) {
                    // User successfully linked
                    Log.d("-->Public token: ", linkData.get("public_token")+"");
                    Log.d("-->Account ID: ", linkData.get("account_id")+"");
                    Log.d("-->Account name: ", linkData.get("account_name")+"");
                    Log.d("-->Institution type: ", linkData.get("institution_type")+"");
                    Log.d("-->Institution name: ", linkData.get("institution_name")+"");

                    // Reload Link in the Webview
                    // You will likely want to transition the view at this point.
                    plaidLinkWebview.loadUrl(linkInitializationUrl.toString());
                } else if (action.equals("exit")) {
                    // User exited
                    // linkData may contain information about the user's status in the Link flow,
                    // the institution selected, information about any error encountered,
                    // and relevant API request IDs.
                    Log.d("User status in flow: ", linkData.get("status"));
                    // The requet ID keys may or may not exist depending on when the user exited
                    // the Link flow.
                    Log.d("Link request ID: ", linkData.get("link_request_id"));
                    Log.d("API request ID: ", linkData.get("plaid_api_request_id"));

                    // Reload Link in the Webview
                    // You will likely want to transition the view at this point.
                    plaidLinkWebview.loadUrl(linkInitializationUrl.toString());
                } else {
                    Log.d("Link action detected: ", action);
                }
                // Override URL loading
                return true;
            } else if (parsedUri.getScheme().equals("https") ||
                       parsedUri.getScheme().equals("http")) {
                // Open in browser - this is most  typically for 'account locked' or
                // 'forgotten password' redirects
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                // Override URL loading
                return true;
            } else {
                // Unknown case - do not override URL loading
                return false;
            }
        }
    });
}

// Generate a Link initialization URL based on a set of configuration options
public Uri generateLinkInitializationUrl(HashMap<String,String>linkOptions) {
    Uri.Builder builder = Uri.parse(linkOptions.get("baseUrl"))
            .buildUpon()
            .appendQueryParameter("isWebview", "true")
            .appendQueryParameter("isMobile", "true");
    for (String key : linkOptions.keySet()) {
        if (!key.equals("baseUrl")) {
            builder.appendQueryParameter(key, linkOptions.get(key));
        }
    }
    return builder.build();
}

// Parse a Link redirect URL querystring into a HashMap for easy manipulation and access
public HashMap<String,String> parseLinkUriData(Uri linkUri) {
    HashMap<String,String> linkData = new HashMap<String,String>();
    for(String key : linkUri.getQueryParameterNames()) {
        linkData.put(key, linkUri.getQueryParameter(key));
    }
    return linkData;
}

Это мой код, и я успешно получаю результат

05-09 10:29:32.268 3091-3091/? D/-->Public token:: public-sandbox-2fddfc55-abb1-439d-84e0-6b1207503eb3
05-09 10:29:32.268 3091-3091/? D/-->Account ID:: nordpMwPjZSoVok6XzaeCQArXDjjM4H6Nj3ox
05-09 10:29:32.268 3091-3091/? D/-->Account name:: Plaid Credit Card
05-09 10:29:32.269 3091-3091/? D/-->Institution type:: null
05-09 10:29:32.269 3091-3091/? D/-->Institution name:: Citi

из этого, я хочу получить транзакцию, пожалуйста, помогите мне

Используя почтальона, я сделал https://sandbox.plaid.com/transactions/get

{
  "client_id": "5ae9627a6c0fcd0012c97bf1",
  "secret": "b67ff6d1a462303cf43e2e83edaf33",
  "access_token": "public-sandbox-2fddfc55-abb1-439d-84e0-6b1207503eb3",
  "start_date": "2017-01-01",
  "end_date": "2017-02-01",
  "options": {
    "count": 250,
    "offset": 100
  }
  }

но я получаю сообщение об ошибке

{
    "display_message": null,
    "error_code": "INVALID_ACCESS_TOKEN",
    "error_message": "provided token is the wrong type. expected \"access\", got \"public\"",
    "error_type": "INVALID_INPUT",
    "request_id": "bTgTg"
}

как это, пожалуйста, помогите

1 Ответ

0 голосов
/ 16 октября 2018

Старый вопрос, но все еще пишу это для записей Похоже, вы использовали публичный токен, как указано в вашем запросе почтальона. Сначала необходимо обменять общедоступный токен с токеном доступа, что устранит необходимость в прямой связи между конечным пользователем и пледом.

"access_token": "public-sandbox-2fddfc55-abb1-439d-84e0-6b1207503eb3",

Для справки, жетоны доступа к пледам начинаются с access-.., а не public-..

Для получения дополнительной информации вы можете обратиться туда. enter image description here https://plaid.com/docs/quickstart/#rotate-access-token

...