2017-11-07 1 views
-2

다음 동작을 이해하는 데 어려움이 있습니다.스크립트 내에서 Python 함수를 직접 실행하는 경우와 Flask 응용 프로그램 컨트롤러에서 수행하는 경우

특정 모바일 결제 API를 통합하려고합니다. 결제 기능을 실행하면 결제 API가 호출되며 요청의 수신을 확인하는 응답을 반환하고 사용자의 휴대 전화에서 STKPush 화면을 실행 한 직후 API가 제공됩니다 (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 웹 응용 프로그램 컨트롤러에서 로직의 일부로 동일한 로직을 실행하면 적절한 응답이 반환되지만 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가 처리되지 않은 오류를 반환하는 것으로 나타났습니다. 지금은 괜찮아.

관련 문제