swifturlaffiliate

Build Amazon Affiliate Link Swift


I would like to be able to build an Amazon-Affiliate link, when a "normal" Amazon URL is given.

I tried using this structure:

http://www.amazon.com/dp/{ASIN}/?tag={trackingId}

as suggested here.

This is how I try to create the URL:

func getAmazonAffiliateLink() -> URL? {
    if let regex = try? NSRegularExpression(pattern: "([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})"),
       let match = regex.firstMatch(in: self, range: NSRange(self.startIndex..., in: self)),
       let asinMatchRange = Range(match.range(at: 4), in: self) {
        let asin = self[asinMatchRange]
        let partnerId = "wishlists07-21"
        let affiliateLink = "https://www.amazon.com/dp/\(asin)/?tag=\(partnerId)"
        return URL(string: affiliateLink)
    } else {
        return nil
    }

}

But this gives me this URL for example:

https://www.amazon.com/dp/b085sp5sxh/?tag=wishlists07-21

And as you can see for yourself, it is not working...

What am I missing here? How can I build affiliate links?


Solution

  • It looks like the initial link you're testing with is probably bad -- in other words, when I remove your wishlist tag and just try the basic Amazon link, it still fails.

    But, with a valid Amazon product link, it seems to work. Here's what I did in a Playground:

    extension String {
        func getAmazonAffiliateLink() -> URL? {
            if let regex = try? NSRegularExpression(pattern: "([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})"),
               let match = regex.firstMatch(in: self, range: NSRange(self.startIndex..., in: self)),
               let asinMatchRange = Range(match.range(at: 4), in: self) {
                let asin = self[asinMatchRange]
                let partnerId = "wishlists07-21"
                let affiliateLink = "https://www.amazon.com/dp/\(asin)/?tag=\(partnerId)"
                return URL(string: affiliateLink)
            } else {
                return nil
            }
    
        }
    }
    
    "https://www.amazon.com/dp/B0863ZGP2R/ref=fs_a_ipadt2_us0".getAmazonAffiliateLink()
    

    Which yields the result of https://www.amazon.com/dp/B0863ZGP2R/?tag=wishlists07-21 which is a working Amazon link.