Bitpay\Client\Client::createToken PHP Method

createToken() public method

public createToken ( array $payload = [] )
$payload array
    public function createToken(array $payload = array())
    {
        if (isset($payload['pairingCode']) && 1 !== preg_match('/^[a-zA-Z0-9]{7}$/', $payload['pairingCode'])) {
            throw new ArgumentException("pairing code is not legal");
        }
        $this->request = $this->createNewRequest();
        $this->request->setMethod(Request::METHOD_POST);
        $this->request->setPath('tokens');
        $payload['guid'] = Util::guid();
        $this->request->setBody(json_encode($payload));
        $this->response = $this->sendRequest($this->request);
        $body = json_decode($this->response->getBody(), true);
        if (isset($body['error'])) {
            throw new \Bitpay\Client\BitpayException($this->response->getStatusCode() . ": " . $body['error']);
        }
        $tkn = $body['data'][0];
        $createdAt = new \DateTime();
        $pairingExpiration = new \DateTime();
        $token = new \Bitpay\Token();
        $token->setPolicies($tkn['policies'])->setToken($tkn['token'])->setFacade($tkn['facade'])->setCreatedAt($createdAt->setTimestamp(floor($tkn['dateCreated'] / 1000)));
        if (isset($tkn['resource'])) {
            $token->setResource($tkn['resource']);
        }
        if (isset($tkn['pairingCode'])) {
            $token->setPairingCode($tkn['pairingCode']);
            $token->setPairingExpiration($pairingExpiration->setTimestamp(floor($tkn['pairingExpiration'] / 1000)));
        }
        return $token;
    }

Usage Example

 public function pairTokens($pairingCode)
 {
     $storageEngine = new Bitpay\Storage\FilesystemStorage();
     if (_BIT_PAY_PRODUCTION_) {
         $privateKey = $storageEngine->load('/tmp/bitpay.pri');
         $publicKey = $storageEngine->load('/tmp/bitpay.pub');
     } else {
         $privateKey = $storageEngine->load('/tmp/bitpaydev.pri');
         $publicKey = $storageEngine->load('/tmp/bitpaydev.pub');
     }
     $sin = Bitpay\SinKey::create()->setPublicKey($publicKey)->generate();
     $client = new Bitpay\Client\Client();
     if (_BIT_PAY_PRODUCTION_) {
         $network = new Bitpay\Network\Livenet();
     } else {
         $network = new Bitpay\Network\Testnet();
     }
     $adapter = new Bitpay\Client\Adapter\CurlAdapter();
     $client->setPrivateKey($privateKey);
     $client->setPublicKey($publicKey);
     $client->setNetwork($network);
     $client->setAdapter($adapter);
     $token = $client->createToken(array('pairingCode' => $pairingCode, 'label' => 'Auto-CMS', 'id' => (string) $sin));
     $persistThisValue = $token->getToken();
     return array('Token' => $persistThisValue);
 }