Payumoney integration in react-native

China☆狼群 提交于 2021-01-29 10:24:34

问题


I am trying to integrating payumoney payment gateway in react-native but when I pressed "Pay" button I got an error "java.lang.double cannot be cast to java.lang.string" on the mobile screen.

I searched the whole google for the code but I got in node js as backend.

My JS file is like this:-

import * as React from 'react';
import { Image, ImageBackground, ScrollView, Animated, Text, StyleSheet, View, ListView, TextInput, ActivityIndicator, Alert, TouchableOpacity } from 'react-native';
import PayuMoney from 'react-native-payumoney';

export default class Consult_dr extends React.Component {

  constructor(props) {
    super(props);
    this.state = { 
      name:'',
      email:'',
      phone:'',
    };
    this._makePay = this._makePay.bind(this);
  }

   _makePay() {

    let amount = 300;
    let d = new Date();
    let txid = d.getTime();
    let productId = "Consulting";
    let name = this.state.name;
    let email = this.state.email;
    let phone = this.state.phone;
    let surl = "https://www.payumoney.com/mobileapp/payumoney/success.php"; 
    let furl = "https://www.payumoney.com/mobileapp/payumoney/failure.php";
    let id = "xxxxxx"; 
    let key = "xxxxxx"; 
    let sandbox = true; //Make sure to set false on production or you will get error

    fetch('https://athirst-desertions.000webhostapp.com/payu-hash.php', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            key: key,
            txnid: txid,
            amount: amount,
            productinfo: productId,
            firstname: name,
            email: email,
            phone: phone,
        }),
    })
    .then((response) => response.text())
    .then((hash) => {
      var test = hash.replace(/\"/g, "");
        let options = {
            amount: amount,
            txid: txid ,
            productId: productId,
            name: name,
            email: email,
            phone: phone,
            id: id,
            key: key,
            surl: surl,
            furl: furl,
            sandbox: sandbox,
            hash: test
        };
      console.log("this is then funciton====", options)
        PayuMoney.pay(options).then((d) => {
            console.log("payumoney===>",d);
        }).catch(e => {
            console.log(e);
        });
     })  
   }

  static navigationOptions = { title: 'Consult Doctor',};

  render() {

    return (
      <ScrollView>
      <ImageBackground source={require('../assets/bg.png')} style={styles.container} >

        <Image 
          source={require('../btnimage/consult_dr_header.jpg')} 
          style={{width:420, height:300, marginTop:20}} 
        />

        <View style={{marginTop:100, marginLeft:20, marginRight:20, marginBottom:200}}>


            <TextInput
              placeholder = "Descrbe your problem in detail"
              placeholderTextColor="white"
              onChangeText = {(TextInputText) => this.setState({name:TextInputText})} />

              <TextInput
              placeholder = "Descrbe your problem in detail"
              placeholderTextColor="white"
              style = {styles.textInput}
              onChangeText = {(TextInputText) => this.setState({email:TextInputText})} />

          <TextInput
            placeholder = "Descrbe your problem in detail"
            placeholderTextColor="white"
            style = {styles.textInput}
            onChangeText = {(TextInputText) => this.setState({phone:TextInputText})} />

          <TouchableOpacity style={styles.btnstyle}
            onPress={this._makePay}>
            <Text style={{textAlign: 'center', color: 'blue',}}> Submit </Text>
          </TouchableOpacity> 

        </View>
      </ImageBackground>
      </ScrollView>    
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: null,
    height: null,
  },
  textInput:{
    width: 300,
    color: 'white',
  },
});

My backend code like this:-

<?php 

$HostName = "localhost";
$DatabaseName = "xxxxxxxxxx";
$HostUser = "xxxxxxxxx";
$HostPass = "xxxxxxxxx";

$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

$obj = json_decode(file_get_contents('php://input'), true);

