applepay

package module
v0.0.0-...-e69e823 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2022 License: MIT Imports: 25 Imported by: 0

README

applepay

GoDoc

applepay is a Go package for processing Apple Pay transactions easily. It is aimed at merchants or PSPs that are looking to manage their own Apple Pay flow, as opposed to letting a third-party (such as Stripe) do it end-to-end. You will need a paid Apple Developer account to use this.

Note: we have included the Apple root CA in this repository. For production use-cases, you should always download the certificates directly from Apple.

Running tests

go test

You may need to change your PKG_CONFIG_PATH to include OpenSSL. For example, on my Mac I use PKG_CONFIG_PATH=$(brew --prefix openssl)/lib/pkgconfig go test.

Getting up and running with the example

Requirements:

  • An account in the Apple Developer Program
  • A recent version of Go (tested with v1.9.2)
  • cfssl
  • OpenSSL/libssl-dev
  • make
  1. Log into your developer account. In the developer console, create a Merchant ID

  2. Verify your domain by serving the apple-developer-merchantid-domain-association file at https://yourdomain.com/.well-known/apple-developer-merchantid-domain-association (the example app will do it for you if you put it in example/static/.well-known). Note: Be careful to support one of the supported cipher suites for HTTPS!

  3. Edit the JSON files in the certs/ directory of this repo with your merchant ID, your domain and your email address.

  4. Generate a Payment Processing Certificate request by running make cert-processing.certSigningRequest in the certs/ directory.

  5. Upload the certificate request to the developer console. Select your merchant ID and click "Create Certificate" in the "Payment Processing Certificate" section

  6. Download the signed certificate to certs/cert-processing.cer, run make cert-processing.crt to convert it to the proper format

  7. Repeat steps 4-6 for the Merchant Identity Certificate, by running make cert-merchant.certSigningRequest and, with the certificate, make cert-merchant.crt

  8. Move the directory certs/ to example/certs/

  9. Deploy the application under your domain. We have included a Dockerfile your your convenience; you should be able to run docker build, docker push and docker run.

  10. Go to the running application and try to pay with Apple Pay. If you don't see an Apple Pay button, you are probably visiting from an unsupported browser or device. You will not be charged.

Picking a Payment Service Provider (PSP) that supports Apple Pay

Some PSPs, such as Braintree or Stripe, will accept Apple Pay payments on your behalf. That means that you don't have to use this package and just need to verify your domain with them. If you really want to, you can probably use this package and pass the tokens that decrypt yourself. Check with your processor for more info on how to know how to do that.

Other payment services may not do the integration for you, but will let you pass Apple Pay-related values (such as the payment cryptogram). This package is made for you!

If you can't charge network tokens with your payment processor, unfortunately you will not be able to accept Apple Pay. Contact your provider for more details.

Documentation

Overview

Package applepay abstracts all the Apple Pay flow.

It support features such as RSA-encrypted tokens (used in China), elliptic curve-encrypted token, full signature verification and protection against replay attacks.

Sample usage:

 ap, err := applepay.New(
	 "com.processout.test",
	 applepay.MerchantDisplayName("ProcessOut Test Store"),
	 applepay.MerchantDomainName("store.processout.com"),
	 applepay.MerchantCertificateLocation("cert-merchant.crt", "cert-merchant-key.pem"),
	 applepay.ProcessingCertificateLocation("cert-processing.crt", "cert-processing-key.pem"),
 )

 // Create a new session
 sessionPayload, err := ap.Session("https://apple-pay-gateway.apple.com/paymentservices/startSession")

 // Decrypt a token
 token, err := ap.DecryptResponse(res)

A working example can be found in applepay/app.go. It requires a registered domain and valid certificates to work.

Index

Constants

This section is empty.

Variables

View Source
var (

	// AppleRootCertificatePath is the relative path to Apple's root certificate
	AppleRootCertificatePath = "certs/AppleRootCA-G3.crt"

	// TransactionTimeWindow is the window of time, in minutes, where
	// transactions can fit to limit replay attacks
	TransactionTimeWindow = 5 * time.Minute
)

Functions

func MerchantCertificate

func MerchantCertificate(cert tls.Certificate) func(*Merchant) error

func MerchantCertificateLocation

func MerchantCertificateLocation(certLocation,
	keyLocation string) func(*Merchant) error

func MerchantDisplayName

func MerchantDisplayName(displayName string) func(*Merchant) error

func MerchantDomainName

func MerchantDomainName(domainName string) func(*Merchant) error

func ProcessingCertificate

