I am trying to send payment using coinbase.com wallet API. I found a code on GitHub, using it I successfully sent payment to LTC address. Here's the code:
<?php
include 'vendor/autoload.php';
$apiKey = 'MY_API_HERE';
$apiSecret = 'MY_SECRET_HERE';
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;
$accountId = "MY_LTC_ACCOUNT_ID_HERE";
$account = $client->getAccount($accountId);
$transaction = Transaction::send([
'toBitcoinAddress' => 'PAYMENT_ADDRESS',
'amount' => new Money(AMOUNT_OF_LTC_HERE, CurrencyCode::LTC)
]);
try {
$client->createAccountTransaction($account, $transaction);
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
My included files are here https://darkchannel.info/coinbase/vendor.zip
But I don't know how to get the transaction hash (coin transaction id).
You still have initial transaction as $transaction, so after creating the transaction in the network, you can access the hash using this code $transaction->getNetwork()-> getHash().
Related
i have integrated coinbase api in my web app. When charge is created, users are directed to coinbase commerce website to make payment. How do i check if the user has finished paying or not and if the exact amount has been paid. Below is my code
<?php
require_once __DIR__ . "/vendor/autoload.php";
use CoinbaseCommerce\ApiClient;
use CoinbaseCommerce\Resources\Charge;
/**
* Init ApiClient with your Api Key
* Your Api Keys are available in the Coinbase Commerce Dashboard.
* Make sure you don't store your API Key in your source code!
*/
ApiClient::init("MY API KEY HERE");
$chargeObj = new Charge();
$chargeObj->name = 'Bitcoin Deposit';
$chargeObj->description = 'Testing the payment system';
$chargeObj->local_price = [
'amount' => '100.00',
'currency' => 'USD'
];
$chargeObj->pricing_type = 'fixed_price';
try {
$chargeObj->save();
// insert into database with status pending
$queryobject->insertTransaction($_SESSION['user_id'],$chargeObj->id, $amount, $status, $currentTime,
$chargeObj->name, $chargeObj->currency);
} catch (\Exception $exception) {
echo sprintf("Sorry! payment could not be created. Error: %s \n", $exception->getMessage());
}
if ($chargeObj->id) {
$chargeObj->description = "New description";
// Retrieve charge by "id"
try {
$retrievedCharge = Charge::retrieve($chargeObj->id);
$hosted_url = $retrievedCharge->hosted_url;
header('location: '.$hosted_url);
} catch (\Exception $exception) {
echo sprintf("Enable to retrieve charge. Error: %s \n", $exception->getMessage());
}
}
You need to use webhooks for this, you can create an endpoint for this. Unfortunately Coinbase does not have a sandbox environment so you are going to need a bit of cryptocurrency in your account.
I am using PayPal REST API in sandbox mode to test payments.
I create the approval link, then redirect user to said link.
PayPal then asks for credentials which I insert as a sandbox test buyer. But after logging in, PayPal does not redirect me to complete the approval of payment, and instead straight to My Account summary from where I cannot approve the payment. However if the user was already logged in, the payment approval proceeds as expected.
Is it the problem with how was the link created or is it a bug?
This is the code used to create the link
<?php
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
class PaypalFactory
{
private const CLIENT_ID = 'yyy';
private const CLIENT_SECRET = 'xxx';
private function __construct()
{
}
public static final function getContext()
{
return new ApiContext(
new OAuthTokenCredential(
self::CLIENT_ID,
self::CLIENT_SECRET
)
);
}
public static final function createPaymentLink(
int $orderId,
string $currency,
float $totalPrice,
float $deliveryPrice,
string $returnUrl,
string $cancelUrl): string
{
$payer = new Payer();
$payer
->setPaymentMethod("paypal");
$details = new Details();
$details
->setShipping($deliveryPrice)
->setSubtotal($totalPrice);
$item = new Item();
$item
->setName('products and shipping')
->setCurrency($currency)
->setPrice($totalPrice)
->setQuantity(1);
$itemList = new ItemList();
$itemList->setItems(array($item));
$amount = new Amount();
$amount
->setCurrency($currency)
->setTotal($totalPrice + $deliveryPrice)
->setDetails($details);
$transaction = new Transaction();
$transaction
->setItemList($itemList)
->setAmount($amount)
->setDescription("Products from ")
->setInvoiceNumber($orderId);
$redirectUrls = new RedirectUrls();
$redirectUrls
->setReturnUrl($returnUrl)
->setCancelUrl($cancelUrl);
$payment = new Payment();
$payment
->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
try {
$payment->create(PaypalFactory::getContext());
} catch (Exception $ex) {
print $ex;
}
return $payment->getApprovalLink();
}
}
Purging all browser cookies for paypal domains is good advice, and may help. The problem you're experiencing is probably a general sandbox issue (that won't happen in live mode), and not a problem with your code.
However, seeing your code/solution, I do have suggestions for trying some newer/better things:
Instead of the old PayPal-PHP-SDK for v1/payments, use the new Checkout-PHP-SDK for v2/orders
Instead of redirecting the buyer to the approval URL, give the approval token to the Javascript code of Smart Payment Buttons, which will display an in-context window that keeps your site loaded in the background. Here's a demo pattern
I am trying to test coinbase api. Api authorized fine but most functions are returning empty arrey, bellow is my code sample
<?php
require_once('vendor/autoload.php');
use Coinbase\Wallet\Resource\Account;
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;
use Coinbase\Wallet\Resource\Address;
$apiKey='********';
$apiSecret='********;';
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
$accounts = $client->getAccounts();
$account = $client->getPrimaryAccount();
$auth = $client->getCurrentAuthorization();
$user = $client->getCurrentUser();
$paymentMethods = $client->getPaymentMethods();
echo "accounts arrey". json_encode($accounts)."<hr/>";//empty arrey
echo "primary account arrey".json_encode($account)." <hr/>";//empty arrey
echo "current auth arrey".json_encode($auth)."<hr/>";//printing data perfectly
echo "current user arrey".json_encode($user)."<hr/>";//empty array
echo "payment methods arrey".json_encode($paymentMethods)."<hr/>";//empty array
?>
All of echo printing empty array except $authbellow is output screenshot
This problem was solved by using $response=$client->decodeLastResponse(); and echo $response
Just trying get list of all incoming transactions to our PayPal account with PayPal PHP SDK, but result from following example return me still just one record (and we have thousands of payments in our live environment). According PP documentation everything looks ok... Is there any different service for incoming payments?
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__ . '/vendor/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'...SUssUIJQ6zEOdQBI7nUG...', // ClientID
'...YHw3aCroq0mbqSdzimPq...' //Secret hash
)
);
$apiContext->setConfig(array('mode' => 'live'));
$payment = new \PayPal\Api\Payment();
try {
$params = array();
$payments = $payment->all($params, $apiContext);
echo $payments;
} catch (Exception $ex) {
print_r($ex);
}
Basically what I can see is that I am failing to create the apiContext object. Can anyone see where the error is? Please tell me how I can improve the question.
Here is the error:
Fatal error: Uncaught exception 'PayPal\Exception\PPConnectionException'
with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.' in /vendor/paypal
/sdk-core-php/lib/PayPal/Core/PPHttpConnection.php:104 Stack trace: #0
/vendor/paypal/sdk-core-php/lib/PayPal/Transport/PPRestCall.php(44):
PayPal\Core\PPHttpConnection->execute('{"intent":"sale...') #1 /vendor/paypal
/rest-api-sdk-php/lib/PayPal/Api/Payment.php(246): PayPal\Transport
\PPRestCall->execute(Array, '/v1/payments/pa...', 'POST',
'{"intent":"sale...') #2 /pymt.php(38): PayPal\Api
\Payment->create(Object(PayPal\Rest\ApiContext)) #3 {main} thrown in /vendor
/paypal/sdk-core-php/lib/PayPal/Core/PPHttpConnection.php on line 104
This is the PHP sample I'm using. I am trying to run it off my server. If a customer clicks the pay with paypal button, it runs the following sample script:
<?php
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Address;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
session_start();
$payer = new Payer();
$payer->setPayment_method('paypal');
$amount = new Amount();
$amount->setCurrency('USD');
$amount->setTotal('1.00');
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('This is the payment description.');
$baseUrl = getBaseUrl();
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturn_url('baseUrl/sale.php');
$redirectUrls->setCancel_url('baseUrl/saleFail.php');
$payment = new Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setRedirect_urls($redirectUrls);
$payment->setTransactions(array($transaction));
try {
$payment->create($apiContext);
} catch (\PPConnectionException $ex) {
echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData());
exit(1);
}
foreach ($payment->getLinks() as $link) {
if ($link->getRel() == 'approval_url') {
$redirectUrl = $link->getHref();
}
}
$_SESSION['paymentId'] = $payment->getId();
if(isset($redirectUrl)) {
header('Location: $redirectUrl');
exit;
}
Here's the redacted bootstrap.php:
<?php
/*
* Sample bootstrap file.
*/
// Include the composer autoloader
if(!file_exists(__DIR__ .'/vendor/autoload.php')) {
echo "The 'vendor' folder is missing. You must run 'composer update --no-dev' to resolve application dependencies.\nPlease see the README for more information.\n";
exit(1);
}
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/common.php';
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
$apiContext = getApiContext();
/**
Helper method for getting an APIContext for all calls
*
* #return PayPal\Rest\ApiContext
*/
function getApiContext() {
// ### Api context
// Use an ApiContext object to authenticate
// API calls. The clientId and clientSecret for the
// OAuthTokenCredential class can be retrieved from
// developer.paypal.com
$apiContext = new ApiContext(
new OAuthTokenCredential(
'MY CLIENT ID',
'MY SECRET'
)
);
// Register the sdk_config.ini file in current directory
// as the configuration source.
if(!defined("PP_CONFIG_PATH")) {
define("PP_CONFIG_PATH", __DIR__);
}
return $apiContext;
}
Can anyone help? Let me know if you need more info. Thanks up front.
I got the same problem too, I found that if any param was wrong (for example: an invalid card number or a invalid currency format), php SDK throw Connection Exception, Instead of returning certain Json Message(when I organize POST data myself and send with curl , It's OK)! I wander if it is reasonable to design like this, Or we just missed something!...