get() public static méthode

Shows details for a payment, by ID.
public static get ( string $paymentId, ApiContext $apiContext = null, PayPalRestCall $restCall = null ) : Payment
$paymentId string
$apiContext PayPal\Rest\ApiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials.
$restCall PayPalRestCall is the Rest Call Service that is used to make rest calls
Résultat Payment
 public function getPaymentStatus()
 {
     // Get the payment ID before session clear
     $payment_id = Session::get('paypal_payment_id');
     // clear the session payment ID
     Session::forget('paypal_payment_id');
     if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
         return Redirect::route('original.route')->with('error', 'Payment failed');
     }
     $payment = Payment::get($payment_id, $this->_api_context);
     // PaymentExecution object includes information necessary
     // to execute a PayPal account payment.
     // The payer_id is added to the request query parameters
     // when the user is redirected from paypal back to your site
     $execution = new PaymentExecution();
     $execution->setPayerId(Input::get('PayerID'));
     //Execute the payment
     $result = $payment->execute($execution, $this->_api_context);
     echo '<pre>';
     print_r($result);
     echo '</pre>';
     exit;
     // DEBUG RESULT, remove it later
     if ($result->getState() == 'approved') {
         // payment made
         return Redirect::route('original.route')->with('success', 'Payment success');
     }
     return Redirect::route('original.route')->with('error', 'Payment failed');
 }
Exemple #2
0
 public function processResult($data)
 {
     $paymentId = ArrayHelper::getValue($data, 'paymentId');
     if (!$paymentId) {
         throw new BadRequestHttpException('Missing payment id');
     }
     $payerId = ArrayHelper::getValue($data, 'PayerID');
     if (!$payerId) {
         throw new BadRequestHttpException('Missing payer id');
     }
     $payment = Payment::get($paymentId, $this->getContext());
     $event = new GatewayEvent(['gatewayData' => $data, 'payment' => $payment]);
     $this->trigger(GatewayEvent::EVENT_PAYMENT_REQUEST, $event);
     if (!$event->handled) {
         throw new ServerErrorHttpException('Error processing request');
     }
     $transaction = \Yii::$app->getDb()->beginTransaction();
     try {
         $paymentExecution = new PaymentExecution();
         $paymentExecution->setPayerId($payerId);
         $event->payment = $payment->execute($paymentExecution, $this->getContext());
         $this->trigger(GatewayEvent::EVENT_PAYMENT_SUCCESS, $event);
         $transaction->commit();
     } catch (\Exception $e) {
         $transaction->rollback();
         \Yii::error('Payment processing error: ' . $e->getMessage(), 'PayPal');
         throw new ServerErrorHttpException('Error processing request');
     }
     return true;
 }
 /**
  * @param PaymentInterface $payment
  * @throws InvalidPaymentException
  */
 public function check(PaymentInterface $payment)
 {
     if ($payment->getTransaction()) {
         throw new InvalidPaymentException('Payment has already been received.');
     }
     $credentials = new OAuthTokenCredential($this->options['client_id'], $this->options['secret']);
     $apiContext = new ApiContext($credentials);
     $apiContext->setConfig(['mode' => $this->options['mode']]);
     $paypalPayment = Payment::get($payment->getExtraData('paypal_payment_id'), $apiContext);
     $payer = $paypalPayment->getPayer();
     if (!$payer || 'verified' !== strtolower($payer->getStatus())) {
         throw new InvalidPaymentException('Payer not verified.');
     }
     if ('created' == $paypalPayment->getState()) {
         $execution = new PaymentExecution();
         $execution->setPayerId($paypalPayment->getPayer()->getPayerInfo()->getPayerId());
         $paypalPayment->execute($execution, $apiContext);
     }
     if ('approved' != $paypalPayment->getState()) {
         throw new InvalidPaymentException('Invalid payment state.');
     }
     $math = new NativeMath();
     $controlSum = 0;
     foreach ($paypalPayment->getTransactions() as $transaction) {
         if ($transaction->getAmount()->getCurrency() != $payment->getAccount()->getCurrency()) {
             throw new InvalidPaymentException('Invalid payment currency.');
         }
         $controlSum = $math->sum($controlSum, $transaction->getAmount()->getTotal());
     }
     if (!$math->eq($payment->getPaymentSum(), $controlSum)) {
         throw new InvalidPaymentException('Invalid payment sum.');
     }
 }
 public function ExecutePayment($paymentId = 0, $payerId = 0)
 {
     $apiContext = $this->getApiContext();
     try {
         $payment = Payment::get($paymentId, $apiContext);
     } catch (Exception $ex) {
         $this->error = $ex->getMessage();
         return false;
     }
     $dataP = json_decode($payment->toJSON());
     if ($dataP->payer->payer_info->payer_id != $payerId) {
         $this->error = 'Los datos son inválidos';
         return false;
     }
     if ($dataP->state == 'approved') {
         $this->error = 'El pedido ya fue pagado';
         return false;
     }
     if (!$dataP->state == 'created') {
         $this->error = 'El pedido no ya fue aprobado';
         return false;
     }
     try {
         $paymentExecution = new PaymentExecution();
         $paymentExecution->setPayerId($payerId);
         $payment = $payment->execute($paymentExecution, $apiContext);
     } catch (Exception $ex) {
         $this->error = $ex->getMessage();
         return false;
     }
     return $payment->toJSON();
 }
 /**
  * @depends testCreate
  * @param $payment Payment
  * @return Payment
  */
 public function testGet($payment)
 {
     $result = Payment::get($payment->getId(), $this->apiContext, $this->mockPayPalRestCall);
     $this->assertNotNull($result);
     $this->assertEquals($payment->getId(), $result->getId());
     return $result;
 }
