1+ <?php
2+
3+ use BitPayKeyUtils \KeyHelper \PrivateKey ;
4+ use BitPayKeyUtils \Storage \EncryptedFilesystemStorage ;
5+
6+ require __DIR__ . '/vendor/autoload.php ' ;
7+
8+ /**
9+ * Generate new private key for every new merchant.
10+ * Make sure you provide an easy recognizable name for each private key/Merchant
11+ *
12+ * WARNING: It is EXTREMELY IMPORTANT to place this key files in a very SECURE location
13+ **/
14+ $ privateKey = new PrivateKey (__DIR__ . '/secure/SecurePathPlusYourClientName.key ' );
15+ $ storageEngine = new EncryptedFilesystemStorage ('YourMasterPassword ' );
16+
17+ try {
18+ // Use the EncryptedFilesystemStorage to load the Merchant's encrypted private key with the Master Password.
19+ $ privateKey = $ storageEngine ->load (__DIR__ . '/secure/SecurePathPlusYourClientName.key ' );
20+ } catch (Exception $ ex ) {
21+ // Check if the loaded keys is a valid key
22+ if (!$ privateKey ->isValid ()) {
23+ $ privateKey ->generate ();
24+ }
25+
26+ // Encrypt and store it securely.
27+ // This Master password could be one for all keys or a different one for each merchant
28+ $ storageEngine ->persist ($ privateKey );
29+ }
30+
31+ /**
32+ * Generate the public key from the private key every time (no need to store the public key).
33+ **/
34+ try {
35+ $ publicKey = $ privateKey ->getPublicKey ();
36+ } catch (Exception $ ex ) {
37+ echo $ ex ->getMessage ();
38+ }
39+
40+ /**
41+ * Derive the SIN from the public key.
42+ **/
43+ $ sin = $ publicKey ->getSin ()->__toString ();
44+
45+ /**
46+ * Use the SIN to request a pairing code and token.
47+ * The pairing code has to be approved in the BitPay Dashboard
48+ * THIS is just a cUrl example, which explains how to use the key pair for signing requests
49+ **/
50+ $ resourceUrl = 'https://test.bitpay.com/tokens ' ;
51+
52+ $ facade = 'merchant ' ;
53+
54+ $ postData = json_encode ([
55+ 'id ' => $ sin ,
56+ 'facade ' => $ facade
57+ ]);
58+
59+ $ curlCli = curl_init ($ resourceUrl );
60+
61+ curl_setopt ($ curlCli , CURLOPT_HTTPHEADER , [
62+ 'x-accept-version: 2.0.0 ' ,
63+ 'Content-Type: application/json ' ,
64+ 'x-identity ' => $ publicKey ->__toString (),
65+ 'x-signature ' => $ privateKey ->sign ($ resourceUrl . $ postData ),
66+ ]);
67+
68+ curl_setopt ($ curlCli , CURLOPT_CUSTOMREQUEST , 'POST ' );
69+ curl_setopt ($ curlCli , CURLOPT_POSTFIELDS , stripslashes ($ postData ));
70+ curl_setopt ($ curlCli , CURLOPT_RETURNTRANSFER , true );
71+
72+ $ result = curl_exec ($ curlCli );
73+ $ resultData = json_decode ($ result , TRUE );
74+ curl_close ($ curlCli );
75+
76+ if (array_key_exists ('error ' , $ resultData )) {
77+ echo $ resultData ['error ' ];
78+ exit ;
79+ }
80+
81+ /**
82+ * Example of a pairing Code returned from the BitPay API
83+ * which needs to be APPROVED on the BitPay Dashboard before being able to use it.
84+ **/
85+ echo $ resultData ['data ' ][0 ]['pairingCode ' ];
86+
87+ /** End of request **/
0 commit comments