/** * @return Payment * @throws CheckoutException */ public function startPayment() { $total_amount = ($this->request->amount + $this->request->tax_amount - $this->request->discount_amount) * 100; $apiContext->setConfig(array('service.EndPoint' => "https://test-api.sandbox.paypal.com")); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item1 = new Item(); $item1->setName('Product1')->setCurrency('EUR')->setPrice(10.0)->setQuantity(2)->setTax(3.0); $itemList = new ItemList(); $itemList->setItems(array($item1)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5); $amount = new Amount(); $amount->setCurrency('EUR')->setTotal(20)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription('Payment')->setInvoiceNumber('transactionid'); $baseUrl = getBaseUrl(); $redir = new RedirectUrls(); $redir->setReturnUrl($baseUrl . '/'); $redir->setCancelUrl($baseUrl . '/'); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redir)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($apiContext); } catch (\Exception $e) { throw new CheckoutException('Paypal error', 500, $e); } $approvalUrl = $payment->getApprovalLink(); ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='{$approvalUrl}' >{$approvalUrl}</a>", $request, $payment); return $payment; }
function CreateTransaction($transactionType, $itemArray, $details) { $payer = new Payer(); $payer->setPaymentMethod($GLOBALS['PAYPAL']['payment_method']); $itemList = new ItemList(); $itemList->setItems($itemArray); $amount = new Amount(); $amount->setCurrency($GLOBALS['PAYPAL']['currency'])->setTotal(GetDetailsTotal($details))->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription($GLOBALS['TRANSACTION_TYPE']['DONATION']['payment_desc'])->setInvoiceNumber(uniqid()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($GLOBALS['TRANSACTION_TYPE']['DONATION']['return_url'])->setCancelUrl($GLOBALS['TRANSACTION_TYPE']['DONATION']['cancel_url']); $payment = new Payment(); $payment->setIntent($GLOBALS['TRANSACTION_TYPE']['DONATION']['intent'])->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($GLOBALS['PAYPAL']['api_context']); } catch (Exception $ex) { ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex); return false; } $approvalUrl = $payment->getApprovalLink(); echo $approvalUrl; return array('request' => $request, 'payment' => $payment, 'approvalUrl' => $approvalUrl); }
/** * @throws \InvalidArgumentException * * @return Payment */ private function payment() : Payment { if ($this->payment === null) { $this->payment = $this->return->payment(); $this->payment->execute($this->execution(), $this->context); } return $this->payment; }
public static function addTrackingParameters(Payment $payment) { $redirectUrls = $payment->getRedirectUrls(); $url = new Url($redirectUrls->getReturnUrl()); $url->setQueryParameter('utm_nooverride', 1); $redirectUrls->setReturnUrl($url->getAbsoluteUrl()); $payment->setRedirectUrls($redirectUrls); return $payment; }
public function createPayment($card, $transaction) { $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi)); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setTransactions(array($transaction)); $payment->create($this->apiContext); return $payment; }
/** * @throws \InvalidArgumentException * * @return Payment|MockInterface */ private function mockPayPalPayment() { if ($this->payPalPayment === null) { $this->payPalPayment = Mockery::mock(Payment::class); $this->payPalPayment->shouldIgnoreMissing()->asUndefined(); app()->extend(Payment::class, function () { return $this->payPalPayment; }); } return $this->payPalPayment; }
public static function createPayPal($invoiceNumber, \PropelPDO $con) { $i18n = Localizer::get('payment'); // ### Payer // A resource representing a Payer that funds a payment // For direct credit card payments, set payment method // to 'credit_card' and add an array of funding instruments. $payer = new Payer(); $payer->setPaymentMethod("paypal"); // ### Itemized information // (Optional) Lets you specify item wise // information $item1 = new Item(); $item1->setName($i18n['item_name'])->setDescription($i18n['item_description'])->setCurrency(TransactionEntity::$BASE_CURRENCY)->setQuantity(1)->setTax(0)->setPrice(TransactionEntity::$MEMBER_FEE); $itemList = new ItemList(); $itemList->setItems(array($item1)); // ### Amount // Lets you specify a payment amount. // You can also specify additional details // such as shipping, tax. $amount = new Amount(); $amount->setCurrency(TransactionEntity::$BASE_CURRENCY)->setTotal(TransactionEntity::$MEMBER_FEE); // ### Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription($i18n['transaction_description'])->setInvoiceNumber($invoiceNumber); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation. $success = Router::toModule('account', 'index'); $failure = Router::toModule('guide', 'index', ['purchase_failed' => true]); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($success)->setCancelUrl($failure); // ### Payment // A Payment Resource; create one using // the above types and intent set to sale 'sale' $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setExperienceProfileId(self::getPaymentExperienceProfileId())->setTransactions(array($transaction)); // ### Create Payment // Create a payment by calling the payment->create() method // with a valid ApiContext (See bootstrap.php for more on `ApiContext`) // The return object contains the state. $apiContext = self::getApiContext(); $payment->create($apiContext); return $payment; }
function paypal($data) { try { foreach ($data as $k => $v) { ${$k} = $v; } include_once 'config.paypal.php'; $apiContext = new ApiContext(new OAuthTokenCredential(CLIENT_ID, CLIENT_SECRET)); list($m, $y) = explode("/", $card_expiry); $card = new CreditCard(); $card->setNumber($card_number); $card->setType(strtolower($card_type)); $card->setExpireMonth($m); $card->setExpireYear($y); $card->setCvv2($card_cvv); $card->setFirstName($first_name); $card->setLastName($last_name); $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod('credit_card'); $payer->setFundingInstruments(array($fi)); $amount = new Amount(); $amount->setCurrency($currency); $amount->setTotal($price); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setDescription('Enter your card details and proceed'); $payment = new Payment(); $payment->setIntent('sale'); $payment->setPayer($payer); $payment->setTransactions(array($transaction)); $res = json_decode($payment->create($apiContext)); $this->save($data, __FUNCTION__, $res, 1); return json_encode(["status" => true, "msg" => sprintf("Your payment has been %s", $res->state)]); } catch (Exception $e) { if ($e instanceof PPConfigurationException) { } elseif ($e instanceof PPConnectionException) { } elseif ($e instanceof PayPal\Exception\PayPalConnectionException) { $res = json_decode($e->getData(), 1); $this->save($data, __FUNCTION__, $res, 0); $msg = array_shift(isset($res["details"]) ? $res["details"] : []); return json_encode(["status" => false, "msg" => $res["name"] == "UNKNOWN_ERROR" || empty($msg["issue"]) ? "An unknown error has occurred" : sprintf("%s %s", ["cvv2" => "CVV2", "expire_year" => "Card expiration", "credit_card" => "", "type" => "Invalid credit card number or", "number" => "Credit card number", "expire_month" => "Expiration month"][end(explode(".", $msg["field"]))], strtolower($msg["issue"]))]); } else { throw $e; } } }
/** * @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 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'); }
/** * @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; }
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; }
public function createPayment() { $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item_1 = new Item(); $item_1->setName('Item 1')->setCurrency('USD')->setQuantity(2)->setPrice('15'); // unit price $item_2 = new Item(); $item_2->setName('Item 2')->setCurrency('USD')->setQuantity(4)->setPrice('7'); $item_3 = new Item(); $item_3->setName('Item 3')->setCurrency('USD')->setQuantity(1)->setPrice('20'); // add item to list $item_list = new ItemList(); $item_list->setItems(array($item_1, $item_2, $item_3)); $amount = new Amount(); $amount->setCurrency('USD')->setTotal(78); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Your transaction description'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(route('payment.status'))->setCancelUrl(route('payment.status')); $payment = new Payment(); $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction)); try { $payment->create($this->_api_context); } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); exit; } else { die('Some error occur, sorry for inconvenient'); } } foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } // add payment ID to session Session::put('paypal_payment_id', $payment->getId()); if (isset($redirect_url)) { // redirect to paypal return Redirect::away($redirect_url); } return Redirect::route('original.route')->with('error', 'Unknown error occurred'); }
/** * {@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()); }
/** * {@inheritDoc} */ public function execute($request) { /** @var $request Capture */ RequestNotSupportedException::assertSupports($this, $request); $details = ArrayObject::ensureArrayObject($request->getModel()); $payment = new Payment(); $payer = new Payer(); $payer->payment_method = "paypal"; $amount = new Amount(); $amount->currency = $details['PAYMENTREQUEST_CURRENCYCODE']; $amount->total = $details['PAYMENTREQUEST_AMT']; $transaction = new Transaction(); $transaction->amount = $amount; $transaction->description = $details['PAYMENTREQUEST_DESCRIPTION']; $redirectUrls = new RedirectUrls(); $redirectUrls->return_url = $details['RETURN_URL']; $redirectUrls->cancel_url = $details['CANCEL_URL']; $payment->intent = "sale"; $payment->payer = $payer; $payment->redirect_urls = $redirectUrls; $payment->transactions = [$transaction]; if (false == isset($details['response']) && false == isset($details['response']['state']) && isset($payment->payer->payment_method) && 'paypal' == $payment->payer->payment_method) { $paymentResponse = $payment->create($this->api); $details['response'] = $paymentResponse->toArray(); foreach ($paymentResponse->links as $link) { if ($link->rel == 'approval_url') { throw new HttpRedirect($link->href); } } } if (false == isset($details['response']) && false == isset($details['response']['state']) && isset($payment->payer->payment_method) && 'credit_card' == $payment->payer->payment_method) { $paymentResponse = $payment->create($this->api); $details['response'] = $paymentResponse->toArray(); } $this->gateway->execute(new Sync($details)); if (true == isset($details['response']) && true == isset($details['response']['state']) && true == isset($details['response']['id']) && isset($payment->payer->payment_method) && 'paypal' == $payment->payer->payment_method && true == isset($details['PayerID'])) { $payment->setId($details['response']['id']); $execution = new PaymentExecution(); $execution->setPayerId($details['PayerID']); //Execute the payment $paymentResponse = $payment->execute($execution, $this->api); $details['response'] = $paymentResponse->toArray(); } }
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); }
/** * {@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()); }
/** * {@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()); }
/** * @throws \InvalidArgumentException * * @return Payment */ private function payment() : Payment { if ($this->payment === null) { $this->payment = app(Payment::class); $this->payment->setIntent('sale'); $this->payment->setPayer($this->payer()); $this->payment->setRedirectUrls($this->redirectUrls()); $this->payment->setTransactions([$this->transaction()]); $this->payment->create($this->apiContext); } return $this->payment; }
/** * Creates a new mock 'payment authorization' * * @param PayPal\Api\ApiContext apiContext * @return PayPal\Api\Authorization */ function createAuthorization($apiContext) { $addr = new Address(); $addr->setLine1("3909 Witmer Road")->setLine2("Niagara Falls")->setCity("Niagara Falls")->setState("NY")->setPostalCode("14305")->setCountryCode("US")->setPhone("716-298-1822"); $card = new CreditCard(); $card->setType("visa")->setNumber("4417119669820331")->setExpireMonth("11")->setExpireYear("2019")->setCvv2("012")->setFirstName("Joe")->setLastName("Shopper")->setBillingAddress($addr); $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi)); $amount = new Amount(); $amount->setCurrency("USD")->setTotal("1.00"); $transaction = new Transaction(); $transaction->setAmount($amount)->setDescription("Payment description."); $payment = new Payment(); // Setting intent to authorize creates a payment // authorization. Setting it to sale creates actual payment $payment->setIntent("authorize")->setPayer($payer)->setTransactions(array($transaction)); $paymnt = $payment->create($apiContext); $resArray = $paymnt->toArray(); return $authId = $resArray['transactions'][0]['related_resources'][0]['authorization']['id']; }
public static function authorize() { $addr = new Address(); $addr->setLine1("3909 Witmer Road"); $addr->setLine2("Niagara Falls"); $addr->setCity("Niagara Falls"); $addr->setState("NY"); $addr->setPostal_code("14305"); $addr->setCountry_code("US"); $addr->setPhone("716-298-1822"); $card = new CreditCard(); $card->setType("visa"); $card->setNumber("4417119669820331"); $card->setExpire_month("11"); $card->setExpire_year("2019"); $card->setCvv2("012"); $card->setFirst_name("Joe"); $card->setLast_name("Shopper"); $card->setBilling_address($addr); $fi = new FundingInstrument(); $fi->setCredit_card($card); $payer = new Payer(); $payer->setPayment_method("credit_card"); $payer->setFunding_instruments(array($fi)); $amount = new Amount(); $amount->setCurrency("USD"); $amount->setTotal("1.00"); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setDescription("This is the payment description."); $payment = new Payment(); $payment->setIntent("authorize"); $payment->setPayer($payer); $payment->setTransactions(array($transaction)); $paymnt = $payment->create(); $resArray = $paymnt->toArray(); return $authId = $resArray['transactions'][0]['related_resources'][0]['authorization']['id']; }
private function createPayment($details) { $payment = new Payment(); $payer = new Payer(); $payer->payment_method = "paypal"; $amount = new Amount(); $amount->currency = $details['PAYMENTREQUEST_CURRENCYCODE']; $amount->total = $details['PAYMENTREQUEST_AMT']; $transaction = new Transaction(); $transaction->amount = $amount; $transaction->description = $details['PAYMENTREQUEST_DESCRIPTION']; $itemList = new ItemList(); foreach ($details['PAYMENTREQUEST_ITEMS'] as $itemInfo) { $item = new Item(); $item->setQuantity($itemInfo['quantity']); $item->setName($itemInfo['name']); $item->setDescription($itemInfo['description']); $item->setPrice($itemInfo['price']); $item->setCategory($itemInfo['category']); $item->setCurrency($itemInfo['currency']); $item->setTax($itemInfo['tax']); $item->setSku($itemInfo['sku']); $itemList->addItem($item); } $addressInfo = $details['PAYMENTREQUEST_SHIPPING_ADDRESS']; $shippingAddress = new ShippingAddress(); $shippingAddress->setRecipientName($addressInfo['recipient_name']); $shippingAddress->setLine1($addressInfo['line1']); $shippingAddress->setPostalCode($addressInfo['postal_code']); $shippingAddress->setCity($addressInfo['city']); $shippingAddress->setCountryCode($addressInfo['country_code']); $itemList->setShippingAddress($shippingAddress); $transaction->setItemList($itemList); $redirectUrls = new RedirectUrls(); $redirectUrls->return_url = $details['RETURN_URL']; $redirectUrls->cancel_url = $details['CANCEL_URL']; $payment->intent = "sale"; $payment->payer = $payer; $payment->redirect_urls = $redirectUrls; $payment->transactions = [$transaction]; if (false == isset($details['response']) && false == isset($details['response']['state']) && isset($payment->payer->payment_method) && 'paypal' == $payment->payer->payment_method) { $paymentResponse = $payment->create($this->api); $details->replace(['response' => $paymentResponse->toArray()]); foreach ($paymentResponse->links as $link) { if ($link->rel == 'approval_url') { $details->replace(['approval_url' => $link->href]); } } } }
/** * 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); } }
public function sendRequest() { $details = new Details(); $details->setShipping(0)->setTax(0)->setSubtotal($this->totalAmount); $amount = new Amount(); $amount->setCurrency($this->currencyCode)->setTotal($this->totalAmount)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($this->itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $baseUrl = 'http://localhost/'; $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/ExecutePayment.php?success=true")->setCancelUrl("{$baseUrl}/ExecutePayment.php?success=false"); $payment = new Payment(); $payment->setIntent("sale")->setPayer($this->payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $payment->create($this->apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY var_dump($ex); exit(1); } $approvalUrl = $payment->getApprovalLink(); header('Location: ' . $approvalUrl); quit(); }
/** * Creates a PayPal payment * * @param array $configuration * @param Payer $payer * @param RedirectUrls $redirectUrls * @param Transaction $transaction * * @return Payment */ public function createPayment(array $configuration, Payer $payer, RedirectUrls $redirectUrls, Transaction $transaction) : Payment { $apiContext = $this->getApiContext($configuration); $payment = new Payment(); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setRedirectUrls($redirectUrls); $payment->setTransactions([$transaction]); return $payment->create($apiContext); }
/** * @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); }
/** * {@inheritdoc} */ public function processPayment(PaymentInterface $payment) : PaymentInterface { $order = $payment->getOrder(); $payer = $this->createPayer('paypal'); $redirectUrls = $this->createRedirectUrls($payment); $transaction = $this->createTransaction($order); $payPalPayment = new Payment(); $payPalPayment->setIntent("sale"); $payPalPayment->setPayer($payer); $payPalPayment->setRedirectUrls($redirectUrls); $payPalPayment->setTransactions([$transaction]); try { $payPalPayment->create($apiContext); } catch (\Exception $e) { echo $e->getMessage(); } $payment->setApprovalUrl($payPalPayment->getApprovalLink()); $payment->setState($payPalPayment->getState()); $payment->setToken($payPalPayment->getId()); $this->paymentManager->updateResource($payment); return $payment; }
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 order() { $paypalConf = $this->config->item('paypal'); $clientId = $paypalConf['clientId']; $clientSecret = $paypalConf['clientSecret']; $appName = $paypalConf['appName']; $price = $paypalConf['price']; $shiping = 0; $tax = 0; $mode = "sandbox"; //or live $apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret)); $apiContext->setConfig(array('mode' => $mode, 'log.LogEnabled' => false)); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName($appName)->setCurrency('USD')->setQuantity(1)->setPrice($price); $itemList = new ItemList(); $itemList->setItems(array($item1)); $details = new Details(); $details->setShipping($shiping)->setTax($tax)->setSubtotal($price); $amount = new Amount(); $amount->setCurrency("USD")->setTotal($price + $shiping + $tax)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $token = $this->createToken(); $baseUrl = getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/paypal/ordersucess?success=true&tk1=" . $token[0] . "&tk2=" . $token[1])->setCancelUrl("{$baseUrl}/paypal/orderfailed?success=false"); $payment = new Payment(); $payment->setIntent("order")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); // For Sample Purposes Only. $request = clone $payment; try { $payment->create($apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printError("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex); exit(1); } $approvalUrl = $payment->getApprovalLink(); header("Location: " . $approvalUrl . ""); die; }
public function credit_card() { return "Hello?"; $card = new CreditCard(); $card->setType("visa")->setNumber("4148529247832259")->setExpireMonth("11")->setExpireYear("2019")->setCvv2("012")->setFirstName("Joe")->setLastName("Shopper"); $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi)); $item1 = new Item(); $item1->setName('Ground Coffee 40 oz')->setDescription('Ground Coffee 40 oz')->setCurrency('USD')->setQuantity(1)->setTax(0.3)->setPrice(7.5); $item2 = new Item(); $item2->setName('Granola bars')->setDescription('Granola Bars with Peanuts')->setCurrency('USD')->setQuantity(5)->setTax(0.2)->setPrice(2); $itemList = new ItemList(); $itemList->setItems(array($item1, $item2)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5); $amount = new Amount(); $amount->setCurrency("USD")->setTotal(20)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($apiContext); } catch (Exception $ex) { ResultPrinter::printError('Create Payment Using Credit Card. If 500 Exception, try creating a new Credit Card using <a href="https://ppmts.custhelp.com/app/answers/detail/a_id/750">Step 4, on this link</a>, and using it.', 'Payment', null, $request, $ex); exit(1); } ResultPrinter::printResult('Create Payment Using Credit Card', 'Payment', $payment->getId(), $request, $payment); return $payment; }