BitPay API gateway payment Bitcoin - pairing - bitcoin

I am struggling with bitpay API.
So far i generated public,priate and sin keys.
I stored them and now i want to pair with special key from bitpay.com
Here is my error and below its my whole code.
Anyone can help ?
Public Key: 0309f03bc0d566c411aeb55b8be57b0485d28706ace9b1a198d053212bde06d718 Private Key: 77cec96ea11e3d35ec2817db6951167755095f8a45c508028ca22734fe7e9962 Sin Key: Tf2XSANqca54VHQG31RXjAY5EKdyaysHtct
Fatal error: Uncaught Bitpay\Client\ArgumentException: pairing code is not legal in /var/www/dev.simplemining.net/vendor/bitpay/php-client/src/Bitpay/Client/Client.php:494 Stack trace: #0 /var/www/dev.simplemining.net/controller/account.php(65): Bitpay\Client\Client->createToken(Array) #1 /var/www/dev.simplemining.net/index.php(20): require('/var/www/dev.si...') #2 {main} thrown in /var/www/dev.simplemining.net/vendor/bitpay/php-client/src/Bitpay/Client/Client.php on line 494
require __DIR__ . '/../vendor/autoload.php';
$private = new \Bitpay\PrivateKey('/tmp/private.key');
$public = new \Bitpay\PublicKey('/tmp/public.key');
$sin = new \Bitpay\SinKey('/tmp/sin.key');
// Generate Private Key values
$private->generate();
// Generate Public Key values
$public->setPrivateKey($private);
$public->generate();
// Generate Sin Key values
$sin->setPublicKey($public);
$sin->generate();
printf("Public Key: %s\n", $public);
printf("Private Key: %s\n", $private);
printf("Sin Key: %s\n\n", $sin);
$manager = new \Bitpay\KeyManager(new \Bitpay\Storage\EncryptedFilesystemStorage('fdgkjnfdERTPWIEFMVwe'));
$manager->persist($private);
$manager->persist($public);
$manager->persist($sin);
$bitpay = new \Bitpay\Bitpay(
array(
'bitpay' => array(
'network' => 'testnet', // testnet or livenet, default is livenet
'public_key' => '/tmp/public.key', //see tutorial/001.php and 002.php
'private_key' => '/tmp/private.key',
'key_storage' => 'Bitpay\Storage\EncryptedFilesystemStorage',
'key_storage_password' => 'fdgkjnfdERTPWIEFMVwe'
)
)
);
/**
* Create the client that will be used to send requests to BitPay's API
*/
$client = $bitpay->get('client');
// #var \Bitpay\KeyManager
$manager = $bitpay->get('key_manager');
$publicKey = $manager->load($bitpay->getContainer()->getParameter('bitpay.public_key'));
$sin = new \Bitpay\SinKey();
$sin->setPublicKey($publicKey);
$sin->generate();
// #var \Bitpay\TokenInterface
$token = $client->createToken(
array(
'id' => (string) $sin,
'pairingCode' => 'fees',
'label' => 'y1FdbaA',
)
);

I was faced this problem. Then I used properly this "https://github.com/bitpay/php-bitpay-client" library and follow the steps.
So first of all download latest bitpay library and configure properly as per document read me file.
You can integrate with tutorial from https://github.com/bitpay/php-bitpay-client/tree/master/examples/tutorial.

Related

Xero Oauth2 Node Examples

