Skip to content
This repository has been archived by the owner on Mar 20, 2024. It is now read-only.

Commit

Permalink
Merge pull request #52 from Vonage/add-verify-psd2
Browse files Browse the repository at this point in the history
Update Verify and add PSD2 feature
  • Loading branch information
Lorna Jane Mitchell committed Nov 16, 2020
2 parents 7888b1c + 5e378b9 commit 0d04809
Show file tree
Hide file tree
Showing 21 changed files with 538 additions and 186 deletions.
32 changes: 32 additions & 0 deletions docs/examples/verify.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ permalink: examples/verify
---

* [Verify a User's Phone Number](#verify-a-users-phone-number)
* [Verify a Payment via Phone (PSD2)](#verify-a-payment-via-phone-psd2)
* [Check Verification Code](#check-verification-code)
* [Cancel a Verification](#cancel-a-verification)
* [Trigger the Next Event in a Verification](#trigger-the-next-event-in-a-verification)
Expand Down Expand Up @@ -40,6 +41,37 @@ func main() {
}
```

Copy the request ID; the user will receive a PIN code and when they have it, you can check the code (see [Check PIN Code section](#check-verification-code))

## Verify a Payment via Phone (PSD2)

Just like verifying a user's number, this is a multi-step process. First: send a code to the user alongside information about the amount and destination of the payment.

```golang
package main

import (
"fmt"

"github.com/vonage/vonage-go-sdk"
)

func main() {
auth := vonage.CreateAuthFromKeySecret(API_KEY, API_SECRET)
verifyClient := vonage.NewVerifyClient(auth)

response, errResp, err := verifyClient.Psd2("44777000777", "GoTestRetail", 45.67, vonage.VerifyPsd2Opts{})

if err != nil {
fmt.Printf("%#v\n", err)
} else if response.Status != "0" {
fmt.Println("Error status " + errResp.Status + ": " + errResp.ErrorText)
} else {
fmt.Println("Request started: " + response.RequestId)
}
}
```

Copy the request ID; the user will receive a PIN code and when they have it, you can check the code (see next section)

## Check Verification Code
Expand Down
307 changes: 178 additions & 129 deletions internal/verify/api_default.go

Large diffs are not rendered by default.

43 changes: 40 additions & 3 deletions internal/verify/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.0.11
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
Expand All @@ -18,8 +18,11 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
Expand All @@ -38,7 +41,7 @@ var (
xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
)

// APIClient manages communication with the Nexmo Verify API API v1.0.11
// APIClient manages communication with the Nexmo Verify API API v1.1.3
// In most cases there should be only one, shared, APIClient.
type APIClient struct {
cfg *Configuration
Expand Down Expand Up @@ -158,7 +161,28 @@ func parameterToJson(obj interface{}) (string, error) {

// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
return c.cfg.HTTPClient.Do(request)
if c.cfg.Debug {
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, err
}
log.Printf("\n%s\n", string(dump))
}

resp, err := c.cfg.HTTPClient.Do(request)
if err != nil {
return resp, err
}

if c.cfg.Debug {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return resp, err
}
log.Printf("\n%s\n", string(dump))
}

return resp, err
}

// ChangeBasePath changes base path to allow switching to mocks
Expand Down Expand Up @@ -326,6 +350,7 @@ func (c *APIClient) prepareRequest(
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}

}

for header, value := range c.cfg.DefaultHeader {
Expand All @@ -336,10 +361,22 @@ func (c *APIClient) prepareRequest(
}

func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
if len(b) == 0 {
return nil
}
if s, ok := v.(*string); ok {
*s = string(b)
return nil
}
if f, ok := v.(**os.File); ok {
*f, err = ioutil.TempFile("", "HttpClientFile")
if err != nil {
return
}
_, err = (*f).Write(b)
_, err = (*f).Seek(0, io.SeekStart)
return
}
if xmlCheck.MatchString(contentType) {
if err = xml.Unmarshal(b, v); err != nil {
return err
Expand Down
57 changes: 56 additions & 1 deletion internal/verify/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.0.11
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/

package verify

import (
"fmt"
"net/http"
"strings"
)

// contextKeys are used to identify the type of value in the context.
Expand All @@ -36,6 +38,7 @@ var (

// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")

)

// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
Expand All @@ -50,13 +53,30 @@ type APIKey struct {
Prefix string
}


// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}

// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
Description string
Variables map[string]ServerVariable
}

// Configuration stores the configuration of the API client
type Configuration struct {
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers []ServerConfiguration
HTTPClient *http.Client
}

Expand All @@ -66,6 +86,13 @@ func NewConfiguration() *Configuration {
BasePath: "https://api.nexmo.com/verify",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: []ServerConfiguration{
{
Url: "https://api.nexmo.com/verify",
Description: "No description provided",
},
},
}
return cfg
}
Expand All @@ -74,3 +101,31 @@ func NewConfiguration() *Configuration {
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}

// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
}
server := c.Servers[index]
url := server.Url

// go through variables and replace placeholders
for name, variable := range server.Variables {
if value, ok := variables[name]; ok {
found := bool(len(variable.EnumValues) == 0)
for _, enumValue := range variable.EnumValues {
if value == enumValue {
found = true
}
}
if !found {
return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
}
url = strings.Replace(url, "{"+name+"}", value, -1)
} else {
url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
}
}
return url, nil
}
4 changes: 2 additions & 2 deletions internal/verify/model_check_error_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.0.11
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
Expand All @@ -13,7 +13,7 @@ package verify
type CheckErrorResponse struct {
// The `request_id` that you received in the response to the Verify request and used in the Verify check request.
RequestId string `json:"request_id,omitempty"`
// Code | Text | Description -- | -- | -- 0 | Success | The request was successfully accepted by Nexmo. 1 | Throttled | You are trying to send more than the maximum of 30 requests per second. 2 | Your request is incomplete and missing the mandatory parameter `$parameter` | The stated parameter is missing. 3 | Invalid value for parameter `$parameter` | Invalid value for parameter. If you see Facility not allowed in the error text, check that you are using the correct Base URL in your request. 4 | Invalid credentials were provided | The supplied API key or secret in the request is either invalid or disabled. 5 | Internal Error | An error occurred processing this request in the Cloud Communications Platform. 6 | The Nexmo platform was unable to process this message for the following reason: `$reason` | The request could not be routed. 16 | The code inserted does not match the expected value | 17 | The wrong code was provided too many times | You can run Verify check on a specific `request_id` up to three times unless a new verification code is generated. If you check a request more than three times, it is set to FAILED and you cannot check it again. 101 | No request found | There are no matching verify requests.
// Code | Text | Description -- | -- | -- 0 | Success | The request was successfully accepted by Nexmo. 1 | Throttled | You are trying to send more than the maximum of 30 requests per second. 2 | Your request is incomplete and missing the mandatory parameter `$parameter` | The stated parameter is missing. 3 | Invalid value for parameter `$parameter` | Invalid value for parameter. If you see Facility not allowed in the error text, check that you are using the correct Base URL in your request. 4 | Invalid credentials were provided | The supplied API key or secret in the request is either invalid or disabled. 5 | Internal Error | An error occurred processing this request in the Cloud Communications Platform. 6 | The Nexmo platform was unable to process this message for the following reason: `$reason` | The request could not be routed. 16 | The code inserted does not match the expected value | 17 | The wrong code was provided too many times | You can run Verify check on a specific `request_id` up to three times unless a new verification code is generated. If you check a request more than three times, it is set to FAILED and you cannot check it again.
Status string `json:"status,omitempty"`
// If the `status` is non-zero, this explains the error encountered.
ErrorText string `json:"error_text,omitempty"`
Expand Down
24 changes: 24 additions & 0 deletions internal/verify/model_check_request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Nexmo Verify API
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/

package verify
// CheckRequest struct for CheckRequest
type CheckRequest struct {
// You can find your API key in your [account dashboard](https://dashboard.nexmo.com)
ApiKey string `json:"api_key"`
// You can find your API secret in your [account dashboard](https://dashboard.nexmo.com)
ApiSecret string `json:"api_secret"`
// The Verify request to check. This is the `request_id` you received in the response to the Verify request.
RequestId string `json:"request_id"`
// The verification code entered by your user.
Code string `json:"code"`
// (This field is no longer used)
IpAddress string `json:"ip_address,omitempty"`
}
2 changes: 1 addition & 1 deletion internal/verify/model_check_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.0.11
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
Expand Down
4 changes: 2 additions & 2 deletions internal/verify/model_control_error_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.0.11
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/

package verify
// ControlErrorResponse Error
type ControlErrorResponse struct {
// Code | Text | Description -- | -- | -- 0 | Success | The request was successfully accepted by Nexmo. 1 | Throttled | You are trying to send more than the maximum of 30 requests per second. 2 | Your request is incomplete and missing the mandatory parameter `$parameter` | The stated parameter is missing. 3 | Invalid value for parameter `$parameter` | Invalid value for parameter. If you see Facility not allowed in the error text, check that you are using the correct Base URL in your request. 4 | Invalid credentials were provided | The supplied API key or secret in the request is either invalid or disabled. 5 | Internal Error | An error occurred processing this request in the Cloud Communications Platform. 6 | The Nexmo platform was unable to process this message for the following reason: `$reason` | The request could not be routed. 8 | The api_key you supplied is for an account that has been barred from submitting messages. | 9 | Partner quota exceeded | Your account does not have sufficient credit to process this request. 19 | For `cancel`: Either you have not waited at least 30 secs after sending a Verify request before cancelling or Verify has made too many attempts to deliver the verification code for this request and you must now wait for the process to complete. For `trigger_next_event`: All attempts to deliver the verification code for this request have completed and there are no remaining events to advance to. 101 | No request found | There are no matching verify requests.
// Code | Text | Description -- | -- | -- 0 | Success | The request was successfully accepted by Nexmo. 1 | Throttled | You are trying to send more than the maximum of 30 requests per second. 2 | Your request is incomplete and missing the mandatory parameter `$parameter` | The stated parameter is missing. 3 | Invalid value for parameter `$parameter` | Invalid value for parameter. If you see Facility not allowed in the error text, check that you are using the correct Base URL in your request. 4 | Invalid credentials were provided | The supplied API key or secret in the request is either invalid or disabled. 5 | Internal Error | An error occurred processing this request in the Cloud Communications Platform. 6 | The Nexmo platform was unable to process this message for the following reason: `$reason` | The request could not be routed. 8 | The api_key you supplied is for an account that has been barred from submitting messages. | 9 | Partner quota exceeded | Your account does not have sufficient credit to process this request. 19 | For `cancel`: Either you have not waited at least 30 secs after sending a Verify request before cancelling or Verify has made too many attempts to deliver the verification code for this request and you must now wait for the process to complete. For `trigger_next_event`: All attempts to deliver the verification code for this request have completed and there are no remaining events to advance to.
Status string `json:"status,omitempty"`
// If the `status` is non-zero, this explains the error encountered.
ErrorText string `json:"error_text,omitempty"`
Expand Down
22 changes: 22 additions & 0 deletions internal/verify/model_control_request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Nexmo Verify API
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/

package verify
// ControlRequest struct for ControlRequest
type ControlRequest struct {
// You can find your API key in your [account dashboard](https://dashboard.nexmo.com)
ApiKey string `json:"api_key"`
// You can find your API secret in your [account dashboard](https://dashboard.nexmo.com)
ApiSecret string `json:"api_secret"`
// The `request_id` you received in the response to the Verify request.
RequestId string `json:"request_id"`
// The possible commands are `cancel` to request cancellation of the verification process, or `trigger_next_event` to advance to the next verification event (if any). Cancellation is only possible 30 seconds after the start of the verification request and before the second event (either TTS or SMS) has taken place.
Cmd string `json:"cmd"`
}
2 changes: 1 addition & 1 deletion internal/verify/model_control_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* The Verify API helps you to implement 2FA (two-factor authentication) in your applications. This is useful for: * Protecting against spam, by preventing spammers from creating multiple accounts * Monitoring suspicious activity, by forcing an account user to verify ownership of a number * Ensuring that you can reach your users at any time because you have their correct phone number More information is available at <https://developer.nexmo.com/verify>
*
* API version: 1.0.11
* API version: 1.1.3
* Contact: devrel@nexmo.com
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
Expand Down
Loading

0 comments on commit 0d04809

Please sign in to comment.