Exemple #6
0
 /**
  * {@inheritDoc}
  */
 public function execute($request)
 {
     /** @var $request Sync */
     RequestNotSupportedException::assertSupports($this, $request);
     /** @var Payment $model */
     $model = $request->getModel();
     $payment = Payment::get($model->id);
     $model->fromArray($payment->toArray());
 }
Exemple #7
0
 public function testOperations()
 {
     $p1 = $this->payments['new'];
     $p1->create();
     $this->assertNotNull($p1->getId());
     $p2 = Payment::get($p1->getId());
     $this->assertNotNull($p2);
     $paymentHistory = Payment::all(array('count' => '10'));
     $this->assertNotNull($paymentHistory);
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 public function execute($request)
 {
     /** @var $request \Payum\Core\Request\Sync */
     if (false == $this->supports($request)) {
         throw RequestNotSupportedException::createActionNotSupported($this, $request);
     }
     /** @var Payment $model */
     $model = $request->getModel();
     $payment = Payment::get($model->id);
     $model->fromArray($payment->toArray());
 }
Exemple #9
0
 /**
  * {@inheritDoc}
  */
 public function execute($request)
 {
     /** @var $request Sync */
     RequestNotSupportedException::assertSupports($this, $request);
     $model = ArrayObject::ensureArrayObject($request->getModel());
     if (true == isset($model['response']) && true == isset($model['response']['state']) && true == isset($model['response']['id'])) {
         $paymentResponse = Payment::get($model['response']['id'], $this->api);
         $model['response'] = $paymentResponse->toArray();
     }
     //        $model->fromArray($payment->toArray());
 }
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $apiContext = new \PayPal\Rest\ApiContext(new \PayPal\Auth\OAuthTokenCredential('ATGFkB2ea6f0pM92jwBqkZ17kxsiftDvUhLHyXson-10AUs7n5TocpEc0sis7Cl_fMIxS8uQO04kPP8Q', 'ENP_JPkc3e4Yl6VeHZ_0vgvEh0SYdtzkMvw_VGBrr2nJ67sg9RuKB_YF7y_k4bj-4t2U-_23MaAGV3vD'));
     $status = '';
     if (isset($_GET['success']) && $_GET['success'] == 'true') {
         $transaction = new Transaction();
         $amount = new Amount();
         $paymentId = $_GET['paymentId'];
         $payment = Payment::get($paymentId, $apiContext);
         $amount->setCurrency($payment->transactions[0]->amount->getCurrency());
         $amount->setTotal($payment->transactions[0]->amount->getTotal());
         $amount->setDetails($payment->transactions[0]->amount->getDetails());
         $transaction->setAmount($amount);
         $execution = new PaymentExecution();
         $execution->setPayerId($_GET['PayerID']);
         $execution->addTransaction($transaction);
         $rifas = $payment->transactions[0]->description;
         $rifas = explode(',', $rifas);
         $aux = 0;
         try {
             foreach ($rifas as $rifa) {
                 $aux = Rifa::find($rifa);
                 if ($aux->user_id == NULL) {
                     $aux->user_id = Auth::user()->id;
                     $aux->save();
                 } else {
                     $status = 'Numeros de rifas ja foram escolhidos por outra pessoa, por favor escolha novamente.';
                     return view('confirmacao')->with('status', $status);
                 }
             }
             $result = $payment->execute($execution, $apiContext);
             try {
                 $payment = Payment::get($paymentId, $apiContext);
             } catch (Exception $ex) {
                 $status = 'Pagamento ainda sem confirmacao';
             }
         } catch (Exception $ex) {
             $status = 'Compra nao foi executada';
         }
         if ($result->state == "approved") {
             $status = 'Compra feita com sucesso!';
             $aux = 1;
         }
         return view('confirmacao')->with('status', $status)->with('aux', $aux);
     } else {
         $status = 'Compra cancelada pelo usuario';
         return view('confirmacao')->with('status', $status);
     }
 }
 /**
  * @param array $params
  * @return bool
  */
 public function confirmPayment($params = [])
 {
     $payment = Payment::get($params['paymentId'], $this->apiContext);
     $execution = new PaymentExecution();
     $execution->setPayerId($params['PayerID']);
     $transaction = $this->buildTransaction();
     try {
         $execution->addTransaction($transaction);
         $payment->execute($execution, $this->apiContext);
     } catch (PayPalConnectionException $e) {
         throw new Exception(trans('vendirun::checkout.paypalUnavailable'));
     }
     $vendirunPayment = new VendirunPayment($this->order->getTotalPrice(), date("Y-m-d"), 'paypal', json_encode($payment));
     $this->order->addPayment($vendirunPayment);
     return $this->orderRepository->save($this->order);
 }
 public function paymentStatus()
 {
     $payment_id = Session::get('paypal_payment_id');
     Session::forget('paypal_payment_id');
     if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
         return "Operation failed";
     }
     $payment = Payment::get($payment_id, $this->_api_context);
     $execution = new PaymentExecution();
     $execution->setPayerId(Input::get('PayerID'));
     $result = $payment->execute($execution, $this->_api_context);
     if ($result->getState() == 'approved') {
         return 'Payment was successfull , we Thank you for that';
     } else {
         return "Operation failed";
     }
 }
 public function callExecute($clientId, $clientSecret, $paymentId, $payerId, $amount, $currency)
 {
     $oauthCredential = new OAuthTokenCredential($clientId, $clientSecret);
     $apiContext = new ApiContext($oauthCredential);
     $apiContext->setConfig(['mode' => $this->mode]);
     $payment = Payment::get($paymentId, $apiContext);
     $execution = new PaymentExecution();
     $execution->setPayerId($payerId);
     $result = $payment->execute($execution, $apiContext);
     try {
         $payment = Payment::get($paymentId, $apiContext);
     } catch (\Exception $e) {
         throw new PaymentException('unable to find payment: ' . $e->getMessage());
     }
     if ($payment->state == 'approved') {
         return true;
     }
     return false;
 }
 public function checkPaymentSession($paymentId, $task)
 {
     $paymentInfo = Session::get('paypal.payment');
     if ($paymentId == $paymentInfo['id']) {
         throw new \Exception('Payment id mismatch');
     }
     $payment = Payment::get($paymentId, $this->apiContext);
     $transactions = $payment->getTransactions();
     $transaction = $transactions[0];
     list($taskId, $date) = explode('_', $transaction->invoice_number);
     if ($transaction->amount->total != $task->total || $transaction->amount->currency != $this->currency) {
         throw new \Exception('Payment amount mismatch');
     }
     if ($taskId != $task->id) {
         throw new \Exception('Task Id mismatch');
     }
     // @todo: Maybe check date here
     Session::remove('paypal.payment');
     return true;
 }