I am doing some expermenting with the xero API, however i cant seem to get past the Connect to Xero returning an error
"Sorry, something went wrong
Go back and try again.
If the issue continues, check out our Status Page."
I have setup my App in the xero dev center
I have tried these 2 repos
https://github.com/XeroAPI/xero-node-oauth2-app
https://github.com/XeroAPI/node-oauth2-example
Both yeld the same result just an error page, no information in console/dev tools
Any help would be amazing as im completely stuck with this
So that looks like the error you get when either API keys and/or callback urls are not setup correctly.
Have you swapped in all your api keys & callback urls to the .env (environment) files?
Create a .env file in the root of your project & replace the 3 variables
Create an .env file in the root of your project using touch .env or edit the sample prefix off sample.env and change out with your /myapps credentials of the app you just made.
CLIENT_ID=...
CLIENT_SECRET=...
REDIRECT_URI=...
Here is the library that is used successfully with ouath2.0 tokenization. The token is expired in 30 mints. After that, we need to refresh the token with old token objects.
First set up an app in developer.xero.com.
Add Company Name and Redirect URL while creating the app.
Setup environment configuration in your file.
X_CLIENT_ID=CD43E78278ED4BE68F35F155C3E708F7
X_CLIENT_SECRET=IuP5TrE70JoyYiezMRM2KwvcHFYoLy3qRbD3NFlOkYLN0Asy
X_REDIRECT_URL=https://baseredirecturl.com/xero/default/redirect
Step-1: Here is the code for creating a token and refresh token.
public function actionConnectXero()
{
$session = Yii::$app->session;
$request = Yii::$app->request;
if (empty($request->get('code'))) {
// If we don't have an authorization code then get one
$authUrl = $this->provider->getAuthorizationUrl([
'scope' => 'offline_access openid email profile accounting.settings accounting.transactions accounting.contacts accounting.reports.read projects accounting.journals.read'
]);
//offline_access openid email profile accounting.settings accounting.transactions accounting.contacts accounting.reports.read projects accounting.journals.read
$session->set('oauth2state', $this->provider->getState());
$this->redirect($authUrl);
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($request->get('state')) || ($request->get('state') !== $session->get('oauth2state'))) {
$session->remove('oauth2state');
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $this->provider->getAccessToken('authorization_code', [
'code' => $request->get('code')
]);
$session->set('access_token', $token);
//If you added the openid/profile scopes you can access the authorizing user's identity.
$identity = $this->provider->getResourceOwner($token);
echo "<pre>";
print_r($identity);
//Get the tenants that this user is authorized to access
$tenants = $this->provider->getTenants($token);
print_r($tenants);
$session->set('tenantId', $tenants[0]->tenantId);
exit;
}
}
Step-2: Redirect to URL.
public function actionRedirectXero()
{
$request = Yii::$app->request;
$codeStr = explode("?", $request->getUrl());
$token = $this->provider->getAccessToken('authorization_code', [
'code' => $request->get('code')
]);
$tenants = $this->provider->getTenants($token);
$exits = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
$xeroConf = $exits ? XeroConfigs::findOne($exits->id) : new XeroConfigs();
$xeroConf->access_token = $token;
$xeroConf->refresh_token = $token->getRefreshToken();
$xeroConf->expiry = $token->getExpires();
$xeroConf->tenant_id = isset($tenants[0]) ? $tenants[0]->id : 0;
$xeroConf->token_object = serialize($token);
$xeroConf->created_by = Yii::$app->user->identity->id;
$xeroConf->save();
$this->redirect('/xero/default/get-xero-data?'.$codeStr[1]);
}
Step-3: Get data from xero. I just save and get contacts. for more examples, you can check the package documentation.
public function actionGetXeroData(){
$configs = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
if($configs->expiry < time()){
$newAccessToken = $this->provider->getAccessToken('refresh_token', [
'grant_type' => 'refresh_token',
'refresh_token' => $configs->refresh_token
]);
$tenants = $this->provider->getTenants($newAccessToken);
$xeroConf = XeroConfigs::findOne($configs->id);
$xeroConf->access_token = $newAccessToken;
$xeroConf->refresh_token = $newAccessToken->getRefreshToken();
$xeroConf->expiry = $newAccessToken->getExpires();
$xeroConf->tenant_id = isset($tenants[0]) ? $tenants[0]->id : 0;;
$xeroConf->token_object = serialize($newAccessToken);;
$xeroConf->updated_at = Carbon::now()->toDateTimeString();
$xeroConf->created_by = Yii::$app->user->identity->id;
$xeroConf->save();
$configs = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
}
$tokenObj = unserialize($configs->token_object);
$tenants = $this->provider->getTenants($tokenObj);
$xero = new \XeroPHP\Application($tokenObj, $tenants[0]->tenantId);
$contact = new Contact($xero);
$contact->setName('Hassan Raza')
->setAccountNumber('0245541574185741')
->setContactID('852986')
->setGUID('52552548-5585-8715-8888-871222554154')
->setBankAccountDetail('0245541574185741')
->setTaxNumber('55545352')
->setContactStatus('ACTIVE')
->setSkypeUserName('hassan_raza2010')
->setTrackingCategoryName('Manager')
->setFirstName('Hassan')
->setLastName('Raza')
->setEmailAddress('hassan#xero.com');
$response = $contact->save();
dd($response->getResponseBody());

How do I fix 'type '() => T' is not a subtype of type 'T' in type cast'

am manually setting up a model class with json (de)serialization. By now I have implemented some testcases. In particular one where I check if toJson -> fromJson is the identity for my model type called Session.
Here is the relevant part of my model type:
class Session extends Equatable {
final List<User> audience;
/* ... */
Session.fromJson(Map<String, dynamic> json) :
/* ... */
audience = (json['audience'] as List).map(((it) =>
User.fromMap(it))).toList();
Map<String, dynamic> toJson() => {
/* ... */
'audience': audience.map((it) => it.toJson()).toList()
};
}
These are the types in the audience field:
class User extends Equatable {
factory User.fromJson(Map<String, dynamic> json) {
if (_isRegisteredUserJson(json)) {
return RegisteredUser.fromMap(json);
} else {
return User(id: json['id']);
}
}
/* ... */
}
class RegisteredUser extends User {/* ... */}
In my test I set up the audience field (using the faker library) like so:
User _user() => User(id: faker.guid.guid());
RegisteredUser _registeredUser() => RegisteredUser(
id: faker.guid.guid(),
alias: faker.person.name(),
email: faker.internet.email());
Session _session => Session(
audience: faker.randomGenerator
.amount((n) => n % 3 == 0 ? _registeredUser() : _user, 100)
.cast<User>()
/* ... */
);
I expect the audience List to contain only elements of type User or RegisteredUser after toJson() returns. Instead I get A List containing either RegisteredUsers or _Closure: () => 'User from Function' which I am not exactly sure about what that is.
As a result I get the following Error Message for my test:
00:00 +4 -1: toJson -> fromJson is identity for Session [E]
type '() => User' is not a subtype of type 'User' in type cast
dart:_internal/cast.dart 99:46 _CastListBase.[]
dart:collection/list.dart 60:33 __CastListBase&_CastIterableBase&ListMixin.elementAt
dart:_internal/iterable.dart 414:40 MappedListIterable.elementAt
dart:_internal/iterable.dart 219:19 ListIterable.toList
package:feedback/model/base_module.dart 42:54 BaseModule.toJson
package:feedback/model/session.dart 51:23 Session.toJson
test/json_test.dart 34:47 main.<fn>.<fn>
package:test_api/src/backend/declarer.dart 168:27 Declarer.test.<fn>.<fn>.<fn>
===== asynchronous gap ===========================
dart:async/future_impl.dart 22:43 _Completer.completeError
dart:async/runtime/libasync_patch.dart 40:18 _AsyncAwaitCompleter.completeError
package:test_api/src/backend/declarer.dart Declarer.test.<fn>.<fn>.<fn>
===== asynchronous gap ===========================
dart:async/zone.dart 1053:19 _CustomZone.registerUnaryCallback
dart:async/runtime/libasync_patch.dart 77:23 _asyncThenWrapperHelper
package:test_api/src/backend/declarer.dart Declarer.test.<fn>.<fn>.<fn>
package:test_api/src/backend/invoker.dart 250:15 Invoker.waitForOutstandingCallbacks.<fn>
===== asynchronous gap ===========================
dart:async/zone.dart 1045:19 _CustomZone.registerCallback
dart:async/zone.dart 962:22 _CustomZone.bindCallbackGuarded
dart:async/timer.dart 52:45 new Timer
dart:async/timer.dart 87:9 Timer.run
dart:async/future.dart 174:11 new Future
package:test_api/src/backend/invoker.dart 399:21 Invoker._onRun.<fn>.<fn>.<fn>
00:00 +4 -1: Some tests failed.
Unhandled exception:
Dummy exception to set exit code.
#0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1112:29)
#1 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#2 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#3 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:391:30)
#4 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#5 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
Thanks to Jordan Davies, here is the answer:
In the method call _user I accidentally omitted the brackets and therefore passed a function as parameter where I wanted the result of that function.

blockcypher api generate multisig address

I want create multisig address on blockcypher api. pubkeys array is required.
$pubkeys = array(
"02c716d071a76cbf0d29c29cacfec76e0ef8116b37389fb7a3e76d6d32cf59f4d3",
"033ef4d5165637d99b673bcdbb7ead359cee6afd7aaf78d3da9d2392ee4102c8ea",
"022b8934cc41e76cb4286b9f3ed57e2d27798395b04dd23711981a77dc216df8ca"
);
But I don't know, how can I create these keys.
For generate public keys you can use bitcore-lib.
For example if you want use HD keys:
const HdPrivate = require('bitcore-lib').HDPrivateKey;
const HdPublic = require('bitcore-lib').HDPublicKey;
const root = new HdPrivate();
function newPublic(root, depth){
//return the public key at depth
return root.derive(depth).publicKey.toString();
}
const publicKey = newPublic(root, 'm/1');
Of course for you must save and keep secret root.

TYPO3 6.2 - how to create FileReference in frontend (FE)?

I have the hypothetical Zoo extension in which I've Animal model with photo field and FrontEnd (FE) plugin with typical CRUD actions. photo field is typical FAL's FileReference and it works perfectly in backend (BE) with common TCA IRRE config.
I'm able to successful upload the file to the storage, it's visible in the Filelist module, and I can use it in BE during my Animal editing, anyway I can't create FileReference within my FE plugin.
My current approach looks like this:
/**
* #param \Zoo\Zoo\Domain\Model\Animal $animal
*/
public function updateAction(\Zoo\Zoo\Domain\Model\Animal $animal) {
// It reads proper uploaded `photo` from form's $_FILES
$file = $this->getFromFILES('tx_zoo_animal', 'photo');
if ($file && is_array($file) && $file['error'] == 0) {
/** #type $storageRepository \TYPO3\CMS\Core\Resource\StorageRepository */
$storageRepository = GeneralUtility::makeInstance('\TYPO3\CMS\Core\Resource\StorageRepository');
$storage = $storageRepository->findByUid(5); // TODO: make target storage configurable
// This adds uploaded file to the storage perfectly
$fileObject = $storage->addFile($file['tmp_name'], $storage->getRootLevelFolder(), $file['name']);
// Here I stuck... below line doesn't work (throws Exception no. 1 :/)
// It's 'cause $fileObject is type of FileInterface and FileReference is required
$animal->addPhoto($fileObject);
}
$this->animalRepository->update($animal);
$this->redirect('list');
}
anyway attempt to create reference by this line throws exception:
$animal->addPhoto($fileObject);
How can I resolve this?
Checked: DataHandler approach (link) won't work also, as it's unavailable for FE users.
TL;DR
How to add FileReference to Animal model from existing (just created) FAL record?
You need to do several things. This issue on forge is where I got the info, and some stuff is taken out of Helmut Hummels frontend upload example (and the accompanying blogpost) which #derhansen already commented.
I'm not entirely sure if this is everything you need, so feel free to add things. This does not use a TypeConverter, which you should probably do. That would open further possibilities, for example it would be easily possible to implement deletion and replacement of file references.
You need to:
Create a FAL file reference object from the File object. This can be done using FALs resource factory.
Wrap it in a \TYPO3\CMS\Extbase\Domain\Model\FileReference (method ->setOriginalResource)
EDIT: This step is unnecessary as of TYPO3 6.2.11 and 7.2, you can directly use the class \TYPO3\CMS\Extbase\Domain\Model\FileReference.
But, because the extbase model misses a field ($uidLocal) in 6.2.10rc1, that won't work. You need to inherit from the extbase model, add that field, and fill it. Don't forget to add a mapping in TypoScript to map your own model to sys_file_reference.
config.tx_extbase.persistence.classes.Zoo\Zoo\Domain\Model\FileReference.mapping.tableName = sys_file_reference
The class would look like this (taken from the forge issue):
class FileReference extends \TYPO3\CMS\Extbase\Domain\Model\FileReference {
/**
* We need this property so that the Extbase persistence can properly persist the object
*
* #var integer
*/
protected $uidLocal;
/**
* #param \TYPO3\CMS\Core\Resource\ResourceInterface $originalResource
*/
public function setOriginalResource(\TYPO3\CMS\Core\Resource\ResourceInterface $originalResource) {
$this->originalResource = $originalResource;
$this->uidLocal = (int)$originalResource->getUid();
}
}
Add this to the TCA of the image field, in the config-section (adapt to your table and field names of course):
'foreign_match_fields' => array(
'fieldname' => 'photo',
'tablenames' => 'tx_zoo_domain_model_animal',
'table_local' => 'sys_file',
),
EDIT: Use \TYPO3\CMS\Extbase\Domain\Model\FileReference in this step if on TYPO3 6.2.11 or 7.2 or above.
So at the end add the created $fileRef instead of $fileObject
$fileRef = GeneralUtility::makeInstance('\Zoo\Zoo\Domain\Model\FileReference');
$fileRef->setOriginalResource($fileObject);
$animal->addPhoto($fileRef);
Don't tell anyone what you have done.
Here is the complete function to upload file in TYPO3 using FAL and create filereference
/**
* Function to upload file and create file reference
*
* #var array $fileData
* #var mixed $obj foreing model object
*
* #return void
*/
private function uploadAndCreateFileReference($fileData, $obj) {
$storageUid = 2;
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
//Adding file to storage
$storage = $resourceFactory->getStorageObject($storageUid);
if (!is_object($storage)) {
$storage = $resourceFactory->getDefaultStorage();
}
$file = $storage->addFile(
$fileData['tmp_name'],
$storage->getRootLevelFolder(),
$fileData['name']
);
//Creating file reference
$newId = uniqid('NEW_');
$data = [];
$data['sys_file_reference'][$newId] = [
'table_local' => 'sys_file',
'uid_local' => $file->getUid(),
'tablenames' => 'tx_imageupload_domain_model_upload', //foreign table name
'uid_foreign' => $obj->getUid(),
'fieldname' => 'image', //field name of foreign table
'pid' => $obj->getPid(),
];
$data['tx_imageupload_domain_model_upload'][$obj->getUid()] = [
'image' => $newId,
];
$dataHandler = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
'TYPO3\CMS\Core\DataHandling\DataHandler'
);
$dataHandler->start($data, []);
}
where $filedata =
$this->request->getArgument('file_input_field_name');
And
$obj = //Object of your model for which you are creating file
reference
This example does not deserve a beauty prize but it might help you. It works in 7.6.x
private function uploadLogo(){
$file['name'] = $_FILES['logo']['name'];
$file['type'] = $_FILES['logo']['type'];
$file['tmp_name'] = $_FILES['logo']['tmp_name'];
$file['size'] = $_FILES['logo']['size'];
// Store the image
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
$storage = $resourceFactory->getDefaultStorage();
$saveFolder = $storage->getFolder('logo-companies/');
$newFile = $storage->addFile(
$file['tmp_name'],
$saveFolder,
$file['name']
);
// remove earlier refereces
$GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_file_reference', 'uid_foreign = '. $this->getCurrentUserCompanyID());
$addressRecord = $this->getUserCompanyAddressRecord();
// Create new reference
$data = array(
'table_local' => 'sys_file',
'uid_local' => $newFile->getUid(),
'tablenames' => 'tt_address',
'uid_foreign' => $addressRecord['uid'],
'fieldname' => 'image',
'pid' => $addressRecord['pid']
);
$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $data);
$newId = $GLOBALS['TYPO3_DB']->sql_insert_id();
$where = "tt_address.uid = ".$addressRecord['uid'];
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tt_address', $where, array('image' => $newId ));
}

