<p>Here is the algorythm without the code:</p>

<ol>
<li><p><code>createrawtransaction</code> with <code>amount</code> that you want to send assuming that fees are <code>0</code></p></li>
<li><p><code>fundrawtransaction</code> to let your bitcoind construct final transaction, put your <code>change</code> address (on where you get change from unspent transaction - <strong>very important!</strong>) AND to caclulate <code>fees</code> that will be taken of your account for this transaction.</p></li>
<li><p>Substract caclulated <code>fees</code> from initial <code>amount</code></p></li>
<li><p>Repeat steps 1-2 with new lowered amount.</p></li>
<li><p>Profit.</p></li>
</ol>

<p>And here is the PHP code. </p>

<p>We will need function to create and fund new transaction</p>

<pre><code>function prepareRawTransaction($amountToSend, $addressToSendTo) {

    $bitcoin = new Bitcoin('bitcoinrpc', 'xxx');

    $collectedAmount = 0;
    $sendToArray = [];
    $sendToArray[$addressToSendTo] = $amountToSend;

    $unspentTransactions = $bitcoin-&gt;listunspent(); //First we find out all our unspent transactions from where we can withdraw
    $collectedTransactions = [];

    foreach ($unspentTransactions as $unspentTransaction) {

        if ($collectedAmount &lt; $amountToSend) {
            $collectedTransactions[] = [
                'txid'  =&gt; $unspentTransaction['txid'],
                'vout'  =&gt; $unspentTransaction['vout'],
            ];

            $collectedAmount += $unspentTransaction['amount'];
        } else {

            break;
        }
    }

    //Now we create raw transactions
    $rawTransaction = $bitcoin-&gt;createrawtransaction($collectedTransactions, $sendToArray);

    //And fund it
    $newTransaction = $bitcoin-&gt;fundrawtransaction($rawTransaction);
    return $newTransaction;
}
</code></pre>

<p>Now we can use that function to go on algorythm</p>

<pre><code>$bitcoin = new Bitcoin('bitcoinrpc', 'xxx');

$amountToSend = 0.09999556; //That's exact amount that we want to send INCLUDING commission
$addressToSendTo = '2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF';

//createrawtransaction with amount that you want to send assuming that fees are 0
$transactionWithoutCommission = prepareRawTransaction($amountToSend, $addressToSendTo);

$decoded = $bitcoin-&gt;decoderawtransaction($transactionWithoutCommission['hex']);
print_r($decoded); //You can see that fees now set up

//Substract caclulated fees from initial amount
$amountToSend =  $amountToSend - $transactionWithoutCommission['fee'];

//Repeat steps 1-2 with new lowered amount
$transactionWithCommission = prepareRawTransaction($amountToSend, $addressToSendTo);

$decoded = $bitcoin-&gt;decoderawtransaction($transactionWithCommission['hex']);
print_r($decoded); //Here you can see that total amount + commission equal needed amount

$signed = $bitcoin-&gt;signrawtransaction($transactionWithCommission['hex']);
print_r($signed); //should say complete:1 if everything was correctly put

$published = $bitcoin-&gt;sendrawtransaction($signed['hex']);
print_r($published); //will output you tx id
</code></pre>

<p>And profit: you have sent exactly the amount you wanted INCLUDING the commission</p>

<p><a href="https://i.sstatic.net/GMwCK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GMwCK.png" alt="enter image description here"></a></p>

CC BY-SA 3.0
2018-01-28T03:11:51.613Z
What API/lib your using e.g. easybitcoin.php
zhiyan114
CC BY-SA 3.0
2018-01-28T11:26:59.503Z
`easybitcoin`, yes
Denis Matafonov
CC BY-SA 3.0
2018-01-28T16:51:34.043Z
Ok so does the answer below me helps ?
zhiyan114
CC BY-SA 3.0
2018-01-28T01:21:51.813Z
2018-01-28T01:21:51.813Z
Denis Matafonov
<p>What you can do is use
<code>
$txid = $bitcoin-        &gt;sendtoaddress("User's bitcoIN address here ","amount of btc to send","comment 1","comment 2", true);
// echo $txid;
</code>
what the true is that it makes sure the fees are already included in the amount you want to set (not sure if the lib is glitches and if it is then the true may not work properly)</p>

