Django: чтение параметров из запроса POST - PullRequest
0 голосов
/ 22 февраля 2020

Я добавляю систему регулярных платежей, используя платежный шлюз (безналичный платежный шлюз), к веб-сайту, который я разрабатываю. После обработки платежа платежный шлюз перенаправляет на мой URL-адрес wesbite с некоторыми параметрами с запросом POST как , приведенным здесь . Я не могу прочитать эти параметры. Это мой первый проект по веб-разработке, и я немного запутался здесь. В документации упоминалось, что это был запрос POST, но в бэкэнде request.method дает метод GET. Я использую приведенный ниже код

@csrf_exempt
@login_required
def cashfree_response(request):
    if request.method == "POST":
        print('inside post method')
    if request.method == "GET":
        print('inside get method')
        sub_ref = request.GET['cf_subReferenceId']

Как прочитать cf_subReferenceId значение параметра и другие значения параметра, переданные платежным шлюзом? Я также попытался использовать sub_ref = request.GET.get('cf_subReferenceId'), но он вернул None. Как прочитать эти параметры и как проверить, отправляет ли платежный шлюз какие-либо параметры?

Обновление:

Я связался с безналичным платежным шлюзом, и они ответили, что это запрос POST. Но когда я print(request.method) это показывает как GET. Они прислали мне пару PHP файлов, но я не знаю PHP. Ниже приведены файлы PHP, которые мне прислали. Может кто-нибудь помочь мне определить, что такое метод возврата и как читать возвращаемые параметры?

<?php  
     $secretkey = "60e9cfebec82c9693d9423011fc2898766119d1c";
     $cf_subReferenceId = $_POST["cf_subReferenceId"];
     $cf_subscriptionId = $_POST["cf_subscriptionId"];
     $cf_authAmount = $_POST["cf_authAmount"];
     $cf_orderId = $_POST["cf_orderId"];
     $cf_referenceId = $_POST["cf_referenceId"];
     $cf_status = $_POST["cf_status"];
     $cf_message = $_POST["cf_message"];
     $signature = $_POST["signature"];
     $data = "";
     $postData = $_POST;
     ksort($postData);
     foreach ($postData as $key => $value) {
     if (substr($key, 0, 3) == "cf_") {
     $data .= $key . $value;
}
 }
 //echo($data);
         //die();
         $hash_hmac = hash_hmac('sha256', $data, $secretkey, true) ;
         $computedSignature = base64_encode($hash_hmac);
         if ($signature == $computedSignature) {
         print_r("yes");
         }else{
         print_r("no");
         }
?>

и

