# Walkthrough

## Traffic Authentication <a href="#guide-walkthrough-trafficauthentication" id="guide-walkthrough-trafficauthentication"></a>

The Authorization Service requires the Basic Token in the header while the Transaction, Customer and Plan Services require a Bearer Token. All requests to the Authorization Service will need to point to the root endpoint or url [https://auth.payfirma.com](https://auth.payfirma.com/) and requests to the other services will be addressed to [https://apigateway.payfirma.com](https://apigateway.payfirma.com/).

### Get your Bearer Token <a href="#guide-walkthrough-getyourbearertoken" id="guide-walkthrough-getyourbearertoken"></a>

Step 1. Get your Client ID & Client Secret from your PayHQ account by going to Settings – eCommerce.

Step 2. Using Base64 encoding, combine the Client ID & Client Secret together with a colon in between to acquire your Basic Token for your header.

Step 3. Use your Basic Token with your Client ID and Client Secret to get your Bearer Token from the Client Credentials Grant.

Step 4. Set up a recurring request to get your Bearer Token based on the validity timeframe that you set for your Client ID & Client Secret. The default validity that we recommend is 12 hours. This can be changed in Settings - eCommerce when you create or edit a Client ID and Client Secret.

```
Step 3. 
curl https://auth.payfirma.com/oauth/token  
--request POST  
--header "Content-Type: application/x-www-form-urlencoded"  
--header "Authorization: Basic {BASIC_TOKEN}"  
--data "grant_type=client_credentials&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}" 
```

### Get your Merchants Bearer Token <a href="#guide-walkthrough-getyourmerchantsbearertoken" id="guide-walkthrough-getyourmerchantsbearertoken"></a>

Step 1. Set up your Partner OAuth flow with PayHQ by sending us your selected business name, an image url for your business with a square format, and the callback URI to your Merrco or Payfirma point of contact.

Step 2. Set up an invokable [Authorization function](/api/authorization.md#api-authorization-authorization) in your application to get the short-lived authorization code when your Merchants complete the sign-in and authorization process.

Step 3. Make an [Authorization Code Grant](/api/authorization.md#api-authorization-authorizationcodegrant) request with the Authorization code from Step 2

Step 4. Store the Bearer and Refresh Tokens for each Merchant

Step 5. Use the [Token Refresh Grant](/api/authorization.md#api-authorization-refreshtokengrant) to request a new Access Token either based of receiving a 401 error for an invalid token, or based off the time validity of the Bearer Token. Please note that Bearer Tokens are valid for 12 hours and the Refresh Token can only be used to refresh the Bearer token once with a new Refresh token provided with a successful Refresh Token Grant request.

```
Step 3. 
curl https://auth.payfirma.com/oauth/token?grant_type=authorization_code&code=Grf5pV&redirect_uri=https%3A%2F%2Fwww.example.com&state=xyzABC123  
--request POST  
--header "Content-Type: application/x-www-form-urlencoded"  
--header "Authorization: Basic {BASIC_TOKEN}"  
Step 4. 
{"access_token":"{BEARER_TOKEN}","token_type": "Bearer","refresh_token": "955d8714-f1d6-49d6-830a-2d221631a2b3", "expires_in": 1199, "merchant_id": "01234abcde", "scope": "invoice ecom"}
Step 5. 
curl https://auth.payfirma.com/oauth/token?grant_type=refresh_token&refresh_token=41c128f2-b2e2-4d85-9443-b6e37d02a482&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}   
--request POST  
--header "Content-Type: application/x-www-form-urlencoded" 
```

## Simple Transactions <a href="#guide-walkthrough-simpletransactions" id="guide-walkthrough-simpletransactions"></a>

[Sales](/api/transaction.md#api-transaction-sale) and [Authorizations](/api/transaction.md#api-transaction-authorize) can be completed on their own, while a [Capture](/api/transaction.md#api-transaction-capture) transaction requires an [Authorization](https://developers.payfirma.com/api-reference#authorize) transaction and a Refund requires either a [Sale](https://developers.payfirma.com/api-reference#sale) or [Capture](https://developers.payfirma.com/api-reference#capture-transaction).

### Charge a card <a href="#guide-walkthrough-chargeacard" id="guide-walkthrough-chargeacard"></a>

​Step 1. Use the [Bearer Token](/guide/walkthrough.md#guide-walkthrough-getyourbearertoken) ​as your Authorization header and make sure to provide all the card parameters required for a regular sale transaction along with the different request URL.

```
curl https://apigateway.payfirma.com/transaction-service/sale  
--request POST 
--header "Content-Type: application/json" 
--header "Authorization: Bearer{BEARER_TOKEN}"
--data "{ 
           "amount": 10.99,
           "currency": "CAD",
           "card_expiry_month": 11,
           "card_expiry_year":16,
           "card_number": "4111111111111111",
           "cvv2": 595
         }"
```

### Authorize a hold and then capture the payment <a href="#guide-walkthrough-authorizeaholdandthencapturethepayment" id="guide-walkthrough-authorizeaholdandthencapturethepayment"></a>

Step 1. Use the Bearer Token as your Authorization header and make sure to provide all the card parameters required for a regular sale transaction along with the different request URL. The hold will stay on the card for between 5-30 business days depending on the policy of the cardholder’s bank.

Step 2. Use the ID field from the transaction response to finalize the payment and request funds. You will still be able to request a payment even if the hold has expired, but you run the risk of the funds not being available for the payment.

```
Step 1
curl https://apigateway.payfirma.com/transaction-service/authorize 
--request POST 
--header "Content-Type: application/json" 
--header "Authorization: Bearer {BEARER_TOKEN}" 
--data "{
           "amount": 10.99,
           "currency": "CAD",
           "card_expiry_month": 11,
           "card_expiry_year": 16,
           "card_number":"4111111111111111",
           "cvv2": 595
         }"
Step 2
curl https://apigateway.payfirma.com/transaction-service/capture/{ID} 
--request POST 
--header "Content-Type: application/json" 
--header "Authorization: Bearer {BEARER_TOKEN}" 
--data "{"amount": 10.99,}"
```

### Refund a payment <a href="#guide-walkthrough-refundapayment" id="guide-walkthrough-refundapayment"></a>

Option 1. Log into PayHQ and select My Transactions to view the complete list of transaction available for review. With each transaction, you have the control to refund the transaction and send a receipt for the refund to the email of your preference.

Option 2. Build the API request to ask for a refund by using the ID from the original sale or capture transaction. Authorization transactions cannot be refunded because no funds have been requested or transferred.

```
curl " https://apigateway.payfirma.com/transaction-service/refund/{ID} " 
--header "Content-Type: application/json" 
--header "Authorization: Bearer {BEARER_TOKEN}"
--data "{"amount": 10.99,}"
curl 
--include     
--request POST      
--header "Content-Type: application/json"     
--header "Authorization: Bearer {BEARER_TOKEN}"      
--data-binary "{ "amount": 10.99,  "test_mode": true}" 
"https://apigateway.payfirma.com/transaction-service/refund/1234567"
```

### Encrypt credit card as a token <a href="#guide-walkthrough-encryptcreditcardasatoken" id="guide-walkthrough-encryptcreditcardasatoken"></a>

The [Payfirma Card Encryption](https://www.payfirma.com/payfirma-card-encryption-min.js) Javascript library generates a secure and encrypted card token to be used with any of our transaction methods.<br>

### How to use this library <a href="#guide-walkthrough-howtousethislibrary" id="guide-walkthrough-howtousethislibrary"></a>

This library was developed specifically for client use.

Within your HTML page, include the following inside the head tab. Alternatively, you can import/require the script from your code base.

```
src="https://www.payfirma.com/payfirma-card-encryption-min.js"
```

You can access and reference the library from inside your Javascript file.

```
let PayfirmaCardEncryption = window.PayfirmaCardEncryption;
```

Your public encryption key requires to be sent as an alphanumeric string.

```
let publicEncryptionKey = "2d2d2d2d2d424547494e205055424c4943204b45592d2d2";
```

Make sure all your card parameters are sent as numeric strings. Numbers or objects will not be accepted.

```
let cardNumber = "1234567890123456";
let cardMonth = "12";
let cardYear = "34";
let cardCvv2 = "123"
```

Generate an encoded token using the the encode function. It requires **Public Encryption Key**, **Card Number**, **Card Month**, **Card Year**, **CVV2** as parameters.

```
let encryptedCard = PayfirmaCardEncryption(publicEncryptionKey, cardNumber, cardMonth, cardYear, cardCvv2);
```

Use the encoded token within the body of your transaction request.

```
let transactionObject = {
amount: 1.00,
currency: "CAD",
token: encryptedCard,
email: "goku.son@payfirma.com",
first_name: "Goku",
last_name: "Son",
company: "Capsule Corporation",
telephone: "123-456-7890"
};
```

Post your first transaction!

```
let request = new XMLHttpRequest();
request.open("POST", "https://apigateway.payfirma.com/transaction-service/sale");
request.setRequestHeader("Content-Type", "application/json");
request.setRequestHeader("Authorization", bearerToken);
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log("Something went wrong");
} else {
console.log("Success!");}
};
request.send(stringifyTransaction(transactionObject));
```

Example:

```
let publicEncryptionKey = "2d2d2d2d2d424547494e205055424c4943204b45592d2d2";
let cardNumber = "1234567890123456";
let cardMonth = "01";
let cardYear = "23";
let cardCvv2 = "045"
let encryptedCard = window.PayfirmaCardEncryption(publicEncryptionKey, cardNumber, cardMonth, cardYear, cardCvv2);
let transactionObject = {
    amount: 0.01,
    currency: "CAD",
    token: encryptedCard,
    email: "goku.son@payfirma.com",
    first_name: "Goku",
    last_name: "Son",
    company: "Capsule Corporation",
    telephone: "123-456-7890"
};
```

## Future Payments <a href="#guide-walkthrough-futurepayments" id="guide-walkthrough-futurepayments"></a>

The Customer and Transaction Services can be used together to store cards and make payments on those stored cards.The Customer and Plan Services can be used together to set up recurring payment plans called subscriptions.

### Storing a credit card <a href="#guide-walkthrough-storingacreditcard" id="guide-walkthrough-storingacreditcard"></a>

Step 1. [Create a customer](/api/customer.md#api-customer-createacustomer) with all the key details that you want to store in the PayHQ database.

Step 2. Use the [Customer\_Lookup\_ID](/api/customer.md#api-customer-retrieveaspecificcustomer) for the customer you just created to save a card to that customer.

```
Step 1.
curl "https://apigateway.payfirma.com/customer-service/customer" 
--request POST  
--header "Content-Type: application/json"       
--header "Authorization: Bearer {BEARER_TOKEN}"      
--data "{  
         "email": "brandon@stark.com",  
         "first_name": "Brandon",  
         "last_name": "Stark",  
         "company": "Payfirma",  
         "bcc_emails": "john.snow@stark.com",  
         "telephone": "1234567891",  
         "address1": "No. 1 Road",  
         "address2": "Street 2",  
         "city": "Vancouver",  
         "province": "BC",  
         "country": "Canada",  
         "postal_code": "V6E 1B2", 
         "custom_id": "Internal456"}"
Step 2. 
curl "https://apigateway.payfirma.com/customer-service/customer/{CUSTOMER_LOOKUP_ID/card/"
--request POST  
--header "Content-Type: application/json"  
--header "Authorization: Bearer {BEARER_TOKEN}"  
--data {
       "card_expiry_month": 11,
       "card_expiry_year": 16,
       "card_number": "4111111111111111",
       "cvv2": "595",
       "is_default": true,
       "card_description": 
       "test card" }
```

### Making a payment on a stored card <a href="#guide-walkthrough-makingapaymentonastoredcard" id="guide-walkthrough-makingapaymentonastoredcard"></a>

Step 1. Use the [Customer\_Lookup\_ID](/api/customer.md#api-customer-retrieveaspecificcustomer) to make a payment with the default card.

Step 2. Use the Customer\_Lookup\_ID and the Card\_Lookup\_ID to make a payment with a card other than the default card stored for that customer.

```
Step 1.
curl "https://apigateway.payfirma.com/customer-service/customer/{CUSTOMER_LOOKUP_ID/card/" 
--request POST  
--header "Content-Type: application/json"      
--header "Authorization: Bearer {BEARER_TOKEN}"    
--data " {  "amount": 10.99,"currency": "CAD" }
Step 2. 
curl "https://apigateway.payfirma.com/customer-service/customer/{CUSTOMER_LOOKUP_ID/card/{CARD_LOOKUP_ID}/" 
--request POST      
--header "Content-Type: application/json"      
--header "Authorization: Bearer {BEARER_TOKEN}"      
--data " {   "amount": 10.99,"currency": "CAD"}
```

### Subscribe a customer with a stored card <a href="#guide-walkthrough-subscribeacustomerwithastoredcard" id="guide-walkthrough-subscribeacustomerwithastoredcard"></a>

Step 1. [Create a plan](/api/plan.md#api-plan-createaplan) with the key payment details.

Step 2. Make sure that you have a [saved customer with a stored card](/api/customer.md#api-customer-addanewcard).

Step 3. [Create a subscription](/api/customer.md#api-customer-subscription) based on a plan for customer with a stored card.

```
Step 1.
curl " https://apigateway.payfirma.com/plan-service/plan/"
--request POST      
--header "Content-Type: application/json"     
--header "Authorization: Bearer {BEARER_TOKEN}"      
--data " {  
"name": "Sample Daily Plan",  
"amount": 10.99,  
"currency": "CAD",  
"frequency": "DAILY",  
"number_of_payments": 10,  
"send_receipt": false 
}"
Step 3. 
curl " https://apigateway.payfirma.com/customer-service/customer/{CUSTOMER_LOOKUP_ID}/subscription "
--request POST      
--header "Content-Type: application/json"   
--data  {
"plan_lookup_id": "{PLAN_LOOKUP_ID}",
"card_lookup_id": "{CARD_LOOKUP_ID}",
"amount": 10.99,
"start_date": 1467760023000,
"email": "brandon@stark.com"
"description": "My test subscription"
} ”
```

## Reporting <a href="#guide-walkthrough-reporting" id="guide-walkthrough-reporting"></a>

Transaction reporting can be accessed through the PayHQ web application or through the PayHQ API.

### Get your transactions <a href="#guide-walkthrough-getyourtransactions" id="guide-walkthrough-getyourtransactions"></a>

Option 1. [Log into PayHQ](https://hq.payfirma.com/#/login) and select "My Transactions" to view the complete list of transaction available for review. There is also the option to export the transaction list to a .csv file.

Option 2. Build the [API call to request the full list of transactions](/api/transaction.md#api-transaction-retrievealltransactionsforaspecificaccount) according to whatever parameters you specify.

```
curl " https://apigateway.payfirma.com/transaction-service/transaction?limit=10000"  
--request POST      
--header "Authorization: Bearer {BEARER_TOKEN}"    
```

### Get your merchant's transactions <a href="#guide-walkthrough-getyourmerchantstransactions" id="guide-walkthrough-getyourmerchantstransactions"></a>

Request the [full list of transactions](/api/transaction.md#api-transaction-retrievealltransactionsforaspecificaccount) according to whatever parameters you specify and please note that the account data will be based off the Bearer token.

```
curl " https://apigateway.payfirma.com/transaction-service/transaction?limit=10000"  
--request POST      
--header "Authorization: Bearer {BEARER_TOKEN}"    
```

## Glossary <a href="#guide-walkthrough-glossary" id="guide-walkthrough-glossary"></a>

**Authorization** is a financial transaction that places a hold on the credit or debit card for the amount you specify. This hold will last 10-20 business days depending on the cardholder’s bank policy. Please see **Capture** for how to receive money from this hold. This term can also refer to the class of token for the Basic and Bearer Tokens.

**Authorization Service** the part of the API that grants access tokens to the **Transaction Service**.

**Basic Token** is an encoded version of your Client ID & Client Secret in Base64 format using UTF-8 encoding that you’ll use for most requests to the Authorization service. Use the tool of your choice and encode the Client ID & Client Secret together with a colon in between both values to get your Basic Token.

Here is an example in bash:<br>

```
echo -n "{CLIENT_ID}:{CLIENT_SECRET}" | base64
```

**Bearer Token** is a token that you’ll receive from the authorization service to use in the header for all requests to the Customer, Plan, and Transaction services. The Bearer Token lasts for 20 minutes.

**Capture** is a financial transaction that collects the payment after a hold has been placed on a credit or debit card. This transfer of funds is entirely dependent on a successful **Authorization** transaction.

**Cards** refer to the unique object that is created when you store a credit or debit card in our tokenized card vault.

**Client ID & Client Secret** are a set of unique account credentials that you generate in your PayHQ account to begin working with our API and should only be shared with team members or colleagues who are going to be working directly with your code base.

**Customer** is an object in our **Customer Service** that you create to be able to store customer information, store the **Cards** of that customer, and create **Subscriptions** on those cards.

**Customer Service** the group of API operations that allows developers to create customer objects, store sensitive card data by creating tokens and create subscription payments

**Password** is the secure, private key that you established with your PayHQ login. This field is only used for the Password Grant Operation and should be managed as privately as possible; only you or people accessing your code should have access to it.

**Plans** are payment templates that you can create with the **Plan Service** and are the base object needed for a **Subscription** payment.

**Plan Service** the set of operations used for creating recurring payment plans used to create subscription objects.

**Refund** is a reverse of a **Sale** or **Capture** transaction that will send the money from the merchant account back to the account of the cardholder.

**Sale** is the straightforward purchase transaction to charge a credit or debit card.

**Subscription** payments are created when a **Plan** is used to bill the stored **Card** of a **Customer**. **Subscriptions** do not have to be an exact copy of a **Plan** and can be updated at the time of creation as needed.

**Transaction Service** the set of transaction and reporting functions, other than subscription payments, for the API.

**Username** is the email address associated with your PayHQ login. This field is only used for the Password Grant Operation.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.payfirma.com/guide/walkthrough.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