CC BY-SA 3.0
2018-01-28T03:26:43.027Z
I suggest you try it on the testnet to see if it works
zhiyan114
CC BY-SA 3.0
2018-01-28T03:32:05.730Z
For bitcoin-cli that supports it, you can type bitcoin-cli "address btc" "amount" "comment 1" "comment 2" true
zhiyan114
CC BY-SA 3.0
2018-01-29T17:49:00.353Z
When using `sendtoaddress` you will pay commission off the primary account.  Say if you want to send me 0.01 BTC, your account totally will be credited to 0.01 BTC PLUS commission for the transaction. That's the main problem.
Denis Matafonov
CC BY-SA 3.0
2018-01-29T17:51:05.820Z
I think scheme when `sender-pays-commission` is more common, since you have to be sure that receiver will get the amount that he expects, not less. But scheme `receiver-pays-commission` is also needed and it wasnt easy to make it up.
Denis Matafonov
CC BY-SA 3.0
2018-01-29T18:49:35.713Z
If it refund depend on your choice
zhiyan114
CC BY-SA 3.0
2018-01-28T03:18:25.607Z
2018-01-28T03:18:25.607Z
zhiyan114
<p>First, I have simple problem. I want to send customer some bitcoins, but <strong>I dont want to pay fees for him</strong>. I'd like to substruct fees from payment, so all commissions would be payed by customer.</p>

<p>I thought it should be a simple and common problem for all merchants that making refunds to clients. But I googled for hours and could not find any detailed explanation on how to achieve this feature '<strong>receiver-pays-commissions</strong>'.</p>

<p>Here some links that I found usefull, but still they dont have exact answer</p>

<p><a href="http://blog.macoymejia.com/2014/08/15/bitcoin-raw-transaction-made-easy/" rel="nofollow noreferrer">How to create raw transaction in bitcoind</a></p>

<p><a href="https://bitcoin.stackexchange.com/questions/13538/jsonrpc-calling-createrawtransaction-in-php">How to create raw transaction in PHP</a></p>

<p><a href="https://bitcoin.stackexchange.com/questions/43532/transaction-fees-and-transactions-with-bitcoin-cli-wallet-address-balance-negat/43601#43601">How to calculate transaction size and fee</a></p>

<p>Simply put. I want to send some bitcoins away so that my account balance will be equal exactly <code>1.8000000</code>. Now it is slightly higher:</p>

<p><a href="https://i.sstatic.net/OgVQf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OgVQf.png" alt="enter image description here"></a></p>

<p>Surprisingly this simple and common problem took hours of googling, so I'm making this question just to share solution with public, since I finally found it. </p>