<!DOCTYPE html>
<html>
<head>
    <title>Cashfree - PG Response Details</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <h1 align="center">PG Response</h1> 

    <?php  
         $secretkey = "60e9cfebec82c9693d9423011fc2898766119d1c";
         $cf_subReferenceId = $_POST["cf_subReferenceId"];
         $cf_subscriptionId = $_POST["cf_subscriptionId"];
         $cf_authAmount = $_POST["cf_authAmount"];
         $cf_orderId = $_POST["cf_orderId"];
         $cf_referenceId = $_POST["cf_referenceId"];
         $cf_status = $_POST["cf_status"];
         $cf_message = $_POST["cf_message"];
         $signature = $_POST["signature"];
         $data = "";
         $postData = $_POST;
         ksort($postData);
         foreach ($postData as $key => $value) {
         if (substr($key, 0, 3) == "cf_") {
         $data .= $key . $value;
}
 }
 //echo($data);
         //die();
         $hash_hmac = hash_hmac('sha256', $data, $secretkey, true) ;
         $computedSignature = base64_encode($hash_hmac);
         if ($signature == $computedSignature) {
     ?>
    <div class="container"> 
    <div class="panel panel-success">
      <div class="panel-heading">Signature Verification Successful</div>
      <div class="panel-body">
        <!-- <div class="container"> -->
            <table class="table table-hover">
                <tbody>
                  <tr>
                    <td>cf_subReferenceId</td>
                    <td><?php echo $cf_subReferenceId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_subscriptionId</td>
                    <td><?php echo $cf_subscriptionId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_authAmount</td>
                    <td><?php echo $cf_authAmount; ?></td>
                  </tr>
                  <tr>
                    <td>cf_orderId</td>
                    <td><?php echo $cf_orderId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_referenceId </td>
                    <td><?php echo $cf_referenceId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_status</td>
                    <td><?php echo $cf_status; ?></td>
                  </tr>
                  <tr>
                    <td>cf_message</td>
                    <td><?php echo $cf_message; ?></td>
                  </tr>
                </tbody>
            </table>
        <!-- </div> -->

       </div>
    </div>
    </div>
     <?php   
        } else {

     ?>
    <div class="container"> 
    <div class="panel panel-danger">
      <div class="panel-heading">Signature Verification failed</div>
      <div class="panel-body">
        <!-- <div class="container"> -->
            <table class="table table-hover">
                <tbody>
                  <tr>
                    <td>cf_subReferenceId</td>
                    <td><?php echo $cf_subReferenceId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_subscriptionId</td>
                    <td><?php echo $cf_subscriptionId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_authAmount</td>
                    <td><?php echo $cf_authAmount; ?></td>
                  </tr>
                  <tr>
                    <td>cf_orderId</td>
                    <td><?php echo $cf_orderId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_referenceId </td>
                    <td><?php echo $cf_referenceId; ?></td>
                  </tr>
                  <tr>
                    <td>cf_status</td>
                    <td><?php echo $cf_status; ?></td>
                  </tr>
                  <tr>
                    <td>cf_message</td>
                    <td><?php echo $cf_message; ?></td>
                  </tr>
                </tbody>
            </table>
        <!-- </div> -->
      </div>    
    </div>  
    </div>

    <?php   
        }
     ?>

</body>
</html>

После установки debug-toolbar он показывает, что аргументы не переданы enter image description here

enter image description here

В views.py создать план и подписку и отправить пользователя на authlink. Это создает план и подписку, и я был перенаправлен на authlink, где я смог ввести данные карты и авторизоваться. Так как это был тестовый режим, я выбрал успех, а затем вернулся к URL, который дал. Здесь я не указал никаких параметров.

@login_required
def payment_process(request):
    if request.method == "POST":
        Sub_value =  int(request.POST.get('sub_value'))
        creator =  request.POST.get('creator')
        url = "https://test.cashfree.com/api/v2/subscription-plans"
        appID = settings.CASHFREEID
        secretKey = settings.CASHFREESECRETKEY
        headers = {
            'cache-control': 'no-cache',
            'content-type': 'application/json',
            'X-Client-Id': appID,
            'X-Client-Secret': secretKey,
        }
        data = {"planId":"plan_1", "planName":"Booster","type":"PERIODIC","amount":Sub_value,"intervalType":"week","intervals":2,"description":"This is the standard planfor our services"}
        data=json.dumps(data)
        response = requests.post('https://test.cashfree.com/api/v2/subscription-plans', headers=headers, data=data)
        response_text = json.loads(response.text)
        if not response_text['status'] == 'OK':
            # redirect to a page to tell the user to try again later!!
            pass

        data = {"subscriptionId":"sub1", "planId":plan_id, "amount":Sub_value, "customerEmail":request.user.email,"customerPhone":"7427259375","expiresOn":"2030-12-31 23:59:59","returnUrl":"http://127.0.0.1:8000/cashfreeresponse/"}
        data=json.dumps(data)
        response = requests.post('https://test.cashfree.com/api/v2/subscriptions', headers=headers, data=data)
        response_text = json.loads(response.text)

        if not response_text['status'] == 'OK':
            # redirect to a page to tell the user to try again later!!
            pass

        return redirect(response_text['authLink'])

1 Ответ

0 голосов
/ 04 марта 2020

Как указано в комментариях, перенаправления обычно выполняются с помощью методов GET из браузера.

Для получения параметров GET в Django вы можете проверить это решение .

С другой стороны, как показано в этом видео Cashfree , вы можете выполнить отладку на вкладке «Сеть» вашего обзора, проверить опцию сохранения журнала, сделать запрос и проверить значения заголовков.

...