if(isset($obj["txnid"]))
{
    $merchant_key = "xxxxxx";
    $salt = "xxxxx";
    $txnid = $obj['txnid'];
    $amount = $obj['amount'];
    $productinfo = $obj['productinfo'];
    $firstname = $obj['firstname'];
    $email = $obj['email'];
    $phone = $obj['phone'];

    $query = "INSERT INTO `pay_table` ( txnid, amount, productinfo, firstname, email, phone ) VALUES ('$txnid', '$amount', '$productinfo', '$firstname', '$email', '$phone')";

    $hash = $merchant_key."|".$txnid."|".$amount."|".$productinfo."|".$firstname."|".$email."|".$phone."|".$salt;
    $hashkey = strtolower(hash('sha512', $hash));

    $result = $conn->query($query);

    if ($result == 1)
    {
        $data = $hashkey;
        //header('Content-type: application/json');

    }
    else
    {
        $data["message"] = "data not saved successfully";
        $data["status"] = "error";    
    }
}
else
{
    $data["message"] = "Format not supported";
    $data["status"] = "error";    
}
    echo json_encode($data);

?>

My response is like this:-

'this is then funciton====', { amount: 300,
txid: 1538136491771,
productId: 'Consulting',
name: 'All',
email: 'So',
phone: '335689',
id: 'xxxxxxx',
key: 'Xxxxxxx',
surl: 'https://www.payumoney.com/mobileapp/payumoney/success.php',
furl: 'https://www.payumoney.com/mobileapp/payumoney/failure.php',
sandbox: false,
hash: '4c9a9dfdfb909cf8f93cefb1f26c736f404b339c8e77d98a2f95f1af879c6a8c06c6f23352f39a180272d15c181b98c70bf1dff7009ef5a732c4ae7da5f9a0fa' }

回答1:


This might be late to the solution, but issue is related to your amount, amount should be 300.0 a double value.

Please try passing this

let options = {
    amount: 10.0,
    txid: "123123123" ,
    productId: "test",
    name: "Name",
    email: "test@gmail.com",
    phone: "8826343434",
    id: "393463",
    key: "LLKwG0",
    surl: "https://www.payumoney.com/mobileapp/payumoney/success.php",
    furl: "https://www.payumoney.com/mobileapp/payumoney/failure.php",
    sandbox: true,
    hash: "d829abecdaf9f2835787b3f56d1c7565721ca2501e6414438e61948dab435f102fc93213008cdfa3474691cadcc2dabdde64cd58c128dd2afcf3b389d617919c"
};
PayuMoney.pay(options).then((d) => {
    console.log(d); // WIll get a Success response with verification hash
}).catch(e => {
    console.log(e); //In case of failture
});

PHP Server Side Code:

<?php
echo makeHash("LLKwG0","123123123","10.0","test","Name","test@gmail.com");

function makeHash($key, $txnid, $amount, $productinfo, $firstname, $email){
    $salt = "qauKbEAJ";
    $payhash_str = $key . '|' . checkNull($txnid) . '|' . checkNull($amount) . '|' . checkNull($productinfo) . '|' . checkNull($firstname) . '|' . checkNull($email) . '|||||||||||' . $salt;
    $hash = strtolower(hash('sha512', $payhash_str));
    return $hash;
}

function checkNull($value)
{
    if ($value == null) {
        return '';
    } else {
        return $value;
    }
}
?>

Reference: Github issue link




回答2:


Alternate solution:

You need to configure PayUMoney in the browser and call that screen using WebView.

PS: I successfully implemented this.

Edited:

Steps:

  1. Include our custom PayUMoney component
    {PayUModalVisibility && (
            <PayUMoney
              visible={PayUModalVisibility}
              onCloseModal={() =>
                this.setState({PayUModalVisibility: false, billingData: []})
              }
              getMagicResponse={magicResponse =>
                this.getMagicResponse(magicResponse)
              }
              paymentOptions={onlineObj}
            />
          )}
  1. My getMagicResponse function
getMagicResponse(resp) {
console.log(resp);
    if (resp.status === 'success') {
        //do whatever u want
    }
  }

3.My PayUMoney component.

import React from 'react';
import {StyleSheet, View, Modal} from 'react-native';
import {Button, Text} from 'native-base';
import {WebView} from 'react-native-webview';

import styles from './styles';

class PayUMoney extends React.Component {
  constructor(props) {
    super(props);
    this.myWebView;
    this.state = {
      response: '',
    };
  }

