2017-11-07 2 views
-2

次の動作を理解するのは苦労しています。スクリプト内で直接Python関数を実行すると、Flaskアプリケーションコントローラ内から対話します。

私は特定のモバイルペイメントAPIを統合しています。支払機能を実行すると、支払APIが呼び出され、要求の受領を確認する応答を返し、ユーザーの携帯電話でSTKPush画面を放した直後に返信する必要があります(APIは、モバイル支払を扱う電気通信会社によって提供されます)。私は最初に単純なPythonスクリプトを書いて統合をテストし、うまく機能しました。以下は、私は、スクリプトでそれを実行しているかの抽出物である:

def get_oauth_token(): 
    resource_url = "https://xxxxxxxxxxx.co.ke/oauth/v1/generate?grant_type=client_credentials" 
    key = "#################" 
    secret = "################" 
    r = requests.get(resource_url, auth=HTTPBasicAuth(key, secret)) 
    return r.json()['access_token'] 


def lipa_online(token): 
    time = str(datetime.datetime.now()).split(".")[0].replace("-", "").replace(" ", "").replace(":", "") 
    password = "{0}{1}{2}".format("174379", "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919", time) 
    encoded = base64.b64encode(password) 
    payload = { 
     "BusinessShortCode": XXXXXX, 
     "Password": encoded, 
     "Timestamp": time, 
     "TransactionType": "PayOnline", 
     "Amount": 1, 
     "PartyA": 25470000000, 
     "PartyB": XXXXXX, 
     "PhoneNumber": 25470000000, 
     "CallBackURL": "https://97ff8c8c.ngrok.io/callback", 
     "AccountReference": "13dbd6hg", 
     "TransactionDesc": "Just a trial" 
    } 
    headers = {'Authorization': 'Bearer {0}'.format(token), 'Content-Type': "application/json"} 
    r = requests.post("https://xxxxxxxx.co.ke/pay/stkpush/v1/processrequest", headers=headers, json=payload) 
    print r.json() 

if __name__ == "__main__": 
    token = get_oauth_token() 
    #The line below fires the payment action. 
    request_id = pay_online(token) 

スクリプトを実行すると、直接支払いのAPIから適切な応答を返す:

{u'CustomerMessage': u'Success. Request accepted for processing', u'CheckoutRequestID': u'ws_CO_07112017182534915', u'ResponseDescription': u'Success. Request accepted for processing', u'MerchantRequestID': u'8955-555026-1', u'ResponseCode': u'0'} 

と火災に関するSTKpushアクションアップユーザーの電話(支払いAPIによって行われます)。

Flask Webアプリケーションコントローラのロジックの一部と同じロジックを実行すると、適切な応答が返されますが、STKPushアクションは実行されません。私は非同期タスクとしてセロリを実行してみましたが、私はまだ同じことを取得します。

@celery.task 
def lipa(token, payload): 
    headers = {'Authorization': 'Bearer {0}'.format(token), 'Content-Type': "application/json"} 
    saf_url = "https://xxxxxxxxxx.co.ke/pay/stkpush/v1/processrequest" 
    r = requests.post(saf_url, headers=headers, json=payload) 
    print r.json() 


@api.route('/payment/pay/', methods=['POST']) 
def make_payment(): 
    if not 'Authorization' in request.headers: 
     abort(401) 
    _data = request.headers['Authorization'].encode('ascii', 'ignore') 
    token = str.replace(str(_data), 'Bearer ', '') 
    if token == application.config['PAYMENT_API_KEY']: 
     pass 
    else: 
     return jsonify({"error": "Invalid authentication token."}) 

    time = str(datetime.datetime.now()).split(".")[0].replace("-", "").replace(" ", "").replace(":", "") 
    password = "{0}{1}{2}".format(str(application.config.get('SHORTCODE')), application.config.get('PASSCODE'), time) 
    encoded = base64.b64encode(password) 
    data = request.get_json(force=True) 
    try: 
     if data["sandbox"] == "true": 
      amount = 1 
     else: 
      amount = data.get('amount') 
    except KeyError: 
     amount = data.get('amount') 
    callback_url = "{0}/api/payment/mpesa/callback".format(application.config.get('SITE')) 
    payload = { 
     "BusinessShortCode": application.config.get('SHORTCODE'), 
     "Password": encoded, 
     "Timestamp": time, 
     "TransactionType": "PayOnline", 
     "Amount": amount, 
     "PartyA": data.get('phone_number'), 
     "PartyB": application.config.get('SHORTCODE'), 
     "PhoneNumber": data.get('phone_number'), 
     "CallBackURL": callback_url, 
     "AccountReference": str(uuid.uuid4()), 
     "TransactionDesc": data.get('description') 
    } 
    token = str(get_oauth_token()) 
    task = lipa.apply_async(args=[token, payload]) 
    return Response() 

何がこの動作の違いを引き起こす可能性がありますか?

ありがとうございます。

答えて

0

APIは、処理されなかったエラーを返していました。今は大丈夫です。

関連する問題