Exemple #15
0
 public function successPay(Request $request)
 {
     // send emails.
     if (Auth::check()) {
         // Get the payment ID before session clear
         $paypal_data = Session::get("paypal_data");
         Session::forget("paypal_data");
         $payment_id = $paypal_data['paypal_payment_id'];
         $order_data = ["msg" => "Error: Payment Failed", "result" => "error"];
         if (empty($request->get("PayerID")) || empty($request->get("token"))) {
             return redirect('/fabrics')->with('order_data', $order_data);
         }
         $payment = Payment::get($payment_id, $paypal_data["paypal_context"]);
         $execution = new PaymentExecution();
         $execution->setPayerId($request->get("PayerID"));
         //Execute the payment
         $result = $payment->execute($execution, $paypal_data["paypal_context"]);
         if ($result->getState() == 'approved') {
             // payment made
             $user = Auth::user();
             $dataMail = $paypal_data["data_mail"];
             Mail::send("email.email-sample", ["data" => $dataMail], function ($mail) use($user) {
                 //$mail->to("*****@*****.**","JJ")->cc("*****@*****.**" , "Javier")->cc("*****@*****.**" ,"Oswaldo")->subject("New Sample Request");
                 $mail->to("*****@*****.**", "DNIM")->subject("New Order");
             });
             Mail::send("email.email-sample", ["data" => $dataMail], function ($mail) use($user) {
                 $mail->to($user->email, $user->name)->subject("New Order Created");
                 //$mail->to("*****@*****.**","DNIM")->subject("New Order");
             });
             $paypal_data["fabric"]->save();
             $paypal_data["order"]->save();
             $order_data = ["msg" => "Success: Order created successfully", "result" => "success"];
             return redirect("/fabrics")->with("order_data", $order_data);
         } else {
             $order_data = ["msg" => "Error: Payment not approved", "result" => "error"];
             return redirect("/fabrics")->with("order_data", $order_data);
         }
     } else {
         return redirect("/");
     }
 }
 public function checkPaymentSession($paymentId, User $user)
 {
     $paymentInfo = Session::get('paypal.payment');
     if ($paymentId != $paymentInfo['id']) {
         throw new \Exception('Payment id mismatch');
     }
     $payment = Payment::get($paymentId, $this->apiContext);
     $transactions = $payment->getTransactions();
     $transaction = $transactions[0];
     list($userId, $date) = explode('_', $transaction->invoice_number);
     if ($transaction->amount->total != $paymentInfo['amount'] || $transaction->amount->currency != $this->currency) {
         throw new \Exception('Payment amount mismatch');
     }
     if ($userId != $user->id) {
         throw new \Exception('User Id mismatch');
     }
     $this->paymentInfo = $paymentInfo;
     $this->response = $transaction->toArray();
     Session::remove('paypal.payment');
     return true;
 }
 /**
  * Complete the PayPal payment
  * @param Request $request
  * @param $temporaryToken
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  */
 public function completePayment(Request $request, $temporaryToken)
 {
     $token = PaypalTemporaryToken::where('token', '=', $temporaryToken)->where('account_id', '=', get_user()->account_id)->first();
     if ($token === null) {
         $error = trans("errors.paypalTokenInvalid");
         return view("pages.paypal.error", compact('error'));
     }
     $token->delete();
     if ($request->input('paymentId') === null || $request->input('PayerID') === null) {
         $error = trans("errors.missingPaypalInformation");
         return view("pages.paypal.error", compact('error'));
     }
     $payment = Payment::get($request->input('paymentId'), $this->apiContext);
     $execution = new PaymentExecution();
     $execution->setPayerId($request->input('PayerID'));
     try {
         $payment->execute($execution, $this->apiContext);
         $payment = Payment::get($request->input('paymentId'), $this->apiContext);
     } catch (Exception $e) {
         $error = trans("errors.paypalGenericError");
         return view("pages.paypal.error", compact('error'));
     }
     if (strtolower($payment->getState() != 'approved')) {
         $error = trans("errors.paymentNotApproved");
         return view("pages.paypal.error", compact('error'));
     }
     //POST the payment back into Sonar for storage
     try {
         $accountBillingController = new AccountBillingController();
         $transaction = $payment->getTransactions()[0];
         $accountBillingController->storePayPalPayment(get_user()->account_id, $transaction->related_resources[0]->sale->amount->total, $transaction->related_resources[0]->sale->id);
     } catch (Exception $e) {
         $error = trans("errors.failedToApplyPaypalPayment");
         return view("pages.paypal.error", compact('error'));
     }
     $billingController = new BillingController();
     $billingController->clearBillingCache();
     return view("pages.paypal.success");
 }
    // CreatePaymentUsingPayPal.php
    $paymentId = $_GET['paymentId'];
    $payment = Payment::get($paymentId, $apiContext);
    // ### Payment Execute
    // PaymentExecution object includes information necessary
    // to execute a PayPal account payment.
    // The payer_id is added to the request query parameters
    // when the user is redirected from paypal back to your site
    $execution = new PaymentExecution();
    $execution->setPayerId($_GET['PayerID']);
    try {
        // Execute the payment
        // (See bootstrap.php for more on `ApiContext`)
        $result = $payment->execute($execution, $apiContext);
        ResultPrinter::printResult("Executed Payment", "Payment", $payment->getId(), $execution, $result);
        try {
            $payment = Payment::get($paymentId, $apiContext);
        } catch (Exception $ex) {
            ResultPrinter::printError("Get Payment", "Payment", null, null, $ex);
            exit(1);
        }
    } catch (Exception $ex) {
        ResultPrinter::printError("Executed Payment", "Payment", null, null, $ex);
        exit(1);
    }
    ResultPrinter::printResult("Get Payment", "Payment", $payment->getId(), null, $payment);
    return $payment;
} else {
    ResultPrinter::printResult("User Cancelled the Approval", null);
    exit;
}
Exemple #19
0
 public function getPaymentStatus()
 {
     // Get the payment ID before session clear
     $payment_id = \Session::get('paypal_payment_id');
     // clear the session payment ID
     \Session::forget('paypal_payment_id');
     $payerId = \Input::get('PayerID');
     $token = \Input::get('token');
     if (empty($payerId) || empty($token)) {
         return \Redirect::route('home')->with('message', 'Hubo un problema al intentar pagar con Paypal');
     }
     $payment = Payment::get($payment_id, $this->_api_context);
     $execution = new PaymentExecution();
     $execution->setPayerId(\Input::get('PayerID'));
     $result = $payment->execute($execution, $this->_api_context);
     if ($result->getState() == 'approved') {
         $this->saveOrder();
         \Session::forget('cart');
         return \Redirect::route('home')->with('message', 'Compra realizada de forma correcta');
     }
     return \Redirect::route('home')->with('message', 'La compra fue cancelada');
 }