  render() {
    const {
      visible,
      getMagicResponse,
      paymentOptions: {amount, productinfo, firstname, lastname, email, phone},
    } = this.props;
    const runFirst = `
            document.getElementById("amount").value = '${amount}';
            document.getElementById("firstname").value = '${firstname}';
            document.getElementById("lastname").value = '${lastname}';
            document.getElementById("email").value = '${email}';
            document.getElementById("phone").value = '${phone}';
            document.getElementById("productinfo").value = '${productinfo}';
            setTimeout(() => {
              document.forms.payuForm.submit();
            }, 200);
          `;

    return (
      <Modal
        animationType={'slide'}
        visible={visible}
        onRequestClose={() => {}}>
        <View style={styles.modalView}>
          <WebView
            ref={el => (this.myWebView = el)}
            startInLoadingState={true}
            useWebKit={false}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            scalesPageToFit={true}
            automaticallyAdjustContentInsets={true}
            injectedJavaScript={runFirst}
            onMessage={event => {
              let response_data = JSON.parse(event.nativeEvent.data);
              getMagicResponse(response_data);
            }}
            source={{
              uri: 'my_payuform_on_my_server.php',
            }}
          />
        </View>
      </Modal>
    );
  }
}

export default PayUMoney;
  1. configure my my_payuform_on_my_server.php using payumoney web sdk.
<?php

$MERCHANT_KEY = "XXXXXX";
$SALT = "YYYYYY";
// Merchant Key and Salt as provided by Payu.

// $PAYU_BASE_URL = "https://sandboxsecure.payu.in";        // For Sandbox Mode
$PAYU_BASE_URL = "https://secure.payu.in";      // For Production Mode

$action = '';

$posted = array();
if (!empty($_POST)) {
  //print_r($_POST);
  foreach ($_POST as $key => $value) {
    $posted[$key] = $value;
  }
}

$formError = 0;

