php 如何实现'Upwork' REST API的回调URL?

fnvucqvd  于 2023-03-21  发布在  PHP
关注(0)|答案(1)|浏览(154)

要能够运行此代码(从www.example.com搜索工作upwork.com):

#!/usr/bin/env python

import upwork
from upwork.routers.jobs import search

# https://developers.upwork.com/?lang=python#authentication_authorization-request
# https://www.upwork.com/developer/keys/apply
config = upwork.Config(
        {
            "client_id": <my_client_id>,
            "client_secret": <my_client_secret>,
            "redirect_uri": <my_redirect_uri>
        }
    )

client = upwork.Client(config)

try:
    config.token
except AttributeError:
    authorization_url, state = client.get_authorization_url()
    # cover "state" flow if needed
    authz_code = input(
        "Please enter the full callback URL you get "
        "following this link:\n{0}\n\n> ".format(authorization_url)
    )

    print("Retrieving access and refresh tokens.... ")
    token = client.get_access_token(authz_code)

params = {'q': 'php', 'title': 'Web developer'}
search.Api(client).find(params)

我需要定义一个 * 回调URL*。
我如何实现它?
有人有phppython脚本吗?
如何从回调(服务器端)获取(客户端)API返回的值?或者您需要在本地主机上提供Web服务?我无法在本地主机上托管Web服务,因为我无法在网络上转发到我的私有IP

**看起来刮站点比API容易:/**你觉得呢?

rkkpypqq

rkkpypqq1#

我认为你可以通过使用你的实际回调URL来改变你的redirect_uri配置来实现这一点。我对php不是很熟悉,但是用flask实现回调URL怎么样?
最小化的设置应该像

from flask import Flask, request
import upwork

app = Flask(__name__)

client_id = "<my_client_id>"
client_secret = "<my_client_secret>"
redirect_uri = "<my_redirect_uri>"

config = upwork.Config(
    {
        "client_id": client_id,
        "client_secret": client_secret,
        "redirect_uri": redirect_uri
    }
)

@app.route('/callback')
def callback():
    # Get the authorization code from the request
    auth_code = request.args.get('code')
    client = upwork.Client(config)
    token = client.get_access_token(auth_code)
    return f"Access token: {token.access_token}\nRefresh token: {token.refresh_token}"

if __name__ == '__main__':
    app.run()

你可以通过运行flask服务器在本地机器上测试它,在你获得授权后,Upwork客户端将被称为你的redirect_uri(在这里它可以被导航到http://127.0.0.1:5000/callback url),并将调用callback()方法。
如果您想从回调URL获取返回的响应,可以使用requests库获取它,如

import requests

response = requests.get("http://127.0.0.1:5000/callback")
if response.status_code != 200:
   response.raise_for_status()
else:
   access_token, refresh_token = response.text.strip().split('\n')
   print(f"Access token: {access_token}\n Refresh token: {refresh_token}"

请记住,您需要根据您的情况和您自己的服务器端端点的结构以及您设置Upwork配置的方式来修改此代码。

相关问题