symfony setPostValidator with sfValidatorFile

I am going through an issue to setup a file upload validator on callback.
I want to achieve this:
I have a form, where user choose the type of the file they are uploading and upload the file.
So I want to set the validator to handle images in case they chose "img" as type, and pdf if they chose "pdf".
Moreover I want to specify the mime type and path and validatedFileClass according to the type.
I tried this.. but i can't get it to work
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'validateUploadedFiles')))
);
the function:
public function validateUploadedFiles($form_validator, $values){
$this_year = date("Y");
$this_month = date("m");
$basic_validator = array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').'restaurant/media/'.$this_year.'/'.$this_month.'/'
);
$doc_validator = $video_validator = $img_validator = $pdf_validator = $basic_validator;
$pdf_validator['mime_types'] = array ('application/pdf');
$doc_validator['mime_types'] = array ('application/msword', 'application/vnd.openxmlformats');
$img_validator['mime_types'] = 'web_images';
//$img_validator['validated_file_class'] = 'imgHandling';
$video_validator['mime_types'] = array('video/mpeg', 'video/3gpp', 'video/mp4', 'video/quicktime');
switch( $values['type'] ):
case 'pdf' : $validator = $pdf_validator; break;
case 'img' : $validator = $img_validator; break;
case 'word' : $validator = $doc_validator; break;
case 'video' : $validator = $video_validator; break;
endswitch;
//$form->getValidatorSchema()->offsetUnset('url') ;
//print_r($validator_fields);
$validator = new sfValidatorFile( $validator );
$validator_schema = new sfValidatorSchema();
$validator_schema->offsetSet('url', $validator);
//$validator_fields = $form->getValidatorSchema()->getFields();
$schema = parent::getValidatorSchema();
$schema->offsetUnset('url') ;
$schema->offsetSet('url', $validator);
// $path = sfConfig::get('sf_upload_dir').'restaurant/media/'.$this_year.'/'.$this_month.'/';
// $values['url'] = new sfValidatedFile( $values['url']['name'], $values['url']['type'], $values['url']['tmp_name'], $values['url']['size'] , $path);
//TODO get this url value run through the new added validator
//$values['url'] = $validator_schema->clean(array( 'url' => $values['url'] ));
return $values;
}
the problem i am facing is that , this function receives the url value as array, and even if I update the validators schema, it's not validating the url and keeps on sending it as array to the object saving method.
So how to make something like
url.validateFile() from inside this function
Not sure about the best solution, but I'd prefer to split validation process into 2 parts:
Validate mime type
If mime is ok, then validate URL
Or vise versa, your choice.
The glue would be sfValidatorAnd.
Did I understand you right?