Skip to content

Commit

Permalink
v1.1, firefox/edge/opera/brave/etc support
Browse files Browse the repository at this point in the history
  • Loading branch information
Glench committed Jan 14, 2021
1 parent 5598960 commit 97f0d84
Show file tree
Hide file tree
Showing 11 changed files with 3,562 additions and 640 deletions.
190 changes: 100 additions & 90 deletions ExtPay.dev.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Sign up at https://extensionpay.com to use this library. AGPLv3 licensed.

// WARNING: DON'T USE THIS FILE IN YOUR EXTENSION. USE A FILE FROM THE /build FOLDER INSTEAD.
// WARNING: DON'T USE THIS FILE IN YOUR EXTENSION. USE A FILE FROM THE /dist FOLDER INSTEAD.

// "content_scripts": [
// {
Expand All @@ -16,26 +15,37 @@
// chrome.runtime.sendMessage(event.data)
// }, false);

import * as browser from 'webextension-polyfill';

export default function ExtPay(extension_id) {
var browser;
if (typeof browser !== 'undefined') {
browser = browser
} else if (typeof chrome !== 'undefined') {
browser = chrome;
} else {
throw "ExtPay: No browser found. ExtPay needs to run in a browser extension context."
}

const HOST = `http://localhost:3000`
var EXTENSION_URL = `${HOST}/extension/${extension_id}`

browser.runtime.onInstalled.addListener(async function(details) {
async function get(key) {
try {
return await browser.storage.sync.get(key)
} catch(e) {
// if sync not available (like with Firefox temp addons), fall back to local
return await browser.storage.local.get(key)
}
}
async function set(dict) {
try {
return await browser.storage.sync.set(dict)
} catch(e) {
// if sync not available (like with Firefox temp addons), fall back to local
return await browser.storage.local.set(dict)
}
}

browser.runtime.onInstalled.addListener(async function(install_details) {

browser.management.getSelf(function(info) {
if (info.installType == 'development') {
if (!info.hostPermissions.includes(HOST+'/*')) {
var permissions = info.permissions.concat(info.hostPermissions)
throw `ExtPay Setup Error: please include "${HOST}/*" in manifest.json["permissions"] or else ExtensionPay won't work correctly.
const ext_info = await browser.management.getSelf()
if (ext_info.installType == 'development') {
if (!ext_info.hostPermissions.includes(HOST+'/*')) {
var permissions = ext_info.permissions.concat(ext_info.hostPermissions)
throw `ExtPay Setup Error: please include "${HOST}/*" in manifest.json["permissions"] or else ExtensionPay won't work correctly.
You can copy and paste this to your manifest.json file to fix this error:
Expand All @@ -44,11 +54,11 @@ You can copy and paste this to your manifest.json file to fix this error:
"${HOST}/*"
]
`
}
}

if (!info.permissions.includes('storage')) {
var permissions = info.hostPermissions.concat(info.permissions)
throw `ExtPay Setup Error: please include the "storage" permission in manifest.json["permissions"] or else ExtensionPay won't work correctly.
if (!ext_info.permissions.includes('storage')) {
var permissions = ext_info.hostPermissions.concat(ext_info.permissions)
throw `ExtPay Setup Error: please include the "storage" permission in manifest.json["permissions"] or else ExtensionPay won't work correctly.
You can copy and paste this to your manifest.json file to fix this error:
Expand All @@ -57,84 +67,92 @@ You can copy and paste this to your manifest.json file to fix this error:
"storage"
]
`
}
}
})
}

if (details.reason == 'install' || details.reason == 'update') {
browser.storage.sync.get(['extensionpay_api_key'], function(storage) {
if (storage.extensionpay_api_key) return;

browser.management.getSelf(async function(info) {
var body = {};
if (info.installType == 'development') {
body.development = true;
}
// TODO: what to do if this request fails?
const resp = await fetch(`${EXTENSION_URL}/api/new-key`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(body),
})
if (!resp.ok) {
console.error('ExtPay: Error generating API key (server response): ', resp.status, `Are you sure you registered your extension? Check here and make sure the ID matches '${extension_id}':`, `${HOST}/home`)
return;
}
const api_key = await resp.json();
browser.storage.sync.set({extensionpay_api_key: api_key}, function() {
fetch_user()
})
})
})
if (install_details.reason !== 'install' && !install_details.reason !== 'update') {
return
}

const storage = await get(['extensionpay_api_key']);
if (storage.extensionpay_api_key) return;

var body = {};
if (ext_info.installType == 'development') {
body.development = true;
}

// TODO: what to do if this request fails?
const resp = await fetch(`${EXTENSION_URL}/api/new-key`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(body),
})
if (!resp.ok) {
console.error('ExtPay: Error generating API key (server response): ', resp.status, `Are you sure you registered your extension? Check at this URL and make sure the ID matches '${extension_id}':`, `${HOST}/home`)
return;
}
const api_key = await resp.json();
await set({extensionpay_api_key: api_key})
fetch_user()
})

function open_payment_page() {
browser.storage.sync.get(['extensionpay_api_key'], function(storage) {
async function open_payment_page() {
const storage = await get(['extensionpay_api_key'])
try {
browser.windows.create({
url: `${EXTENSION_URL}?api_key=${storage.extensionpay_api_key}`,
type: "popup",
focused: true,
width: 500,
height: 800,
left: 200
left: 450
})
})
} catch(e) {
// firefox doesn't support 'focused'
browser.windows.create({
url: `${EXTENSION_URL}?api_key=${storage.extensionpay_api_key}`,
type: "popup",
width: 500,
height: 800,
left: 450
})
}
}

// var paid_callbacks = [];

function fetch_user() {
return new Promise((resolve, reject) => {
browser.storage.sync.get(['extensionpay_api_key'], async function(obj) {
const resp = await fetch(`${EXTENSION_URL}/api/user?api_key=${obj.extensionpay_api_key}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
})
// TODO: think harder about error states and what users will want (bad connection, server error, id not found)
if (!resp.ok) return reject()

const user_data = await resp.json();
browser.storage.sync.get(['extensionpay_user'], function(storage) {
browser.storage.sync.set({extensionpay_user: user_data})
if (user_data.paid) {
if (!storage.extensionpay_user || (storage.extensionpay_user && !storage.extensionpay_user.paid)) {
// paid_callbacks.forEach(cb => cb(user))
}
}
})
const parsed_user = {
paid: user_data.paid,
paidAt: user_data.paidAt ? new Date(user_data.paidAt) : null,
installedAt: new Date(user_data.installedAt),
}
resolve(parsed_user)
})
async function fetch_user() {
const storage = await get(['extensionpay_api_key', 'extensionpay_user'])
const resp = await fetch(`${EXTENSION_URL}/api/user?api_key=${storage.extensionpay_api_key}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
})
// TODO: think harder about error states and what users will want (bad connection, server error, id not found)
if (!resp.ok) throw 'ExtPay error while fetching user: '+resp

const user_data = await resp.json();

const parsed_user = {
paid: user_data.paid,
paidAt: user_data.paidAt ? new Date(user_data.paidAt) : null,
installedAt: new Date(user_data.installedAt),
}

// TODO: implement onPaid callbacks
// if (parsed_user.paid) {
// if (!storage.extensionpay_user || (storage.extensionpay_user && !storage.extensionpay_user.paid)) {
// paid_callbacks.forEach(cb => cb(user))
// }
// }
await set({extensionpay_user: user_data}) // useful for future purposes perhaps

return parsed_user;
}

// browser.runtime.onMessage.addListener(async function(message) {
Expand All @@ -145,14 +163,6 @@ You can copy and paste this to your manifest.json file to fix this error:
//
// });

// function save(key, value) {
// // if no ID found in firefox manifest.json/browser_specific_settings, give warning
// browser.storage.sync.set(data)
// // check API -> storage.sync -> storage.local
// }
// function get(key) {
// }

return {
getUser: function() {
return fetch_user()
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# ExtPay — Payments for browser extensions on [extensionpay.com](https://extensionpay.com)
The JavaScript library for [ExtensionPay.com](https://extensionpay.com), a service to add payments to browser extensions.
The JavaScript library for [ExtensionPay.com](https://extensionpay.com), a service to add payments to browser extensions. It uses [webextension-polyfill](https://github.com/mozilla/webextension-polyfill) internally for compatability across browsers.

Below are the directions for using this library in your browser extension. If you learn better by example, you can also view the sample extension:

Expand Down
Loading

0 comments on commit 97f0d84

Please sign in to comment.