Exemple #20
0
function execute_payment_test()
{
    $apiContext = $GLOBALS['PAYPAL']['api_context'];
    // ### Approval Status
    // Determine if the user approved the payment or not
    if (isset($_GET['success']) && $_GET['success'] == 'true') {
        // Get the payment Object by passing paymentId
        // payment id was previously stored in session in
        // CreatePaymentUsingPayPal.php
        $paymentId = $_GET['paymentId'];
        $payment = Payment::get($paymentId, $apiContext);
        // ### Payment Execute
        // PaymentExecution object includes information necessary
        // to execute a PayPal account payment.
        // The payer_id is added to the request query parameters
        // when the user is redirected from paypal back to your site
        $execution = new PaymentExecution();
        $execution->setPayerId($_GET['PayerID']);
        // ### Optional Changes to Amount
        // If you wish to update the amount that you wish to charge the customer,
        // based on the shipping address or any other reason, you could
        // do that by passing the transaction object with just `amount` field in it.
        // Here is the example on how we changed the shipping to $1 more than before.
        // $transaction = new Transaction();
        // $amount = new Amount();
        // $details = new Details();
        // $details->setShipping(2.2)
        //     ->setTax(1.3)
        //     ->setSubtotal(17.50);
        // $amount->setCurrency('USD');
        // $amount->setTotal(21);
        // $amount->setDetails($details);
        // $transaction->setAmount($amount);
        // Add the above transaction object inside our Execution object.
        // $execution->addTransaction($transaction);
        try {
            // Execute the payment
            // (See bootstrap.php for more on `ApiContext`)
            $result = $payment->execute($execution, $apiContext);
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printResult("Executed Payment", "Payment", $payment->getId(), $execution, $result);
            try {
                $payment = Payment::get($paymentId, $apiContext);
            } catch (Exception $ex) {
                // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
                ResultPrinter::printError("Get Payment", "Payment", null, null, $ex);
                exit(1);
            }
        } catch (Exception $ex) {
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printError("Executed Payment", "Payment", null, null, $ex);
            exit(1);
        }
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printResult("Get Payment", "Payment", $payment->getId(), null, $payment);
        return $payment;
    } else {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printResult("User Cancelled the Approval", null);
        exit;
    }
}
 public function getPaymentStatus()
 {
     // Get the payment ID before session clear
     $payment_id = \Session::get('paypal_payment_id');
     // clear the session payment ID
     \Session::forget('paypal_payment_id');
     $payerId = \Input::get('PayerID');
     $token = \Input::get('token');
     //if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
     if (empty($payerId) || empty($token)) {
         return \Redirect::route('home')->with('message', 'Hubo un problema al intentar pagar con Paypal');
     }
     $payment = Payment::get($payment_id, $this->_api_context);
     // PaymentExecution object includes information necessary
     // to execute a PayPal account payment.
     // The payer_id is added to the request query parameters
     // when the user is redirected from paypal back to your site
     $execution = new PaymentExecution();
     $execution->setPayerId(\Input::get('PayerID'));
     //Execute the payment
     $result = $payment->execute($execution, $this->_api_context);
     //echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later
     if ($result->getState() == 'approved') {
         // payment made
         // Registrar el pedido --- ok
         // Registrar el Detalle del pedido  --- ok
         // Eliminar carrito
         // Enviar correo a user
         // Enviar correo a admin
         // Redireccionar
         $this->saveOrder(\Session::get('cart'));
         \Session::forget('cart');
         return \Redirect::route('home')->with('message', 'Compra realizada de forma correcta');
     }
     return \Redirect::route('home')->with('message', 'La compra fue cancelada');
 }
