I have a bitcoin address created using blockcypher and I would like to transfer some bitcoins from it (already made a deposit) to another address.
I am using the blockcypher php client to create the transaction using the sample code https://www.blockcypher.com/dev/bitcoin/?php#creating-transactions and https://github.com/blockcypher/php-client/blob/master/sample/transaction-api/CreateTransaction.php, I get the error
Class 'Mdanter\Ecc\Math\Gmp' not found in C:\xampp\htdocs\cck\vendor\bitwasp\bitcoin\src\Math\Math.php on line 8
I checked file the vendor and there is Gmp file or class in Mdanter\Ecc\Math\Gmp, so i edited the math.php file and edited line 6 to use \Mdanter\Ecc\Math\GmpMath as Gmp; and now get the error like the one in https://github.com/blockcypher/php-client/issues/21
My code is as below
require_once __DIR__.'/vendor/autoload.php';
use BlockCypher\Auth\SimpleTokenCredential;
use BlockCypher\Rest\ApiContext;
use BlockCypher\Api\TX as DD;
use BlockCypher\Client\TXClient;
// ... other classes
$apiContext = ApiContext::create(
'main', 'btc', 'v1',
new SimpleTokenCredential('4e3a287e603f48c994d978dab061084a'),
array('log.LogEnabled' => true, 'log.FileName' => 'BlockCypher.log', 'log.LogLevel' => 'DEBUG') );
$tx = new DD();
// Tx inputs
$input = new \BlockCypher\Api\TXInput();
$input->addAddress("1DZR2kUCa5HTyVZLY8TWFf2ZfjhWgsgNtf");
$tx->addInput($input);
// Tx outputs
$output = new \BlockCypher\Api\TXOutput();
$output->addAddress("1Mye4sZmd9rzjY6yUw19etZhzeVU2q1kcj");
$output->setValue(1000); // Satoshis
$tx->addOutput($output);
// Tx amount
$txClient = new TXClient($apiContext);
$txSkeleton = $txClient->create($tx);
$privateKeys = array("3ed07ff3e458fabb8b99b723002f4817eebd5fc11f9c76fdd9c200090c04fd1c");
$txSkeleton = $txClient->sign($txSkeleton, $privateKeys);
$txSkeleton = $txClient->send($txSkeleton);
The problem was caused by a bad dependency configuration in one of the php-client dependencies. It was fixed. More info:
https://github.com/blockcypher/php-client/issues/21
You only need to update php-client to the latest release.
Related
I use Inpost ShipX PHP SDK php library one courier company to post/create shipping using API.
With this code I can get shipping label and save, this working correct:
$shipmentData = json_decode($response->getBody()->__toString(), true);
while ($shipmentData['status'] !== 'confirmed') {
sleep(1);
$response = $api->shipments()->get($shipmentData['id']);
$shipmentData = json_decode($response->getBody()->__toString(), true);
}
$labelResponse = $api->shipments()->label()->get($shipmentData['id'], [
'format' => 'Pdf',
'type' => 'A6',
]);
file_put_contents('var/labels/paczkomaty_label.pdf', $labelResponse->getBody()->__toString());
Now I try also get tracking number for created shipping.
I try add to above code:
$trackingResponse = $api->shipments()->tracking()->get($shipmentData['id']);
var_dump($trackingResponse);
But after post I get:
An uncaught Exception was encountered
Type: InvalidArgumentException
Message: tracking resource not found
Filename: /vendor/imper86/php-inpost-api/src/Resource/AbstractResource.php
Line Number: 66
Can anyone check this library and help me build the function correctly or give me a hint how i can check the resource to build the right function?
Code for __call inside /vendor/imper86/php-inpost-api/src/Resource/AbstractResource.php#66:
$className = $this->reflection->getName() . '\\' . ucfirst($name);
In your case it would be Shipments\\Tracking, but there is no such class.
Try doing
$api->tracking()->shippingHistory()->get($shipmentData['id']);
Basically what you see inside src/Resouce dir you can call as method.
I have just performed static analysis of code/structure, may be wrong
So, I have a GKE-based function that does processing on an image file. I want this function to be triggered whenever a new file gets dumped into a bucket, using Pub/Sub. I have an external system that pushes the image file into the bucket. I was using object notifications to do this, now I want to use Pub/Sub.
Can I create a notification in GoogleCloudStorage that generates the Pub/Sub notification that my processing function will be pulling? I was looking at the PHP library (https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.162.0/storage/notification) to do this, but the documentation is ridiculously inadequate.
This code creates a notification, but seems strange that I should be supplying a notification ID, and I'm not sure what the payload is going to be...
$client=new StorageClient(['projectId'=><my project>, 'keyFile'=><key file contents>]);
$bucket_name = <my bucket name>;
$notification_id = '2482'; // ?????
$notification_params = [
'eventType' => 'OBJECT_FINALIZE',
'payloadFormat' => 'JSON_API_V1',
'bucketId' => $bucket_name,
];
$bucket = $client->bucket( $bucket_name );
$notification = $bucket->notification( $notification_id );
Is this the correct way to create the notification I want? Do I specify my own id in this way? What happens if there is a collision?
thanks,
andy
Yes it is possible to create a Pub/Sub notification when an object was pushed into the bucket.You need to first create a Pub/Sub topic and subscriber prior to creating the notification.
I used the sample code create pub/sub notification and just add defining of storage bucket:
use Google\Cloud\Core\Iam\PolicyBuilder;
use Google\Cloud\PubSub\PubSubClient;
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient();
$bucket = $storage->bucket('your-bucket'); // define bucket to be used
$pubSub = new PubSubClient();
$topicName = 'your-topic'; // define the topic to be used
// grant pubsub publisher role for topic
$serviceAccountEmail = $storage->getServiceAccount();
$topic = $pubSub->topic($topicName);
$iam = $topic->iam();
$updatedPolicy = (new PolicyBuilder($iam->policy()))
->addBinding('roles/pubsub.publisher', [
"serviceAccount:$serviceAccountEmail"
])
->result();
$iam->setPolicy($updatedPolicy);
$notification = $bucket->createNotification($topicName, [
'event_types' => [
'OBJECT_DELETE',
'OBJECT_METADATA_UPDATE'
]
]);
To test this, when the pub/sub notification is created:
Push an object in your bucket
Topic should send a message to the subscribers
Check message in the subscriber
Pushed object in test bucket:
Message/notification published to subscribers:
I am using Docusign PHP Client and trying to create and envelope and send it as email. With the current SDK, I was getting an error:
INVALID_REQUEST_BODY The request body is missing or improperly formatted. Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'API_REST.Models.v2.document[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\n ◀
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive t ▶
Path 'documents.documentBase64', line 1, position 31.
So I had to edit EnvelopeApi.php (line 2876) json_encode($httpBody) to make it work.
Now that it's working, I receive a response like this, however I can't change status created to sent is my problem.
EnvelopeSummary {#460 ▼
#container: array:4 [▼
"envelope_id" => "6b9ef863-2ee0-4ea6-9f7e-20b7d4f59b22"
"status" => "created"
"status_date_time" => "2018-10-03T12:30:22.8600000Z"
"uri" => "/envelopes/6b9ef863-2ee0-4ea6-9f7e-20b7d4f59b22"
]
}
My full code:
First, I authenticated and fetched my $accountId
And then creating Envelope:
$path = public_path('test.pdf');
$b64Doc = base64_encode(file_get_contents($path));
$document = new Document();
$document->setName("TEST.pdf");
$document->setFileExtension("pdf");
$document->setDocumentId(1);
$document->setDocumentBase64($b64Doc);
$sign_here = new SignHere();
$sign_here->setXPosition(25);
$sign_here->setYPosition(50);
$sign_here->setDocumentId(1);
$sign_here->setPageNumber(1);
$sign_here->setRecipientId(1);
$tabs = new Tabs();
$tabs->setSignHereTabs($sign_here);
$signers = new Signer();
$signers->setName('Test User');
$signers->setEmail('test#mailinator.com');
$signers->setRoleName('Signer');
$signers->setRecipientId(1);
$signers->setRoutingOrder(1);
$signers->setTabs($tabs);
$recipients = new Recipients();
$recipients->setSigners($signers);
$envelope_definition = new EnvelopeDefinition();
$envelope_definition->setEmailSubject('Signature Request');
$envelope_definition->setStatus("sent"); // ***
$envelope_definition->setDocuments($document);
$envelope_definition->setRecipients($recipients);
$options = new CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);
try {
$envelopeSummary = $envelopeApi->createEnvelope($accountId, $envelope_definition, $options);
dd($envelopeSummary);
// Also tried this:
// $envelopeApi->update($accountId, $envelopeSummary->getEnvelopeId(), json_encode(['status' => 'sent']);
} catch (ApiException $e){
dd($e->getResponseBody()->errorCode . " " . $e->getResponseBody()->message);
}
$envelope_definition->setStatus("sent"); this should trigger the email, right? But it doesn't for some reason. Also I can't see this created envelope in my Sandbox either.
You are not setting signers correctly. It must be an array of signer objects.
Here is some untested code:
# This code creates a signer, not signers
$signer = new Signer();
$signer->setName('Test User');
$signer->setEmail('test#mailinator.com');
$signer->setRoleName('Signer');
$signer->setRecipientId(1);
$signer->setRoutingOrder(1);
$signer->setTabs($tabs);
$recipients = new Recipients();
# setSigners wants an array of signer objects.
# in this case, we make an array with one element
$recipients->setSigners(array($signer));
Also, you are not creating the tabs right either. Again, it needs to be an array of the tab type.
See this example for additional ideas.
Yes, setting status to sent should make DocuSign send the envelope upon creation. The fact that the response contains "status" => "created" seems to indicate that your setting of the property ($envelope_definition->setStatus("sent");) is not actually being included as part of the request that's being issued to DocuSign.
I've compared your code with the code examples provided in GitHub for the PHP SDK, specifically, with the signatureRequestOnDocument function on that page. The only obvious difference I can see between your code and that example code is in the syntax for creating objects. For example, creating the envelope:
Your code: $envelope_definition = new EnvelopeDefinition();
PHP SDK example code: $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
I don't know much about PHP, let alone about the DocuSign PHP SDK, but I'd suggest that you try to closely mimic the code examples that are part of the SDK repo on GitHub, to see if you get a different result that way.
My code work like this :
$signersArray = array();
$signer = new Signer();
$signer->set...
$signersArray[] = $signer;
$recipients->setSigners($signersArray);
If it's not working try to dump the data send from the SDK to the API and double check that the status is correct :
Go to Docusign/esign-client/src/ApiClient.php and var_dump($postData) at line 159
I am trying to post some form data to Google Datastore, using this documentation here and here. I am struggling with knowing how to post the form data to the datastore, but I thought I had cracked it when I got the following error.
Parse error: syntax error, unexpected 'use' (T_USE) in record-usage.php on line 23
So my question is in two parts:
how do I post data to the Datastore from my form? (the examples in the documentation seem to offer two different ways of posting to the store)
how do I fix this syntax error?
Here is my code (it's actually line 7 in the sample below):
if(isset($_POST['submit'])) {
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Datastore\DatastoreClient;
# Your Google Cloud Platform project ID
$projectId = 'room-usage';
# Instantiates a client
$datastore = new DatastoreClient([
'projectId' => $projectId
]);
# The kind for the new entity
$kind = 'RoomUsage';
# The name/ID for the new entity
$name = $roomname + $_POST('timestamp');
# The Cloud Datastore key for the new entity
$taskKey = $datastore->key($kind, $name);
if($_POST('countinput') == '') {
$formdata->Headcount = $_POST('countslider');
} else {
$formdata->Headcount = $_POST('countinput');
}
$formdata->Timestamp = $_POST('timestamp');
$formdata->EnteredBy = $_POST('userid');
$formdata->RoomID = $_POST('roomid');
$formdata->Activity = $_POST('activity');
$formdata->Estimate = $_POST('estimate');
$formdata->NotAudited = $_POST('notaudited');
$formdata->Reason = $_POST('reason');
function save_room_usage(DatastoreClient $datastore, $formdata) {
$RoomUsage = $datastore->RoomUsage();
$transaction->updateBatch([$formdata]);
$transaction->commit();
}
# Prepares the new entity
$task = $datastore->entity($taskKey,
['Timestamp' => $_POST('timestamp'),
'Headcount' => $formdata->Headcount,
'EnteredBy' => $_POST('userid'),
'RoomID' => $_POST('roomid'),
'Activity' => $_POST('activity'),
'Estimate' => $_POST('estimate'),
'NotAudited' => $_POST('notaudited'),
'Reason' => $_POST('reason')]);
# Saves the entity
$datastore->upsert($task);
$status = 'Saved ' . $task->key() . ': ' . $task['description'];
}
Use
You can't have use inside a function. Think of it like an import.
Instead, move it outside of the method but inside your namespace. Simplest way to get going is just move it to the top of your file.
Writing data
Looking at this code:
$transaction->updateBatch([$formdata]);
$transaction->commit();
I think you've misinterpreted the transaction documentation. In the code example it presents, it first reads entities from Datastore via a Batch Lookup, then writes them back as a batch with:
$transaction->updateBatch([$fromAccount, $toAccount]);
In that example $fromAccount and $toAccount are proper entities with keys.
In your example, you are trying to batch write just a bunch of random data. Since you are only writing one record, you should delete that code.
The second part of your code where you create an entity and then upsert it should work. If you did end up needing to write more than one entity in a transaction, it is $task that you would use in the updateBatch method rather than the raw data.
require 'vendor/autoload.php';
use Plivo\RestAPI;
$auth_id = "My AUTH_ID";
$auth_token = "My AUTH_TOKEN";
$p = new RestAPI($auth_id, $auth_token);
$params = array(
'number' => '12512077502' # Phone number to buy
);
$response = $p->get_number($params);
print_r ($response);
It Will Give me Error Message
Array (
[status] => 404
[response] => Array (
[api_id] => 0b6214ee-aec4-11e5-ae4f-22000ac69a0d
[error] => not found
) )
See here https://www.plivo.com/docs/getting-started/phone-number-api/#rent-a-number
You seem to be using the wrong function (get_number) from the python helper library. The correct one is "buy_phone_number" function which uses PhoneNumber API.
Reference - https://github.com/plivo/plivo-python/blob/master/plivo.py#L175
I was using the Python plivo module and had the same problem.
From Plivo Support: "Use the new API: https://www.plivo.com/docs/api/number/phonenumber/#buy-number "
What I found that the the plivo module uses the wrong URL when renting a phone number. My work around is to make the call without the helper library. The following is Python code but it might help give you an idea what to do.
import requests
params = {
'number' : phone_number # Phone number to buy
}
host = 'https://api.plivo.com/v1/Account/%s/PhoneNumber/%s/' % \
(account_sid, phone_number)
r = requests.post(host, timeout=5, json=params, auth=(account_sid, auth_token))
assert r.status_code == 201, 'r.status_code=%s' % `r.status_code`
Update: The above might not be necessary after all. I just got an update from Plivo support. The new method name is buy_phone_number() instead of get_number(). That solved the problem for me. I assume the same is true for the PHP library.