无法使用 Javascript 和 python 打开格子链接
当将格子链接处理程序称为旋转时,然后消失。我无法获得链接对话框以完全显示以获取访问令牌。在端口5000上使用烧瓶为Python服务器进行设置,并使用格子API在Python中进行呼叫。在客户端使用JavaScript。
我可以看到请求正在通过,但是什么都没发生或似乎向客户端发布:
127.0.0.1 - - [05/Apr/2022 21:53:31] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Apr/2022 21:54:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Apr/2022 21:54:10] "POST /create_link_token HTTP/1.1" 200 -
javaScript:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="link-button">Link Account</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
<script type="text/javascript">
(async function($) {
var handler = Plaid.create({
// Create a new link_token to initialize Link
token: (await $.post('/create_link_token')).link_token,
receivedRedirectUri: window.location.href,
onLoad: function() {
// Optional, called when Link loads
},
onSuccess: function(public_token, metadata) {
// Send the public_token to your app server.
// The metadata object contains info about the institution the
// user selected and the account ID or IDs, if the
// Account Select view is enabled.
$.post('/exchange_public_token', {
public_token: public_token,
});
},
onExit: function(err, metadata) {
// The user exited the Link flow.
if (err != null) {
// The user encountered a Plaid API error prior to exiting.
}
// metadata contains information about the institution
// that the user selected and the most recent API request IDs.
// Storing this information can be helpful for support.
},
onEvent: function(eventName, metadata) {
// Optionally capture Link flow events, streamed through
// this callback as your users connect an Item to Plaid.
// For example:
// eventName = "TRANSITION_VIEW"
// metadata = {
// link_session_id: "123-abc",
// mfa_type: "questions",
// timestamp: "2017-09-14T14:42:19.350Z",
// view_name: "MFA",
// }
}
});
$('#link-button').on('click', function(e) {
handler.open();
});
})(jQuery);
</script>
</body>
</html>
python server.py:
# source /Users/tnappy/node_projects/quickstart/python/bin/activate
# Read env vars from .env file
from plaid.exceptions import ApiException
from plaid.model.payment_amount import PaymentAmount
from plaid.model.payment_amount_currency import PaymentAmountCurrency
from plaid.model.products import Products
from plaid.model.country_code import CountryCode
from plaid.model.recipient_bacs_nullable import RecipientBACSNullable
from plaid.model.payment_initiation_address import PaymentInitiationAddress
from plaid.model.payment_initiation_recipient_create_request import PaymentInitiationRecipientCreateRequest
from plaid.model.payment_initiation_payment_create_request import PaymentInitiationPaymentCreateRequest
from plaid.model.payment_initiation_payment_get_request import PaymentInitiationPaymentGetRequest
from plaid.model.link_token_create_request_payment_initiation import LinkTokenCreateRequestPaymentInitiation
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.link_token_create_request import LinkTokenCreateRequest
from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
from plaid.model.asset_report_create_request import AssetReportCreateRequest
from plaid.model.asset_report_create_request_options import AssetReportCreateRequestOptions
from plaid.model.asset_report_user import AssetReportUser
from plaid.model.asset_report_get_request import AssetReportGetRequest
from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest
from plaid.model.auth_get_request import AuthGetRequest
from plaid.model.transactions_get_request import TransactionsGetRequest
from plaid.model.transactions_get_request_options import TransactionsGetRequestOptions
from plaid.model.identity_get_request import IdentityGetRequest
from plaid.model.investments_transactions_get_request_options import InvestmentsTransactionsGetRequestOptions
from plaid.model.investments_transactions_get_request import InvestmentsTransactionsGetRequest
from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest
from plaid.model.accounts_get_request import AccountsGetRequest
from plaid.model.investments_holdings_get_request import InvestmentsHoldingsGetRequest
from plaid.model.item_get_request import ItemGetRequest
from plaid.model.institutions_get_by_id_request import InstitutionsGetByIdRequest
from plaid.model.transfer_authorization_create_request import TransferAuthorizationCreateRequest
from plaid.model.transfer_create_request import TransferCreateRequest
from plaid.model.transfer_get_request import TransferGetRequest
from plaid.model.transfer_network import TransferNetwork
from plaid.model.transfer_type import TransferType
from plaid.model.transfer_user_in_request import TransferUserInRequest
from plaid.model.ach_class import ACHClass
from plaid.model.transfer_create_idempotency_key import TransferCreateIdempotencyKey
from plaid.model.transfer_user_address_in_request import TransferUserAddressInRequest
from plaid.api import plaid_api
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
from datetime import datetime
from datetime import timedelta
import plaid
import base64
import os
import datetime
import json
import time
from dotenv import load_dotenv
from werkzeug.wrappers import response
import pyodbc
load_dotenv()
app = Flask(__name__)
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=DESKTOP-DJCMSVC\MJBOURQUIN_SQL;"
"Database=MyBudget;"
"Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Accounts')
for row in cursor:
print('row = %r' % (row,))
vals = ("SOMETHING")
data = "UPDATE Accounts Set API_ID = 'SOMETHING' WHERE Id = 1"
cursor.execute(data)
cursor.commit();
access = "THAT THING"
cursor = cnxn.execute('UPDATE Accounts Set API_ID = ? WHERE Id = ?', [access,1])
cursor.commit();
# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
# Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')
# PLAID_PRODUCTS is a comma-separated list of products to use when initializing
# Link. Note that this list must contain 'assets' in order for the app to be
# able to create and retrieve asset reports.
PLAID_PRODUCTS = os.getenv('PLAID_PRODUCTS', 'transactions').split(',')
# PLAID_COUNTRY_CODES is a comma-separated list of countries for which users
# will be able to select institutions from.
PLAID_COUNTRY_CODES = os.getenv('PLAID_COUNTRY_CODES', 'US').split(',')
products = []
for product in PLAID_PRODUCTS:
products.append(Products(product))
def empty_to_none(field):
value = os.getenv(field)
if value is None or len(value) == 0:
return None
return value
host = plaid.Environment.Sandbox
if PLAID_ENV == 'sandbox':
host = plaid.Environment.Sandbox
if PLAID_ENV == 'development':
host = plaid.Environment.Development
if PLAID_ENV == 'production':
host = plaid.Environment.Production
# Parameters used for the OAuth redirect Link flow.
#
# Set PLAID_REDIRECT_URI to 'http://localhost:3000/'
# The OAuth redirect flow requires an endpoint on the developer's website
# that the bank website should redirect to. You will need to configure
# this redirect URI for your client ID through the Plaid developer dashboard
# at https://dashboard.plaid.com/team/api.
PLAID_REDIRECT_URI = empty_to_none('PLAID_REDIRECT_URI')
configuration = plaid.Configuration(
host=host,
api_key={
'clientId': PLAID_CLIENT_ID,
'secret': PLAID_SECRET,
'plaidVersion': '2020-09-14'
}
)
api_client = plaid.ApiClient(configuration)
client = plaid_api.PlaidApi(api_client)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/my-link/')
def my_link():
print ('I got clicked!')
return 'Click.'
@app.route("/create_link_token", methods=['POST'])
def create_link_token():
# Get the client_user_id by searching for the current user
request = LinkTokenCreateRequest(
products=products,
client_name="Budgetary",
country_codes=list(map(lambda x: CountryCode(x), PLAID_COUNTRY_CODES)),
language='en',
user=LinkTokenCreateRequestUser(
client_user_id=str(time.time())
)
)
if PLAID_REDIRECT_URI!=None:
request['redirect_uri']=PLAID_REDIRECT_URI
# create link token
response = client.link_token_create(request)
return jsonify(response.to_dict())
@app.route('/exchange_public_token', methods=['POST'])
def exchange_public_token():
global access_token
public_token = request.form['public_token']
request = ItemPublicTokenExchangeRequest(
public_token=public_token
)
response = client.item_public_token_exchange(request)
access_token = response['access_token']
item_id = response['item_id']
cursor = cnxn.execute('UPDATE Accounts Set API_ID = ? WHERE Id = ?', [access_token,1])
cursor.commit();
return jsonify(response.to_dict())
if __name__ == '__main__':
app.run(debug=True)
When the plaid link handler is called it spins and then goes away. I can't get the link dialog box to show completely to get access token. Setup using flask for the python server on port 5000 and using the plaid api for calls in python. Using javascript on the client side.
I can see the requests going through but nothing happens or seems to post to the client:
127.0.0.1 - - [05/Apr/2022 21:53:31] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Apr/2022 21:54:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Apr/2022 21:54:10] "POST /create_link_token HTTP/1.1" 200 -
Javascript:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="link-button">Link Account</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
<script type="text/javascript">
(async function($) {
var handler = Plaid.create({
// Create a new link_token to initialize Link
token: (await $.post('/create_link_token')).link_token,
receivedRedirectUri: window.location.href,
onLoad: function() {
// Optional, called when Link loads
},
onSuccess: function(public_token, metadata) {
// Send the public_token to your app server.
// The metadata object contains info about the institution the
// user selected and the account ID or IDs, if the
// Account Select view is enabled.
$.post('/exchange_public_token', {
public_token: public_token,
});
},
onExit: function(err, metadata) {
// The user exited the Link flow.
if (err != null) {
// The user encountered a Plaid API error prior to exiting.
}
// metadata contains information about the institution
// that the user selected and the most recent API request IDs.
// Storing this information can be helpful for support.
},
onEvent: function(eventName, metadata) {
// Optionally capture Link flow events, streamed through
// this callback as your users connect an Item to Plaid.
// For example:
// eventName = "TRANSITION_VIEW"
// metadata = {
// link_session_id: "123-abc",
// mfa_type: "questions",
// timestamp: "2017-09-14T14:42:19.350Z",
// view_name: "MFA",
// }
}
});
$('#link-button').on('click', function(e) {
handler.open();
});
})(jQuery);
</script>
</body>
</html>
Python server.py:
# source /Users/tnappy/node_projects/quickstart/python/bin/activate
# Read env vars from .env file
from plaid.exceptions import ApiException
from plaid.model.payment_amount import PaymentAmount
from plaid.model.payment_amount_currency import PaymentAmountCurrency
from plaid.model.products import Products
from plaid.model.country_code import CountryCode
from plaid.model.recipient_bacs_nullable import RecipientBACSNullable
from plaid.model.payment_initiation_address import PaymentInitiationAddress
from plaid.model.payment_initiation_recipient_create_request import PaymentInitiationRecipientCreateRequest
from plaid.model.payment_initiation_payment_create_request import PaymentInitiationPaymentCreateRequest
from plaid.model.payment_initiation_payment_get_request import PaymentInitiationPaymentGetRequest
from plaid.model.link_token_create_request_payment_initiation import LinkTokenCreateRequestPaymentInitiation
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.link_token_create_request import LinkTokenCreateRequest
from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
from plaid.model.asset_report_create_request import AssetReportCreateRequest
from plaid.model.asset_report_create_request_options import AssetReportCreateRequestOptions
from plaid.model.asset_report_user import AssetReportUser
from plaid.model.asset_report_get_request import AssetReportGetRequest
from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest
from plaid.model.auth_get_request import AuthGetRequest
from plaid.model.transactions_get_request import TransactionsGetRequest
from plaid.model.transactions_get_request_options import TransactionsGetRequestOptions
from plaid.model.identity_get_request import IdentityGetRequest
from plaid.model.investments_transactions_get_request_options import InvestmentsTransactionsGetRequestOptions
from plaid.model.investments_transactions_get_request import InvestmentsTransactionsGetRequest
from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest
from plaid.model.accounts_get_request import AccountsGetRequest
from plaid.model.investments_holdings_get_request import InvestmentsHoldingsGetRequest
from plaid.model.item_get_request import ItemGetRequest
from plaid.model.institutions_get_by_id_request import InstitutionsGetByIdRequest
from plaid.model.transfer_authorization_create_request import TransferAuthorizationCreateRequest
from plaid.model.transfer_create_request import TransferCreateRequest
from plaid.model.transfer_get_request import TransferGetRequest
from plaid.model.transfer_network import TransferNetwork
from plaid.model.transfer_type import TransferType
from plaid.model.transfer_user_in_request import TransferUserInRequest
from plaid.model.ach_class import ACHClass
from plaid.model.transfer_create_idempotency_key import TransferCreateIdempotencyKey
from plaid.model.transfer_user_address_in_request import TransferUserAddressInRequest
from plaid.api import plaid_api
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
from datetime import datetime
from datetime import timedelta
import plaid
import base64
import os
import datetime
import json
import time
from dotenv import load_dotenv
from werkzeug.wrappers import response
import pyodbc
load_dotenv()
app = Flask(__name__)
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=DESKTOP-DJCMSVC\MJBOURQUIN_SQL;"
"Database=MyBudget;"
"Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Accounts')
for row in cursor:
print('row = %r' % (row,))
vals = ("SOMETHING")
data = "UPDATE Accounts Set API_ID = 'SOMETHING' WHERE Id = 1"
cursor.execute(data)
cursor.commit();
access = "THAT THING"
cursor = cnxn.execute('UPDATE Accounts Set API_ID = ? WHERE Id = ?', [access,1])
cursor.commit();
# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
# Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')
# PLAID_PRODUCTS is a comma-separated list of products to use when initializing
# Link. Note that this list must contain 'assets' in order for the app to be
# able to create and retrieve asset reports.
PLAID_PRODUCTS = os.getenv('PLAID_PRODUCTS', 'transactions').split(',')
# PLAID_COUNTRY_CODES is a comma-separated list of countries for which users
# will be able to select institutions from.
PLAID_COUNTRY_CODES = os.getenv('PLAID_COUNTRY_CODES', 'US').split(',')
products = []
for product in PLAID_PRODUCTS:
products.append(Products(product))
def empty_to_none(field):
value = os.getenv(field)
if value is None or len(value) == 0:
return None
return value
host = plaid.Environment.Sandbox
if PLAID_ENV == 'sandbox':
host = plaid.Environment.Sandbox
if PLAID_ENV == 'development':
host = plaid.Environment.Development
if PLAID_ENV == 'production':
host = plaid.Environment.Production
# Parameters used for the OAuth redirect Link flow.
#
# Set PLAID_REDIRECT_URI to 'http://localhost:3000/'
# The OAuth redirect flow requires an endpoint on the developer's website
# that the bank website should redirect to. You will need to configure
# this redirect URI for your client ID through the Plaid developer dashboard
# at https://dashboard.plaid.com/team/api.
PLAID_REDIRECT_URI = empty_to_none('PLAID_REDIRECT_URI')
configuration = plaid.Configuration(
host=host,
api_key={
'clientId': PLAID_CLIENT_ID,
'secret': PLAID_SECRET,
'plaidVersion': '2020-09-14'
}
)
api_client = plaid.ApiClient(configuration)
client = plaid_api.PlaidApi(api_client)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/my-link/')
def my_link():
print ('I got clicked!')
return 'Click.'
@app.route("/create_link_token", methods=['POST'])
def create_link_token():
# Get the client_user_id by searching for the current user
request = LinkTokenCreateRequest(
products=products,
client_name="Budgetary",
country_codes=list(map(lambda x: CountryCode(x), PLAID_COUNTRY_CODES)),
language='en',
user=LinkTokenCreateRequestUser(
client_user_id=str(time.time())
)
)
if PLAID_REDIRECT_URI!=None:
request['redirect_uri']=PLAID_REDIRECT_URI
# create link token
response = client.link_token_create(request)
return jsonify(response.to_dict())
@app.route('/exchange_public_token', methods=['POST'])
def exchange_public_token():
global access_token
public_token = request.form['public_token']
request = ItemPublicTokenExchangeRequest(
public_token=public_token
)
response = client.item_public_token_exchange(request)
access_token = response['access_token']
item_id = response['item_id']
cursor = cnxn.execute('UPDATE Accounts Set API_ID = ? WHERE Id = ?', [access_token,1])
cursor.commit();
return jsonify(response.to_dict())
if __name__ == '__main__':
app.run(debug=True)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过将代码分成部分来解决。单击按钮,然后在Python中请求和打印值。然后发送并确保正确解析。然后,随着解析的代币价值成功开放链接。
Solved by breaking the code out into pieces. Clicking the button, then requesting and printing value in python. Then sending and making sure it's parsed correctly. Then with the parsed token value opening up link successfully.