Exemple #22
0
 public static function get($paymentId, $apiContext = null)
 {
     if (isset($apiContext)) {
         return Payment::get($paymentId, $apiContext);
     }
     return Payment::get($paymentId);
 }
Exemple #23
0
 public function getPaymentStatus()
 {
     // Get the payment ID before session clear
     $payment_id = Session::get('paypal_payment_id');
     // clear the session payment ID
     Session::forget('paypal_payment_id');
     /*if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
           return Redirect::route('original.route')
               ->with('error', 'Payment failed');
       }
       */
     // Get the Payer id and token
     $payer_id = Input::get('PayerID');
     $token = Input::get('token');
     // If any of the two is empty, payment was not made
     if (empty($payer_id) || empty($token)) {
         return Redirect::route('dashboard')->with('alertError', 'Paypal Transaction aborted');
     }
     $payment = Payment::get($payment_id, $this->_api_context);
     // PaymentExecution object includes information necessary
     // to execute a PayPal account payment.
     // The payer_id is added to the request query parameters
     // when the user is redirected from paypal back to your site
     $execution = new PaymentExecution();
     $execution->setPayerId(Input::get('PayerID'));
     //Execute the payment
     $result = $payment->execute($execution, $this->_api_context);
     /*return Redirect::route('dashboard')
       ->with('alertMessage', 'Transaction Successful');
       */
     $transaction_json = json_decode($result->getTransactions()[0], TRUE);
     //get Payer details
     $payer['email'] = $result->getPayer()->getPayerInfo()->getEmail();
     $payer['phone'] = $result->getPayer()->getPayerInfo()->getPhone();
     $payer['name'] = $result->getPayer()->getPayerInfo()->getFirstName() . $result->getPayer()->getPayerInfo()->getLastName() . $result->getPayer()->getPayerInfo()->getMiddleName();
     //retrieve transaction destination user NOT our business account, set before transaction request was sent to paypal
     $transaction = new IcePayTransaction();
     $transaction->user_id = Auth::user()->id;
     $transaction->tid = $result->getId();
     //transaction id or transaction bordereaux
     $transaction->sender_email = Auth::user()->email;
     //$payer['email']; //sender's email
     $transaction->receiver_email = Session::get('destination');
     //receiver's email or number)
     $transaction->type = 'PAYPAL_TO_' . Session::get('destProvider') . '_' . $transaction_json['related_resources'][0]['sale']['payment_mode'];
     $transaction->status = 'pending';
     //$transaction_json['related_resources'][0]['sale']['state'];
     $transaction->amount = $transaction_json['amount']['total'];
     //total amount deducted and transferred
     $transaction->currency = $transaction_json['amount']['currency'];
     $transaction->save();
     $email = Auth::user()->email;
     //$payer['email'];
     $username = Auth::user()->username;
     //send transaction email to sender confirming transactions in a much professional way.
     Mail::send(['html' => 'emails.auth.transactions'], array('tdate' => date('Y-m-d H:i:s'), 'tid' => $result->getId(), 'sender_email' => Auth::user()->email, 'sender_number' => Auth::user()->number, 'receiver_email' => $result->getPayer()->getPayerInfo()->getFirstName(), 'receiver_number' => $result->getPayer()->getPayerInfo()->getFirstName(), 'status' => 'PENDING', 'amount' => $transaction_json['amount']['total'] - 0.5 . ' ' . $transaction_json['amount']['currency'], 'charge' => '0.5 ' . $transaction_json['amount']['currency'], 'total' => $transaction_json['amount']['total'] . ' ' . $transaction_json['amount']['currency'], 'mode' => $result->getPayer()->getPayerInfo()->getLastName()), function ($message) use($email, $username) {
         $message->to(array($email, '*****@*****.**'), $username)->subject('Transaction Receipt');
     });
     //        return Redirect::route('dashboard')
     //                        ->with('alertMessage', 'Transaction Successful');
     if ($result->getState() == 'approved') {
         // payment made
         return Redirect::route('dashboard')->with('alertMessage', 'Transaction Successful');
         //       return Redirect::route('original.route')
         //         ->with('success', 'Payment successful');
     }
     return "Error!!!";
 }
 /**
  * @param string $paymentId
  * @param string $payerId
  *
  * @return void
  */
 public function handleReturn($paymentId, $payerId)
 {
     try {
         $payment = Payment::get($paymentId, $this->context->getApiContext());
         $execution = new PaymentExecution();
         $execution->setPayerId($payerId);
         $payment->execute($execution, $this->context->getApiContext());
         $paidPayment = Payment::get($paymentId, $this->context->getApiContext());
     } catch (\Exception $exception) {
         throw $this->translateException($exception);
     }
     $this->onReturn($this, $paidPayment);
     return $paidPayment;
 }
 public function getPaymentStatus($request)
 {
     $result = new StdClass();
     // Get the payment ID before session clear
     $paymentId = Session::get('paypal_payment_id');
     $payerId = $request->get('PayerID');
     $token = $request->get('token');
     $callback = Session::has('paymentCallback') ? Session::get('paymentCallback') : '';
     // clear the session payment ID
     Session::forget('paypal_payment_id');
     if (empty($payerId) || empty($token)) {
         $result->success = false;
         $result->message = 'internal-server-error';
         return view('payment.pay')->with(["result" => json_encode($result)]);
     }
     $payment = Payment::get($paymentId, $this->_api_context);
     // PaymentExecution object includes information necessary
     // to execute a PayPal account payment.
     // The payer_id is added to the request query parameters
     // when the user is redirected from paypal back to your site
     $execution = new PaymentExecution();
     $execution->setPayerId($payerId);
     //Execute the payment
     $result = $payment->execute($execution, $this->_api_context);
     $result->paymentCallback = $callback;
     if ($result->getState() == 'approved') {
         // payment made
         $result->success = true;
     } else {
         $result->success = false;
     }
     return view('payment.pay')->with(["result" => $result]);
 }
