Skip to content

Commit

Permalink
(#10): fix all calls
Browse files Browse the repository at this point in the history
  • Loading branch information
ipinak committed Feb 4, 2023
1 parent a3cb8f9 commit d1093a2
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 35 deletions.
25 changes: 15 additions & 10 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,30 +58,32 @@ func (c Client) Authenticate() (*TokenResponse, error) {
// AuthToken returns the token value
func (c Client) AuthToken() string {
c.lock.RLock()
defer c.lock.RUnlock()

t := c.tokenValue.value

c.lock.RUnlock()
return t
}

// SetToken sets the token value and the expiration time of the token.
func (c Client) SetToken(tokenValue string, expires time.Time) {
func (c Client) SetToken(value string, expires time.Time) {
c.lock.Lock()
defer c.lock.Unlock()

c.tokenValue = token{
value: tokenValue,
expires: expires,
}
c.tokenValue.value = value
c.tokenValue.expires = expires

c.lock.Unlock()
}

// HasAuthExpired returns true if the expiry time of the token has passed and false
// otherwise.
func (c Client) HasAuthExpired() bool {
c.lock.RLock()
defer c.lock.RUnlock()

expires := c.tokenValue.expires

c.lock.RUnlock()

now := time.Now()
return now.After(expires)
}
Expand All @@ -91,6 +93,11 @@ func AuthBody(c Config) string {
return base64.StdEncoding.EncodeToString([]byte(auth))
}

func BasicAuth(c Config) string {
auth := fmt.Sprintf("%s:%s", c.MerchantID, c.APIKey)
return base64.StdEncoding.EncodeToString([]byte(auth))
}

func (c Client) tokenEndpoint() string {
return fmt.Sprintf("%s/%s", c.authUri(), "/connect/token")
}
Expand All @@ -101,5 +108,3 @@ func (c Client) authUri() string {
}
return "https://accounts.vivapayments.com"
}


32 changes: 24 additions & 8 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,36 @@ import (
)

func main() {
clientID := ""
clientSecret := ""
client := vivawallet.New(clientID, clientSecret, true)
clientID := "yjp82d6eub7hva6y9usesqtuzd8ambj914odu50n49jz3.apps.vivapayments.com"
clientSecret := "ODX4vwQVmeYo373814yYf2p6Vq85yR"
merchantID := "393969b6-c18e-4770-ba9a-2838c2beafee"
apiKey := "YZ}z>_"
client := vivawallet.New(clientID, clientSecret, merchantID, apiKey, true)

token, err := client.Authenticate()
if err != nil {
fmt.Printf("Error: %s", err.Error())
fmt.Printf("Error: %s\n", err.Error())
return
}
fmt.Printf("Token: %s\n", token.AccessToken)
fmt.Printf("Token: %s\n\n", token.AccessToken)

req := vivawallet.CheckoutOrderRequest{
req := vivawallet.CheckoutOrder{
Amount: 1000,
}
op, _ := client.CreateOrderPayment(req)
fmt.Printf("OrderPayment: %d\n", op.OrderCode)
op, err2 := client.CreateOrderPayment(req)
if err2 != nil {
fmt.Printf("err: %s\n", err2.Error())
} else {
fmt.Printf("OrderPayment: %d\n", op.OrderCode)
}

wallets, err3 := client.GetWallets()
if err3 != nil {
fmt.Printf("err: %s\n", err3.Error())
} else {
for _, w := range wallets {
fmt.Printf("Wallet: %v\n", w)
}
}

}
8 changes: 4 additions & 4 deletions order_payments.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

type CheckoutOrder struct {
Amount int64 `json:"amount"`
CustomerTransactions string `json:"customerTrns"`
CustomerTransactions string `json:"customerTrns,omitempty"`
Customer struct {
Email string `json:"email,omitempty"`
FullName string `json:"fullName,omitempty"`
Expand Down Expand Up @@ -38,7 +38,7 @@ type CheckoutOrderResponse struct {

// CreateOrderPayment creates a new order payment and returns the `orderCode`.
func (c Client) CreateOrderPayment(payload CheckoutOrder) (*CheckoutOrderResponse, error) {
uri := checkoutEndpoint(c.Config)
uri := checkoutOrderUri(c.Config)
data, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to parse order %s", err)
Expand Down Expand Up @@ -76,6 +76,6 @@ func (c Client) CreateOrderPayment(payload CheckoutOrder) (*CheckoutOrderRespons
return response, nil
}

func checkoutEndpoint(c Config) string {
return fmt.Sprintf("%s/%s", ApiUri(c), "checkout/v2/orders")
func checkoutOrderUri(c Config) string {
return fmt.Sprintf("%s/checkout/v2/orders", ApiUri(c))
}
11 changes: 8 additions & 3 deletions viva_wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ type Config struct {
Demo bool
ClientID string
ClientSecret string
MerchantID string
APIKey string
}

type token struct {
Expand All @@ -20,8 +22,8 @@ type token struct {
type Client struct {
Config Config
HTTPClient *http.Client
lock *sync.RWMutex
tokenValue token
lock sync.RWMutex
tokenValue *token
}

// defaultHTTPTimeout is the default timeout on the http.Client used by the library.
Expand All @@ -32,14 +34,17 @@ var httpClient = &http.Client{
}

// New creates a new viva client
func New(clientID string, clientSecret string, demo bool) *Client {
func New(clientID string, clientSecret string, merchantID string, apiKey string, demo bool) *Client {
return &Client{
Config: Config{
Demo: demo,
ClientID: clientID,
ClientSecret: clientSecret,
MerchantID: merchantID,
APIKey: apiKey,
},
HTTPClient: httpClient,
tokenValue: &token{},
}
}

Expand Down
20 changes: 10 additions & 10 deletions wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type BalanceTransferResponse struct {
}

func (c Client) BalanceTranfer(walletID string, targetWalletID string, payload BalanceTransfer) (*BalanceTransferResponse, error) {
auth := AuthBody(c.Config)
auth := BasicAuth(c.Config)

uri := getBalanceTransferUri(c.Config, walletID, targetWalletID)
data, err := json.Marshal(payload)
Expand Down Expand Up @@ -61,19 +61,19 @@ func getWalletsUri(c Config) string {
return fmt.Sprintf("%s/api/wallets", AppUri(c))
}

type GetWalletResponse struct {
type Wallet struct {
IBAN string `json:"Iban"`
WalletID string `json:"WalletId"`
WalletID int `json:"WalletId"`
IsPrimary bool `json:"IsPrimary"`
Amount float64 `json:"Amount"`
Available float64 `json:"Available"`
Overdraft float64 `json:"Overdraft"`
FriendlyName string `json:"FriendlyName"`
CurrencyCode int `json:"CurrencyCode"`
CurrencyCode string `json:"CurrencyCode"`
}

func (c Client) RetrieveWallet() (*GetWalletResponse, error) {
auth := AuthBody(c.Config)
func (c Client) GetWallets() ([]Wallet, error) {
auth := BasicAuth(c.Config)

uri := getWalletsUri(c.Config)

Expand All @@ -83,20 +83,20 @@ func (c Client) RetrieveWallet() (*GetWalletResponse, error) {

resp, httpErr := c.HTTPClient.Do(req)
if httpErr != nil {
return nil, fmt.Errorf("failed to get wallets %s", httpErr)
return nil, fmt.Errorf("failed to get wallet %s", httpErr)
}

if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to get wallets with status %d", resp.StatusCode)
return nil, fmt.Errorf("failed to get wallet with status %d", resp.StatusCode)
}

body, bodyErr := io.ReadAll(resp.Body)
if bodyErr != nil {
return nil, bodyErr
}

r := &GetWalletResponse{}
if jsonErr := json.Unmarshal(body, r); jsonErr != nil {
var r []Wallet
if jsonErr := json.Unmarshal(body, &r); jsonErr != nil {
return nil, jsonErr
}
return r, nil
Expand Down

0 comments on commit d1093a2

Please sign in to comment.