if (empty($posted['txnid'])) {
  // Generate random transaction id
  $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
  $txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if (empty($posted['hash']) && sizeof($posted) > 0) {
  if (
    empty($posted['key'])
    || empty($posted['txnid'])
    || empty($posted['amount'])
    || empty($posted['firstname'])
    || empty($posted['email'])
    || empty($posted['phone'])
    || empty($posted['productinfo'])
    || empty($posted['surl'])
    || empty($posted['furl'])
    || empty($posted['service_provider'])
  ) {
    $formError = 1;
  } else {
    $hashVarsSeq = explode('|', $hashSequence);
    $hash_string = '';
    foreach ($hashVarsSeq as $hash_var) {
      $hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
      $hash_string .= '|';
    }

    $hash_string .= $SALT;

    $hash = strtolower(hash('sha512', $hash_string));
    $action = $PAYU_BASE_URL . '/_payment';
  }
} elseif (!empty($posted['hash'])) {
  $hash = $posted['hash'];
  $action = $PAYU_BASE_URL . '/_payment';
}
file_put_contents('logs.txt', date('Y-m-d H:i:s') . ' :payu_popup data:' . PHP_EOL . json_encode(array_map('utf8_encode', $posted)) . PHP_EOL . '---------------------' . PHP_EOL, FILE_APPEND);

?>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script>
    var hash = '<?php echo $hash ?>';

    function submitPayuForm() {
      if (hash == '') {
        return;
      }
      var payuForm = document.forms.payuForm;
      payuForm.submit();
    }
  </script>
</head>

<body onload="submitPayuForm()" style="display:none">
  <h2>PayU Form</h2>
  <br />
  <?php if ($formError) { ?>

    <span style="color:red">Please fill all mandatory fields.</span>
    <br />
    <br />
  <?php } ?>
  <form action="<?php echo $action; ?>" method="post" name="payuForm">
    <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
    <input type="hidden" name="hash" value="<?php echo $hash ?>" />
    <input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
    <table>
      <tr>
        <td><b>Mandatory Parameters</b></td>
      </tr>
      <tr>
        <td>Amount: </td>
        <td><input name="amount" id="amount" value="<?php echo (empty($posted['amount'])) ? '' : $posted['amount'] ?>" /></td>
        <td>First Name: </td>
        <td><input name="firstname" id="firstname" value="<?php echo (empty($posted['firstname'])) ? '' : $posted['firstname']; ?>" /></td>
      </tr>
      <tr>
        <td>Email: </td>
        <td><input name="email" id="email" value="<?php echo (empty($posted['email'])) ? '' : $posted['email']; ?>" /></td>
        <td>Phone: </td>
        <td><input name="phone" id="phone" value="<?php echo (empty($posted['phone'])) ? '' : $posted['phone']; ?>" /></td>
      </tr>
      <tr>
        <td>Product Info: </td>
        <td colspan="3"><textarea id="productinfo" name="productinfo"><?php echo (empty($posted['productinfo'])) ? '' : $posted['productinfo'] ?></textarea></td>
      </tr>
      <tr>
        <td>Success URI: </td>
        <td colspan="3"><input type="hidden" name="surl" value="my_success.php" size="64" /></td>
      </tr>
      <tr>
        <td>Failure URI: </td>
        <td colspan="3"><input type="hidden" name="furl" value="my_failure.php" size="64" /></td>
      </tr>

      <tr>
        <td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
      </tr>

      <tr>
        <td><b>Optional Parameters</b></td>
      </tr>
      <tr>
        <td>Last Name: </td>
        <td><input name="lastname" id="lastname" value="<?php echo (empty($posted['lastname'])) ? '' : $posted['lastname']; ?>" /></td>
        <td>Cancel URI: </td>
        <td><input name="curl" value="my_failure.php" /></td>
      </tr>
      <tr>
        <td>Address1: </td>
        <td><input name="address1" id="address1" value="<?php echo (empty($posted['address1'])) ? '' : $posted['address1']; ?>" /></td>
        <td>Address2: </td>
        <td><input name="address2" id="address2" value="<?php echo (empty($posted['address2'])) ? '' : $posted['address2']; ?>" /></td>
      </tr>
      <tr>
        <td>City: </td>
        <td><input name="city" id="city" value="<?php echo (empty($posted['city'])) ? '' : $posted['city']; ?>" /></td>
        <td>State: </td>
        <td><input name="state" id="state" value="<?php echo (empty($posted['state'])) ? '' : $posted['state']; ?>" /></td>
      </tr>
      <tr>
        <td>Country: </td>
        <td><input name="country" value="<?php echo (empty($posted['country'])) ? '' : $posted['country']; ?>" /></td>
        <td>Zipcode: </td>
        <td><input name="zipcode" value="<?php echo (empty($posted['zipcode'])) ? '' : $posted['zipcode']; ?>" /></td>
      </tr>
      <tr>
        <td>UDF1: </td>
        <td><input name="udf1" value="<?php echo (empty($posted['udf1'])) ? '' : $posted['udf1']; ?>" /></td>
        <td>UDF2: </td>
        <td><input name="udf2" value="<?php echo (empty($posted['udf2'])) ? '' : $posted['udf2']; ?>" /></td>
      </tr>
      <tr>
        <td>UDF3: </td>
        <td><input name="udf3" value="<?php echo (empty($posted['udf3'])) ? '' : $posted['udf3']; ?>" /></td>
        <td>UDF4: </td>
        <td><input name="udf4" value="<?php echo (empty($posted['udf4'])) ? '' : $posted['udf4']; ?>" /></td>
      </tr>
      <tr>
        <td>UDF5: </td>
        <td><input name="udf5" value="<?php echo (empty($posted['udf5'])) ? '' : $posted['udf5']; ?>" /></td>
        <td>PG: </td>
        <td><input name="pg" value="<?php echo (empty($posted['pg'])) ? '' : $posted['pg']; ?>" /></td>
      </tr>
      <tr>
        <?php if (!$hash) { ?>
          <td colspan="4"><input type="submit" value="Submit" /></td>
        <?php } ?>
      </tr>
    </table>
  </form>
</body>

</html>

  1. My my_success.php file (Same for my_failure.php)
<?php

$returnArray = [];
$returnArray['status'] = $_POST['status'];
$returnArray['txnid'] = $_POST['txnid'];
$returnArray['amount'] = $_POST['amount'];
$returnArray['firstname'] = $_POST['firstname'];
$returnArray['addedon'] = $_POST['addedon'];
$returnArray['productinfo'] = $_POST['productinfo'];
$returnArray['lastname'] = $_POST['lastname'];
$returnArray['email'] = $_POST['email'];
$returnArray['phone'] = $_POST['phone'];

$success_response = json_encode(array_map('utf8_encode', $returnArray));

?>

<script>
      var success_response = '<?php echo $success_response; ?>';
      window.ReactNativeWebView.postMessage(success_response);
</script>


来源:https://stackoverflow.com/questions/52556024/payumoney-integration-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!