<p>(Or at least I think I've found it, so critics and comments are very welcome.)</p>

<bitcoind><php><createrawtransaction>
How to send bitcoins with commission extracted from payment in PHP or bitcoind
Denis Matafonov
# How to send bitcoins with commission extracted from payment in PHP or bitcoind

(Asked by: username_0 on 2018-01-28)

First, I have simple problem. I want to send customer some bitcoins, but **I dont want to pay fees for him**. I'd like to substruct fees from payment, so all commissions would be payed by customer.

I thought it should be a simple and common problem for all merchants that making refunds to clients. But I googled for hours and could not find any detailed explanation on how to achieve this feature '**receiver-pays-commissions**'.

Here some links that I found usefull, but still they dont have exact answer

[How to create raw transaction in bitcoind](http://blog.macoymejia.com/2014/08/15/bitcoin-raw-transaction-made-easy/)

[How to create raw transaction in PHP](https://bitcoin.stackexchange.com/questions/13538/jsonrpc-calling-createrawtransaction-in-php)

[How to calculate transaction size and fee](https://bitcoin.stackexchange.com/questions/43532/transaction-fees-and-transactions-with-bitcoin-cli-wallet-address-balance-negat/43601#43601)

Simply put. I want to send some bitcoins away so that my account balance will be equal exactly `1.8000000`. Now it is slightly higher:

[![enter image description here](https://i.sstatic.net/OgVQf.png)](https://i.sstatic.net/OgVQf.png)

Surprisingly this simple and common problem took hours of googling, so I'm making this question just to share solution with public, since I finally found it.

(Or at least I think I've found it, so critics and comments are very welcome.)

**Tags:** bitcoind, php, createrawtransaction


---

## 2 answers

### Answer by username_0 on 2018-01-28. Score: 3

Here is the algorythm without the code:

createrawtransaction with amount that you want to send assuming that fees are 0
fundrawtransaction to let your bitcoind construct final transaction, put your change address (on where you get change from unspent transaction - very important!) AND to caclulate fees that will be taken of your account for this transaction.
Substract caclulated fees from initial amount
Repeat steps 1-2 with new lowered amount.
Profit.

And here is the PHP code. 
We will need function to create and fund new transaction
function prepareRawTransaction($amountToSend, $addressToSendTo) {

    $bitcoin = new Bitcoin('bitcoinrpc', 'xxx');

    $collectedAmount = 0;
    $sendToArray = [];
    $sendToArray[$addressToSendTo] = $amountToSend;

    $unspentTransactions = $bitcoin->listunspent(); //First we find out all our unspent transactions from where we can withdraw
    $collectedTransactions = [];

    foreach ($unspentTransactions as $unspentTransaction) {

        if ($collectedAmount < $amountToSend) {
            $collectedTransactions[] = [
                'txid'  => $unspentTransaction['txid'],
                'vout'  => $unspentTransaction['vout'],
            ];

            $collectedAmount += $unspentTransaction['amount'];
        } else {

            break;
        }
    }

    //Now we create raw transactions
    $rawTransaction = $bitcoin->createrawtransaction($collectedTransactions, $sendToArray);

    //And fund it
    $newTransaction = $bitcoin->fundrawtransaction($rawTransaction);
    return $newTransaction;
}

Now we can use that function to go on algorythm
$bitcoin = new Bitcoin('bitcoinrpc', 'xxx');

$amountToSend = 0.09999556; //That's exact amount that we want to send INCLUDING commission
$addressToSendTo = '2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF';

//createrawtransaction with amount that you want to send assuming that fees are 0
$transactionWithoutCommission = prepareRawTransaction($amountToSend, $addressToSendTo);

$decoded = $bitcoin->decoderawtransaction($transactionWithoutCommission['hex']);
print_r($decoded); //You can see that fees now set up

//Substract caclulated fees from initial amount
$amountToSend =  $amountToSend - $transactionWithoutCommission['fee'];

//Repeat steps 1-2 with new lowered amount
$transactionWithCommission = prepareRawTransaction($amountToSend, $addressToSendTo);

$decoded = $bitcoin->decoderawtransaction($transactionWithCommission['hex']);
print_r($decoded); //Here you can see that total amount + commission equal needed amount

$signed = $bitcoin->signrawtransaction($transactionWithCommission['hex']);
print_r($signed); //should say complete:1 if everything was correctly put

$published = $bitcoin->sendrawtransaction($signed['hex']);
print_r($published); //will output you tx id

And profit: you have sent exactly the amount you wanted INCLUDING the commission

> **Comments:**
> **username_1**: What API/lib your using e.g. easybitcoin.php  
> **username_0**: `easybitcoin`, yes  
> **username_1**: Ok so does the answer below me helps ?  

---

### Answer by username_1 on 2018-01-28. Score: 0

What you can do is use
`$txid = $bitcoin- >sendtoaddress("User's bitcoIN address here ","amount of btc to send","comment 1","comment 2", true);
// echo $txid;`
what the true is that it makes sure the fees are already included in the amount you want to set (not sure if the lib is glitches and if it is then the true may not work properly)

> **Comments:**
> **username_1**: I suggest you try it on the testnet to see if it works  
> **username_1**: For bitcoin-cli that supports it, you can type bitcoin-cli "address btc" "amount" "comment 1" "comment 2" true  
> **username_0**: When using `sendtoaddress` you will pay commission off the primary account.  Say if you want to send me 0.01 BTC, your account totally will be credited to 0.01 BTC PLUS commission for the transaction. That's the main problem.  
> **username_0**: I think scheme when `sender-pays-commission` is more common, since you have to be sure that receiver will get the amount that he expects, not less. But scheme `receiver-pays-commission` is also needed and it wasnt easy to make it up.  
> **username_1**: If it refund depend on your choice  

---