func ProcessingCertificate(cert tls.Certificate) func(*Merchant) error

func ProcessingCertificateLocation

func ProcessingCertificateLocation(certLocation,
	keyLocation string) func(*Merchant) error

Types

type Contact

type Contact struct {
	GivenName          string
	FamilyName         string
	EmailAddress       string
	AddressLines       []string
	AdministrativeArea string
	Locality           string
	PostalCode         string
	Country            string
	CountryCode        string
}

Contact is the struct that contains billing/shipping information from an Apple Pay response

type EncryptionVersion

type EncryptionVersion string

version is used to represent the different versions of encryption used by Apple Pay

const (
	EC_v1  EncryptionVersion = "EC_v1"
	RSA_v1 EncryptionVersion = "RSA_v1"
)

func (EncryptionVersion) String

func (v EncryptionVersion) String() string

String implements fmt.Stringer for version

type Header struct {
	ApplicationData    string
	EphemeralPublicKey []byte
	WrappedKey         []byte
	PublicKeyHash      []byte
	TransactionID      string
}

type Merchant

type Merchant struct {
	// contains filtered or unexported fields
}

func New

func New(merchantID string, options ...func(*Merchant) error) (*Merchant, error)

New creates an instance of Merchant using the given configuration

func (Merchant) DecryptResponse

func (m Merchant) DecryptResponse(r *Response) (*Token, error)

DecryptResponse calls DecryptToken(r.Token)

func (Merchant) DecryptToken

func (m Merchant) DecryptToken(t *PaymentData) (*Token, error)

DecryptToken decrypts an Apple Pay token

func (Merchant) Session

func (m Merchant) Session(url string) (sessionPayload []byte, err error)

Session returns an opaque payload for setting up an Apple Pay session

type PKPaymentToken

type PKPaymentToken struct {
	TransactionIdentifier string
	PaymentMethod         PaymentMethod
	PaymentData           PaymentData
	// contains filtered or unexported fields
}

PKPaymentToken is the payment information returned by Apple Pay with all data, and an encrypted token See https://developer.apple.com/library/content/documentation/PassKit/Reference/PaymentTokenJSON/PaymentTokenJSON.html

func (*PKPaymentToken) SetTransactionTime

func (t *PKPaymentToken) SetTransactionTime(transactionTime time.Time) error

SetTransactionTime sets the time the merchant received the token. This is useful to protect against replay attacks. By default this value is set to time.Now(), when the token is decrypted. It may be useful to change the transaction time window (see the global variable TransactionTimeWindow)

type PaymentData

type PaymentData struct {
	Version   string
	Signature []byte
	Header    Header
	Data      []byte
}

func (PaymentData) PublicKeyHash

func (t PaymentData) PublicKeyHash() ([]byte, error)

PublicKeyHash returns the hash of the public key used in the token after checking the message's signature. This is useful for selecting the appropriate processing key for merchants/PSPs that may have many.

type PaymentMethod

type PaymentMethod struct {
	Type        string
	Network     string
	DisplayName string
}

type Response

type Response struct {
	ShippingContact Contact
	BillingContact  Contact
	Token           PKPaymentToken
}

Response is the full response from the user's device after an Apple Pay request

type Token

type Token struct {
	// ApplicationPrimaryAccountNumber is the device-specific account number of the card that funds this
	// transaction
	ApplicationPrimaryAccountNumber string
	// ApplicationExpirationDate is the card expiration date in the format YYMMDD
	ApplicationExpirationDate string
	// CurrencyCode is the ISO 4217 numeric currency code, as a string to preserve leading zeros
	CurrencyCode string
	// TransactionAmount is the value of the transaction
	TransactionAmount float64
	// CardholderName is the name on the card
	CardholderName string
	// DeviceManufacturerIdentifier is a hex-encoded device manufacturer identifier
	DeviceManufacturerIdentifier string
	// PaymentDataType is either 3DSecure or, if using Apple Pay in China, EMV
	PaymentDataType string
	// PaymentData contains detailed payment data
	PaymentData struct {

		// OnlinePaymentCryptogram is the 3-D Secure cryptogram
		OnlinePaymentCryptogram []byte
		// ECIIndicator is the Electronic Commerce Indicator for the status of 3-D Secure
		ECIIndicator string

		// EMVData is the output from the Secure Element
		EMVData []byte
		// EncryptedPINData is the PIN encrypted with the bank's key
		EncryptedPINData string
	}
}

Token is the decrypted form of Response.Token.PaymentData.Data

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL