Error while making payments using Mollie API in php - php

I am making payments using mollie API in php. But its giving me some errors . I have posted my code and screenshot of the errors.
THIS IS MY CODE:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
try {
require_once "vendor/autoload.php";
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey("test_XXXX");
$orderId = time();
$amount = $_POST['amount'];
$payment = $mollie->payments->create([
"amount" => [
"currency" => "EUR",
"value" => "$amount", // You must send the correct number of decimals, thus we enforce the use of strings
],
"description" => "Order #{$orderId}",
"redirectUrl" => "https://example.com/Mollie/return/".$orderId."/",
"webhookUrl" => "https://example.com/Mollie/webhook/",
"metadata" => [
"order_id" => $orderId,
],
]);
print_r($payment);
$payment_data = array(
'payment_id' => $payment->id,
'user_id' => $_POST['user_id'],
'order_id' => $orderId,
'mode' => $payment->mode,
'description' => $payment->description,
'status' => $payment->status,
'added_date' => date('Y-m-d'),
'added_time' => date('H:i:s')
);
print_r($payment_data);
header("Location: " . $payment->getCheckoutUrl(), true, 303);
} catch (\Mollie\Api\Exceptions\ApiException $e) {
echo "API call failed: ". htmlspecialchars($e->getMessage());
}
THE SCREENSHOT:
The first image shows "Uncaught SyntaxError: Unexpected token M in JSON at position 0" in RED color.
The second image is the warning I am getting
First image
Second Image

Related

PHP JSON Stripe Text string variable leading to parsing error

Trying to setup Stripe for a client.
In the following code, when I use the term ('Formal Trousers') directly in the code, it works perfectly fine.
However, when I try to use a variable (like, $aname='Formal Trousers';), it is throwing a parsing error (PHP Parse error: syntax error, unexpected end of file in /home/folder1/file1.php). Line no. reported in error is the last line of the PHP file (where we have ?>).
The code that works (see last line of the code where I have ( 'metadata' => ['item_name' => 'Formal Trousers','item_no' => '31'],):
// Set API key
\Stripe\Stripe::setApiKey(STRIPE_API_KEY);
$response = array(
'status' => 0,
'error' => array(
'message' => 'Invalid Request!'
)
);
$aname='Formal Trousers';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$input = file_get_contents('php://input');
$request = json_decode($input);
}
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode($response);
exit;
}
if(!empty($request->createCheckoutSession)){
// Convert product price to cent
$stripeAmount = round($productPrice*100, 2);
// Create new Checkout Session for the order
try {
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'metadata' => ['item_name' => 'Formal Trousers','item_no' => '31'],
Now, instead of a static item name as 'Formal Trousers', I want to use a PHP variable ($aname - like below)
The code that DOES NOT works with a variable (see last line of the code where I have ( 'metadata' => ['item_name' => '<?php echo $aname ?>','item_no' => '31'],):
// Set API key
\Stripe\Stripe::setApiKey(STRIPE_API_KEY);
$response = array(
'status' => 0,
'error' => array(
'message' => 'Invalid Request!'
)
);
$aname='Formal Trousers';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$input = file_get_contents('php://input');
$request = json_decode($input);
}
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode($response);
exit;
}
if(!empty($request->createCheckoutSession)){
// Convert product price to cent
$stripeAmount = round($productPrice*100, 2);
// Create new Checkout Session for the order
try {
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'metadata' => ['item_name' => '<?php echo $aname ?>','item_no' => '31'],
Also, tried only $aname (since it is all PHP code) as follows, but all those are failing:
'metadata' => ['item_name' => '$aname','item_no' => '31'],
'metadata' => ['item_name' => "$aname",'item_no' => '31'],
'metadata' => ['item_name' => $aname,'item_no' => '31'],
Any idea how to use a variable in the above case?
I think you're getting "unexpected end of file" because of the '?>' in this line:
'metadata' => ['item_name' => '<?php echo $aname ?>','item_no' => '31'],
the compiler thinks you are leaving PHP mode and going back to plain text output. everything after that is simply output to the buffer instead of being run as PHP.
the correct line is:
'metadata' => ['item_name' => $aname, 'item_no' => '31'],

Payment API Returns AuthenticationFailed Error

I am integrating payments to my app and using PHP-Payments-SDK from Intuit
When creating echeck debit by the following code.
public function echeck(Request $request){
$this->refreshToken();
$record = QuickbookModel::first();
$client = new PaymentClient([
'access_token' => $record->accessToken,
'environment' => "sandbox" // or 'environment' => "production"
]);
$array = [
"bankAccount" => [
"phone" => $request->phone,
"routingNumber" => $request->routingNumber,
"name" => $request->name,
"accountType" => $request->accountType,
"accountNumber" => $request->accountNumber
],
"description" => "Easyfi Testing",
"paymentMode" => "WEB",
"amount" => "5.55",
];
$bank = ECheckOperations::buildFrom($array);
$response = $client->debit($bank);
if($response->failed()){
$code = $response->getStatusCode();
$errorMessage = $response->getBody();
return json_encode(["status" => $code, "message" => $errorMessage]);
}else{
$responseCharge = $response->getBody();
//Get the Id of the charge request
$id = $responseCharge->id;
//Get the Status of the charge request
$status = $responseCharge->status;
return json_encode(["status" => $status, "message" => $responseCharge, "data" => $id]);
}
}
I always getting following error even everything is up to mark including Access Token
{status: 401, message: "{"code":"AuthenticationFailed","type":"INPUT","message":null,"detail":null,"moreInfo":null}"}

How to process a refund with Omnipay - NAB Transact

I am trying to do the refund process and it is connected to the nab test mode server but not processing the refund transaction.
I did a transaction yesterday and wanted to refund the part money but it is not going through and shows the error that Credit card details not available (Error Code 133).
I am sending the request using TransactionID and TransactionReference and the amount to be deducted but not working.
My code:-
public function pay()
{
$gateway = Omnipay::create('NABTransact_SecureXML');
$gateway->setMerchantId('XYZ0010');
$gateway->setTransactionPassword('abcd1234');
$gateway->setTestMode(true);
$card = new CreditCard([
'firstName' => 'ABC',
'lastName' => 'DEF',
'number' => '4444333322221111',
'expiryMonth' => '05',
'expiryYear' => '2025',
'cvv' => '123',
]
);
$transaction = $gateway->purchase([
'amount' => '5000.00',
'currency' => 'AUD',
'transactionId' => '100321', // (My order ID)
'card' => $card,
]
);
$response = $transaction->send();
}
The transactionID i got here is: 706256
please view the screenshot for the above transaction in the NAB:
public function refund()
{
$gateway = Omnipay::create('NABTransact_SecureXML');
$gateway->setMerchantId('XYZ0010');
$gateway->setTransactionPassword('abcd1234');
$gateway->setTestMode(true);
$card = ([
'firstName' => 'ABC',
'lastName' => 'DEF',
'number' => '4444333322221111',
'expiryMonth' => '05',
'expiryYear' => '2025',
'cvv' => '123',
]
);
$refund = $gateway->refund([
'transactionReference' => "706256",
'amount' => "5.00",
'currency' => "AUD",
'transactionId' => "100321",
'messageID' => '4',
'card' => $card,
]);
$refund->send();
}
please view the screenshot for the above transaction in the NAB when
trying to refund:
yes, i had solved it.
this is the sample of my code:
$gateway = Omnipay::create('NABTransact_SecureXML');
gateway->setMerchantId('_ID_');
$gateway->setTransactionPassword('_PASSWORD_');
$gateway->setTestMode(false);
$refund = $gateway->refund([
'transactionReference' => "12345",
'amount' => "500",
'transactionId' => 765897, (hope u must have saved this number in DB)
]);
$response = $refund->send();
$message = $response->getMessage();
if ($response->isSuccessful()) {
return "I m Happy"
} else {
return back()->with('amountError', $message);
}
Let me know how did it go :)

How to integrate eway payment gateway to a php website?

Does anyone know how to integrate eway payment gateway to a normal php website ?
I have conected but it is showing the error when I am writing the code in this link :https://www.eway.com.au/developers/sdk/php
Its showing the error which is given below :
Error: eWAY library has encountered a problem connecting to Rapid
<?php
require_once 'lib/eway-rapid-php-master/include_eway.php';
// eWAY Credentials
$apiKey = 'F9802AS8MHb/rAm6UyRbT2d5eHjOZWhff++jtFOtMU';
$apiPassword = 'V6E';
$apiEndpoint = 'Sandbox';
// Create the eWAY Client
$client = \Eway\Rapid::createClient($apiKey, $apiPassword, $apiEndpoint);
// Transaction details - these would usually come from the application
$transaction = [
'Customer' => [
'FirstName' => 'John',
'LastName' => 'Smith',
'Street1' => 'Level 5',
'Street2' => '369 Queen Street',
'City' => 'Sydney',
'State' => 'NSW',
'PostalCode' => '2000',
'Country' => 'au',
'Email' => 'demo#example.org',
],
// These should be set to your actual website (on HTTPS of course)
'RedirectUrl' => "http://$_SERVER[HTTP_HOST]" . dirname($_SERVER['REQUEST_URI']) . '/response.php',
'CancelUrl' => "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
'TransactionType' => \Eway\Rapid\Enum\TransactionType::PURCHASE,
'Payment' => [
'TotalAmount' => 1000,
]
];
// Submit data to eWAY to get a Shared Page URL
$response = $client->createTransaction(\Eway\Rapid\Enum\ApiMethod::RESPONSIVE_SHARED, $transaction);
// Check for any errors
if (!$response->getErrors()) {
$sharedURL = $response->SharedPaymentUrl;
} else {
foreach ($response->getErrors() as $error) {
echo "Error: ".\Eway\Rapid::getMessage($error)."<br>";
}
die();
}
echo 'Pay with our secure payment page';
?>
I have written the code as shown above.
I realize you've sorted it by now or given up Lena but please find code is like below
$apiEndpoint = '\Eway\Rapid\Client::MODE_SANDBOX';

Bad Request in QuickBooks API production, works in sandbox

Today I tried to switch over development code to a limited-release production environment and immediately ran into issues.
The QuickBooks Accounting API works fine, however when it comes to payments I am able to accept them in sandbox mode but production returns "400 Bad Request"
I'm using my production API keys, I'm accessing the production API endpoints (api.intuit.com as opposed to sandbox.api.intuit.com), and I know the query I'm sending should be fine since it works in sandbox mode (unique Request-Id, amount, token, and currency provided in request body, proper content-type header, etc)
I also know my API key is fine since it works with the QuickBooks Accounting API. I am able to create a customer and create an invoice, but when I attempt to collect payment on the invoice it throws up on me.
What could be going wrong? I can post any code snippets or errors required. I'm using Laravel 5.2 with a phpOauthLib wrapper written by lusitanian.
The code I'm using:
$oauth = OAuth::consumer('QuickBooks');
$oauth_token = unserialize(file_get_contents(storage_path("tokens/oauth.token")));
$storage = $oauth->getStorage();
$storage->storeAccessToken('QuickBooks', $oauth_token['access_token']);
$member = Member::find(Request::get('id'));
$query = urlencode("select * from customer where displayname = '" . $member->first_name . " " . $member->last_name . "'");
$result = json_decode($oauth->request("/v3/company/" . $oauth_token['company_id'] . "/query?query=" . $query, "GET"));
$donor = null;
if( !property_exists( $result->QueryResponse, 'Customer' ) ) {
$donor = $oauth->request("/v3/company/" . $oauth_token['company_id'] . "/customer", "POST", json_encode([
'DisplayName' => $member->first_name . " " . $member->last_name
]), array('Content-Type' => 'application/json'));
} else {
$donor = $result->QueryResponse->Customer[0];
}
$pledge = $oauth->request("/v3/company/" . $oauth_token['company_id'] . "/invoice", "POST", json_encode([
'Line' => [
[
'Amount' => '25.00',
'DetailType' => 'SalesItemLineDetail',
'SalesItemLineDetail' => [
'ItemRef' => [
'value' => '21'
]
]
]
],
'CustomerRef' => [
'value' => $donor->Id
]
]), array('Content-Type' => 'application/json'));
$pledge = json_decode( $pledge )->Invoice;
$guid = GUID();
/************** THIS IS THE LINE THAT FAILS: ***************/
$capture = $oauth->request("https://api.intuit.com/quickbooks/v4/payments/charges", "POST", json_encode([
'amount' => $amount,
'token' => Request::get('token'),
'currency' => "USD"
]), ['Content-Type' => 'application/json', 'Request-Id' => $guid]);
$capture = json_decode( $capture );
$payment = $oauth->request("/v3/company/" . $oauth_token['company_id'] . "/payment", "POST", json_encode([
'CustomerRef' => [
'value' => $donor->Id,
'name' => $donor->DisplayName
],
'TotalAmt' => $capture->amount,
'Line' => [
[
'Amount' => $capture->amount,
'LinkedTxn' => [
[
'TxnId' => $pledge->Id,
'TxnType' => 'Invoice'
]
]
]
]
]), ['Content-Type' => 'application/json']);
Again, this code worked perfectly with the sandbox API, but now it fails. Tonight I'll see what I can do to get the HTTP transaction (request and response)

Categories