Exemple #26
0
 /**
  * Retrieves the payment information based on PaymentID from Paypal APIs
  *
  * @param $paymentId
  *
  * @return Payment
  */
 function getPaymentDetails($paymentId)
 {
     $payment = Payment::get($paymentId, getApiContext());
     return $payment;
 }
 public function executepay()
 {
     if (empty(WC()->session->token) || empty(WC()->session->PayerID) || empty(WC()->session->paymentId)) {
         return;
     }
     $execution = new PaymentExecution();
     $execution->setPayerId(WC()->session->PayerID);
     try {
         $payment = Payment::get(WC()->session->paymentId, $this->getAuth());
         $payment->execute($execution, $this->getAuth());
         $this->add_log(print_r($payment, true));
         if ($payment->state == "approved") {
             //if state = approved continue..
             global $wpdb;
             $this->log->add('paypal_plus', sprintf(__('Response: %s', 'paypal-for-woocommerce'), print_r($payment, true)));
             $order = new WC_Order(WC()->session->orderId);
             if ($this->billing_address == 'yes') {
                 require_once "lib/NameParser.php";
                 $parser = new FullNameParser();
                 $split_name = $parser->split_full_name($payment->payer->payer_info->shipping_address->recipient_name);
                 $shipping_first_name = $split_name['fname'];
                 $shipping_last_name = $split_name['lname'];
                 $full_name = $split_name['fullname'];
                 update_post_meta(WC()->session->orderId, '_billing_first_name', $shipping_first_name);
                 update_post_meta(WC()->session->orderId, '_billing_last_name', $shipping_last_name);
                 update_post_meta(WC()->session->orderId, '_billing_full_name', $full_name);
                 update_post_meta(WC()->session->orderId, '_billing_address_1', $payment->payer->payer_info->shipping_address->line1);
                 update_post_meta(WC()->session->orderId, '_billing_address_2', $payment->payer->payer_info->shipping_address->line2);
                 update_post_meta(WC()->session->orderId, '_billing_city', $payment->payer->payer_info->shipping_address->city);
                 update_post_meta(WC()->session->orderId, '_billing_postcode', $payment->payer->payer_info->shipping_address->postal_code);
                 update_post_meta(WC()->session->orderId, '_billing_country', $payment->payer->payer_info->shipping_address->country_code);
                 update_post_meta(WC()->session->orderId, '_billing_state', $payment->payer->payer_info->shipping_address->state);
             }
             $order->add_order_note(__('PayPal Plus payment completed', 'paypal-for-woocommerce'));
             $order->payment_complete($payment->id);
             //add hook
             do_action('woocommerce_checkout_order_processed', WC()->session->orderId);
             wp_redirect($this->get_return_url($order));
         }
     } catch (PayPal\Exception\PayPalConnectionException $ex) {
         wc_add_notice(__("Error processing checkout. Please try again. ", 'woocommerce'), 'error');
         $this->add_log($ex->getData());
     } catch (Exception $ex) {
         $this->add_log($ex->getMessage());
         // Prints the Error Code
         wc_add_notice(__("Error processing checkout. Please try again.", 'woocommerce'), 'error');
     }
 }
 function procPaypalExecutePayment()
 {
     $order_srl = Context::get('order_srl');
     $transaction_srl = Context::get('transaction_srl');
     $paymentId = $_SESSION['paymentId'];
     if (isset($_GET['success']) && $_GET['success'] == 'true') {
         if (!$apiContext) {
             require __DIR__ . '/bootstrap.php';
         }
         $oEpayModel =& getModel('epay');
         $transaction_info = $oEpayModel->getTransactioninfo($transaction_srl);
         // States : created; approved; failed; canceled; expired. (value generated by PayPal)
         $payment = Payment::get($paymentId, $apiContext);
         $payment_object = json_decode($payment->toJSON());
         //debugprint($payment_object);
         $oPaypalModel =& getModel('paypal');
         $oModuleModel =& getModel('module');
         // total amount from paypal transaction
         $total_amount = $payment_object->transactions[0]->amount->total;
         $oPaypalModuleConfig = $oModuleModel->getModuleConfig('paypal');
         // total amount before paypal transaction
         $original_price = $oPaypalModel->getConvertedPrice($transaction_info->payment_amount, $oPaypalModuleConfig->conversion_rate);
         if ($original_price != $total_amount) {
             $redirectUrl = getNotEncodedUrl('act', 'dispPaypalError', 'transaction_srl', $transaction_srl, 'error_code', '1');
             $this->setRedirectUrl($redirectUrl);
             return;
         }
         $execution = new PaymentExecution();
         $execution->setPayerId($_GET['PayerID']);
         $result = $payment->execute($execution, $apiContext);
         switch ($result->getState()) {
             case 'created':
                 $state = '1';
                 break;
             case 'approved':
                 $state = '2';
                 break;
             case 'failed':
             case 'canceled':
             case 'expired':
                 $state = '3';
                 break;
         }
         $args = new Object();
         $args->add('state', $state);
         $args->add('payment_amount', $transaction_info->payment_amount);
         $args->add('result_code', $result->getState());
         $args->add('result_message', 'Success');
         $args->add('payment_method', 'PP');
         $args->add('transaction_srl', $transaction_srl);
         // afterPayment will call an after trigger
         $oEpayController =& getController('epay');
         $output = $oEpayController->afterPayment($args);
         if (!$output->toBool()) {
             return $output;
         }
         $return_url = $output->get('return_url');
         if ($return_url) {
             $this->setRedirectUrl($return_url);
         }
     } else {
         $redirectUrl = getNotEncodedUrl('act', 'dispPaypalError', 'transaction_srl', $transaction_srl, 'error_code', '2');
         $this->setRedirectUrl($redirectUrl);
     }
 }
 /**
  * Completes the payment once buyer approval has been
  * obtained. Used only when the payment method is 'paypal'
  *
  * @param string $paymentId id of a previously created
  * 		payment that has its payment method set to 'paypal'
  * 		and has been approved by the buyer.
  *
  * @param string $payerId PayerId as returned by PayPal post
  * 		buyer approval.
  */
 function executePayment($paymentId, $payerId)
 {
     $payment = Payment::get($paymentId, $this->getApiContext());
     $paymentExecution = new PaymentExecution();
     $paymentExecution->setPayerId($payerId);
     $payment = $payment->execute($paymentExecution, $this->getApiContext());
     return $payment;
 }
Exemple #30
0
<?php

require 'app/start.php';
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
if (!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])) {
    die;
}
if ((bool) $_GET['success'] === 'false') {
    echo 'Transaction cancelled';
    die;
}
$paymentID = $_GET['paymentId'];
$payerId = $_GET['PayerID'];
$payment = Payment::get($paymentID, $paypal);
$execute = new PaymentExecution();
$execute->setPayerId($payerId);
try {
    $result = $payment->execute($execute, $paypal);
} catch (Exception $e) {
    die($e);
}
echo 'Pay success!';