Manual

Introdution

The sidebar on the left contains links to the corresponding section:

  • Username - links to the personal profile.
  • Dashboard - view the current status in the form of charts and graphs.
  • Applications - application management.
  • Unlock codes - unlock codes generated automatically or downloaded by you.
  • Payments - history of users' incoming payments.
  • Manual - the current user manual.

Dashboard

You can set common filters for all widgets in the dashboard:

  • Currency - the currency into which incoming and outgoing amounts will be converted on the dashboard.
  • Period - is the period of time for which data is displayed in the charts and tables on the dashboard. It determines the interval during which information and statistics about payments, applications, and other parameters are analyzed and displayed.

Balance

The balance includes the following amounts:

  • Gross amount - the total amount of all user payments for the selected period excluding the fees of payment systems and PayToUse.
  • Net amount - the total amount of all payments for the selected period minus fees of payment systems and PayToUse.
  • Pending amount - the total amount of all payments for the specified period minus the fees of payment systems and PayToUse pending withdrawal to the developer's account. The payment becomes available for withdrawal 7 days after the payment.
  • Available amount - the total amount of all payments for all time minus the fees of payment systems and PayToUse, available for withdrawal to the developer's account.

Payments

The Payments widget includes a table of payments grouped by application for the selected period.

Table fields:

  • Application - application. Only applications for which payments have been made during the selected period are displayed in the table.
  • Payments - number of payments.
  • Gross amount - the total amount of all user payments for the selected period excluding the fees of payment systems and PayToUse.
  • Net amount - the total amount of all payments for the selected period minus fees of payment systems and PayToUse.

The graph shows the dynamics of Net amount and Gross amount values by day.

New users

The graph of new users shows two values in dynamics by day:

  • New users - the number of new API calls. API accesses are recorded only if the device parameter - a unique device identifier - is passed when sending a request to the API. This parameter must be really unique for the device. (see Sending a request)
  • Payments - the number of payments for the same period by day.

Conversion

The Conversion metric refers to the assessment of your sales efficiency to convert New users into Payments.

The graph shows the ratio of the number of Payments to the number of New users, in percent.

Applications

When you go to this section, a list of your applications opens.

The list of columns in the application table:

  • # - unique application identifier. Used when verifying the application code or displaying the payment form.
  • Name - application name. The name is displayed only to you in reports and the dashboard. Clicking on the application name opens the application editing page.
  • Status - the current status of the application. It can be:
    • Created - The application has just been created, it is not configured yet.
    • Released - the application is running.
  • Created - the date of application creation.
  • Additional control buttons:
    • Delete - to remove the application from the list.

Creating or editing an application

To accept payments, you must consistently fill out all the necessary application data and activate app.

The button to create a new application is located in the title bar of the application list.

Application

Fields available when creating an application:

  • Name - the name of the application that only you can see in reports or on the dashboard. The name will be displayed in the page header of the saved application. As long as the application is not saved, "New app" is displayed instead of the name. The field is mandatory to enter.
  • Contact email - the email address to which copies of messages sent to users will be sent. This address is also specified in the "Reply-to" field and is used to reply the user to the received e-mail with the code. The field is mandatory to enter. By default, the field is populated with the value from the developer profile. The value can be changed to a different value.
  • Application type - type of application. If you select a group type of application, a list of applications will be displayed for grouping. Only single applications for which unlock codes are generated are available in the list.
  • Allow feedback on payment - adds a field to the payment form for users to enter free text. Feedback is added to the developer's email copy. Feedback can also be seen in the payment details.

Start typing changing values and the Save button appears. The Save button allows you to save your changes without going to the next page. The Next button saves the changes and moves to the next page. You can always return to make changes later.

In the page header, only the saved application pages are available for navigation. You can click Next or go to the section in the page header.

Description

Select a language from the list and click Add.

A tab with localized application texts for the selected language will appear.

Available languages:

  • German
  • English
  • French
  • Spanish
  • Russian
  • Chinese Simplified

The fields in the description are used to display information on the payment form and in the reply message to the user:

  • Name - the name of the application for the selected language. It is displayed on the payment form and in the payment notification email. By default, when adding a language, the application name is inserted. You can set a different name for each language. Required field.
  • Description - a brief description of the application. Displayed on the payment form under the application name. Optional field. You can leave it empty if you don't want any description to be displayed.
  • Reply - additional information that will be sent to the user in the email upon successful payment. The response text is added at the end of the email after the standard response.

At least one language must be added to save and go to the next page.

The language displayed in the payment form is determined automatically on the basis of the user's preferences specified in his browser settings. You can save the application language for the application.

Start typing or changing values and the Save button appears. The Save button allows you to save your changes without going to the next page. The Next button saves the changes and moves to the next page. You can always return to make changes later.

In the page header, only the saved application pages are available for navigation. You can click Next or go to the section in the page header.

Price

The page contains a list of prices and fields related to payment:

  • Trial period - the length of the trial period.
  • Unit of time - the time unit of the trial period. For example, if you specify 7 days, it means that after 7 days after the application's first API call it will return a response that the trial period has expired. The time of the first device call is saved.
  • Price calculating method - The method of price calculation from the list:
    • Price calculation depending on the term - In the payment form, the user specifies the activation period of the code, and the price is automatically calculated according to the table below. The user receives an automatically generated unlock code in the response email.
    • Term calculation depending on the price - In the payment form, the user selects a price from the list or enters their own price value, and the period is automatically calculated according to the table below. The user receives an automatically generated code in the response message.
    • Permanent code - In the payment form, the user selects a price from the list or enters their own price value. After payment, they receive a code from the list below, corresponding to the selected price, in the response email.
    • Donation - In the payment form, the user selects a price from the list or enters their own price value. For Donation-type applications, an unlock code is not generated.

The price is set in US dollars. The minimum price is 1 US dollar.

Start typing or changing values and the Save button appears. The Save button allows you to save your changes without going to the next page. The Next button saves the changes and moves to the next page. You can always return to make changes later.

In the page header, only the saved application pages are available for navigation. You can click Next or go to the section in the page header.

Preview

This page sets the values:

  • Code length - the length of the generated code, if applicable.
  • Code character set - the set of characters from which the code is generated:
    • Numeric code - the code is generated using only the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Leading zeros may be included in the code. Leading zeros are significant when verifying the code.
    • Alphanumeric code - the code is generated using the characters 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, G, H, I, G, K, L, M, N, P, Q, R, S, T, U, V, X, Y, Z. The code is generated and sent to the user using uppercase characters. The case of the characters does not matter when verifying the code.
  • Link to check code - an example link to be used for code verification.
  • Link to pay - payment link. You can copy the link and paste it into the description of the application on the website where the application is published. Parameters to be passed:
    • app - the unique identifier of the application. Required parameter.
    • amount - the amount that will be specified in the price field when purchasing. The default price is ignored. However, the amount can't be less than the minimum price and can't be lower than the minimum price set for the application. Optional parameter.

To start accepting payments, you need to activate the application with the Launch button. Before activating the application, make sure that all the data entered is correct. The keys generated by the application cannot be changed.

Code verification

Checking the application unlock code is done in 3 steps:

  1. Writing and sending a request for code verification
  2. Checks on the API side
  3. Receiving and processing API response
Sending a request

To verify the code, the user of your application must enter it in the field in the application settings.

/resources/settings/properties.xml
<properties>
	<property id="UnlockCode" type="string"></property>
	<property id="UnlockResult" type="string">Checking...</property>
	...
<properties>
/resources/settings/settings.xml
<settings>
	<setting propertyKey="@Properties.UnlockCode" title="@Strings.UnlockCode">
		<settingConfig type="alphaNumeric" maxLength="12"/>
	</setting>
	<setting propertyKey="@Properties.UnlockResult" title="@Strings.UnlockResult">
		<settingConfig type="alphaNumeric" readonly="true"/>
	</setting>
	...
</settings>

Then you need to send a request to the Pay-to-use API server:

/source/background.mc
function onTemporalEvent() as Void {
	var ds = System.getDeviceSettings();
	return Toybox.Communications.makeWebRequest(
		"https://api.pay-to-use.com", // API URL
		{
			"device" => ds.uniqueIdentifier, // device unique identifier
			"app" => "6", // your Application id
			"model" => ds.partNumber, // device part number
			"code" => Application.Properties.getValue("UnlockCode") // unlock code value in your application
		},
		{
			:method => Communications.HTTP_REQUEST_METHOD_POST,
			:headers => { "Content-Type" => Communications.REQUEST_CONTENT_TYPE_JSON },
			:responseType => Communications.HTTP_RESPONSE_CONTENT_TYPE_JSON
		},
		method(:onReceive)
	);
}

API request parameters:

  • url - https://api.pay-to-use.com. Using HTTPS is mandatory.
  • The body of the request (the values passed). A Dictionary of keys and values:
    • device - unique identifier of the device.
    • app - unique identifier of your application.
    • model - device model identifier. Optional parameter. Data is used to display statistics for new devices.
    • code - unlock code entered by the user in your application settings.
  • Request options:
    • :method - the API supports GET and POST request methods.
    • :headers - for the POST method, parameters need to be passed in JSON format.
    • :responseType - the response is returned in JSON.
  • responseCallback - a link to the callback method, which should accept two arguments:
    • responseCode - the server response header code.
    • data - the content if the request was successful, or null.
Checks on the API side

If no parameters are passed to the API, the API returns a HTTP/1.1 404 Not Found header.

If at least one parameter is passed to the API, the API returns header HTTP/1.1 200 OK.

The server response consists of:

  • response - response code
  • msg - textual description of the response
  • expires - UNIXTIME timestamp (if applicable)

A check is performed to ensure that the application identifier passed in is correct. The application must be in Released status at the time of payment. In case of an error, response code 301 is returned.

If a unique device ID is transmitted, the device ID is searched for and stored. If errors occur when checking or saving, an error code 402 is returned. If such a return code is found, immediately write to support at [email protected]

If the code is passed, the following steps are performed for applications with the Price calculation depending on the term and Term calculation depending on the price calculation methods:

  • If an empty code is transmitted, it is detached from the unique device identifier defined in the previous steps.
  • If a non-empty code is transmitted and it is not activated, the code is activated depending on the conditions of the price specified when the code was purchased, regardless of the date of activation.
  • If no code has been transmitted or if the transmitted code is not found, error code 201 is returned.
  • The activated code is checked against the device and, if a unique device identifier other than the stored one was transmitted during activation, an error code 202 is returned.
  • If the transmitted code has no expiration date and all previous checks have been passed, code 101 is returned.
  • If the code is time limited, a check is performed. If the key is not expired, code 101 is returned. If the code has expired, error code 203 is returned.
  • This type of application requires the code to be bound to the device. If the unique device ID has not been transmitted, error code 304 is returned.

For an app with a Permanent code, only the availability of the code at the time of purchase is checked. If a code is found, code 101 is returned. If no code is found, error code 201 is returned.

For an application with the Donation calculation method, the code is not checked. The code 101 is always returned.

If the previous checks have not been passed the test period is checked. If more time has elapsed since the device was first contacted than the current application settings, error code 204 is returned. If the trial period has not yet expired, error code 102 is returned.

If only the application ID is transmitted and neither the unlock code nor the unique device ID is transmitted, error code 303 is returned.

If the response returned is 500, you should write to support at [email protected]

Below is a table of all returned codes:

Return Message
101 Price calculation depending on the term and Term calculation depending on the price calculation methods:
  • Active forever
{
	"response":101,
	"msg":"Active forever",
	"expires":0
}
  • Active until [date]
{
	"response":101,
	"msg":"Active until 24 Jul 2025",
	"expires":1753338079
}
Permanent code:
{
	"response":101,
	"msg":"The code check was successfull",
	"expires":0
}
Donation:
{
	"response":101,
	"msg":"No code check required",
	"expires":0
}
102
{
	"response":102,
	"msg":"Trial period expires in 16h 12m",
	"expires":1732228419
}
201
{
	"response":201,
	"msg":"Code not found"
}
202
{
	"response":202,
	"msg":"Used on the another device"
}
203
{
	"response":203,
	"msg":"Expiration: 8 Nov 2024",
	"expires":1731046879
}
204
{
	"response":204,
	"msg":"Trial period expired"
}
301
{
	"response":301,
	"msg":"Application not found"
}
302
{
	"response":302,
	"msg":"Term undefined"
}
303
{
	"response":303,
	"msg":"Not enought arguments"
}
304
{
	"response":304,
	"msg":"Device is nesessary"
}
401
{
	"response":401,
	"msg":"Error code saving"
}
402
{
	"response":402,
	"msg":"Error device saving"
}
500
{
	"response":500,
	"msg":"Unknown error"
}
Checking the response

Then you should check the response from the Pay-to-use API server:

/source/background.mc
function onReceive(responseHeader, data) as Void {
	if (responseHeader == 200) { Toybox.Background.exit(data); }
}

You can check all headers and codes, you can display your own messages for user convenience, but in the simplest form the verification will look something like this:

/source/app.mc
function onBackgroundData(data) as Void {
	if (data.hasKey("response")) {
		if (data.hasKey("msg")) {
			// You can show data["msg"] in the properties field with the name "UnlockResult".
			Application.Properties.setValue("UnlockResult", data["msg"]);
		}
		if (data["response"].toString().substring(0, 1).equals("2")) {
			// Code verification failed
			// Paid functions are NOT available
			...
		} else {
			// The code check was successful or the error is your fault or the fault of the API
			// Paid functions are available
			...
		}
	}
}

Unlock codes

When you go to this section, a list of unlock codes will open.

Unlock codes list

You can search the email field or the code in the top search bar. The found codes will be displayed in the list. You can use all or part of the email or the code as the search criterion. Matches will be highlighted in color. Search and filters work simultaneously and do not exclude each other.

The last used filter is stored for the user. That is, the next time you enter the page, the last used filter will be applied automatically. Filters are available for the list of unlock codes:

  • Columns - select table columns to display in the unlock code list.
  • Application - display only unlock codes for selected applications.
  • Status - display only unlock codes that are in the selected statuses.

The list of columns in the unlock codes table:

  • Application - your application. You can follow the link to edit its settings.
  • Code - the unlock code.
  • Email - the email address associated with the unlock code registration. This address is used to search for client unlock codes in the My purchases section of the website. This section is accessible to users.
  • Term - the period of validity of the sent code (specified in the application settings). A validity period is set for the code, corresponding to the conditions of the application settings at the time of its creation.
  • Status - the unlock code status. (see Unlock code status)
  • Created - the unlock code creation date.
  • Activated - the activation date of the code. It is set at the moment when this particular user device first contacts the PayToUse API service and submits this code. The status of the code changes to Activated. Only an inactive code can be activated. If an active code is submitted by a device with a different ID, the API returns error 202. Only one device can be linked to a single code.
  • Expiration - the date on which the code activation expires. Set for codes that have a limited validity period on code activation. For codes with unlimited expiration date remains blank.
  • Deleted - the code deletion date. Upon deletion, the code status is set to Unknown.
  • Payment # - unique sequence number of the payment. You can click on the link to view the details of the payment.
  • Buttons for actions with unlock codes. For example, deletion.

Unlock code status

During its lifecycle, the unlock code goes through different states, which can be tracked by the code status.

Status Description
Available The status is assigned to an unlock code for which no actions have been performed or if the device linkage is reset for the code.
Activated The status is set for a code with a set activation date. The activation date is set when the device successfully accesses the PayToUse API service for the first time. Also, when activating the code, the expiration date of the code is set.
Expired The status is set for an expired code. Unlinking the code from the device does not reset the expiration date of the code. Checking the code with this status will return error 203. (see Checks on the API side)
Unknown The status is set when the code is deleted. Checking the code with this status will return error 201. (see Checks on the API side)

Payments

When you go to this section, a list of user payments will open.

The following payment systems are used to receive payments:

System Description
The payment system fee is from 2.9% + 0.30 USD per each successful card charge. Cards, wallets, and other payment options are supported. The fee depends on the payment method and may differ from the card payment fee. Detailed information about the fees charged by the payment system, you can find on the website of the payment system.
The payment system fee is from 3.4% + 0.30 USD per each successful payment. Cards and PayPal are supported. Detailed information about the fees charged by the payment system, you can find on the website of the payment system.
The payment system fee is from 3.9% for each successful payment. Cards and other payment options are supported. The fee depends on the payment method. Detailed information about the fees charged by the payment system, you can find on the website of the payment system.

After the payment system's fees, PayToUse will charge a 13% fee. We are constantly working to reduce the fees.

If any disputes or refunds arise in the payment system, the penalties of the payment system are reissued to the developer. Therefore you should not allow such situations to occur. PayToUse fee is not charged in controversial situations.

Payments list

You can search the email field or the sent code in the top search bar. The found payments will be displayed in the list. You can use all or part of the email or the sent code as the search criterion. Matches will be highlighted in color. Search and filters work simultaneously and do not exclude each other.

The last used filter is stored for the user. That is, the next time you enter the page, the last used filter will be applied automatically. Filters are available for the list of payments:

  • Columns - select table columns to display in the payment list.
  • Application - displaying payments for selected applications only.
  • System - display payments only from selected payment systems.
  • Status - display payments only with selected statuses.

The list of columns in the payments table:

  • Application - your application. You can follow the link to edit its settings.
  • # - unique sequence number of the payment. It is assigned to the payment automatically when user goes from payment form to payment page in payment system. You can click on the link to view the details of the payment.
  • Comments - message from the user entered in the payment form.
  • System - the payment system selected by the user.
  • Status - the payment status. (see Payment status)
  • Email - user's email indicated in the payment form.
  • Term - the period of validity of the sent code (specified in the application settings).
  • Created - the payment creation date.
  • Invoice amount - the amount of payment charged to the user. Specified in the payment form depending on the application settings.
  • Payment date - the payment date.
  • Payment amount - the amount of payment confirmed by the payment system.
  • Sent code - code sent to the user.
  • Available amount - withdrawal amount available.
  • Payout amount - the amount of withdrawn funds for the payment.

It is not possible to make changes to the payment.

Payment status

During its lifecycle, the payment goes to different states, which can be tracked by the payment status.

Status Description
Incomplete The status is assigned to payments for which no actions have been performed. Payment is created as soon as the user switches from the payment form to the payment system form. The payment is assigned a unique serial number, as well as the basic attributes of payment: amount, payment system, date.
Succeeded The status is assigned to payments that received a positive response from the payment system. The next step is to send an email to the user containing the generated code or other data depending on the application settings. If the payment remains in this status, it is necessary to pay special attention to it, as the subsequent actions have not been performed.
Error The status is assigned to payments for which a negative response is received from the payment system. Subsequent steps are not performed. It is necessary to pay special attention to such payments, as the status on the side of the payment system can be processed with a delay.
Pending The status is assigned to payments for which a positive response is received from the payment system, and all subsequent steps have been completed successfully. Withdrawal for payments with this status is not available. Payments move to the next status automatically in 7 days.
Available Withdrawal is available for payments in this status.
Sending The status is enabled for payments included in the next withdrawal. If the withdrawal is canceled or declined, the payment status is returned to Available.
Sent The status is enabled for payments for which the withdrawal is made. Confirmation of receipt of funds is pending.
Completed The status is enabled for payments with successful withdrawals. You can manually set the status by confirming the withdrawal in the corresponding section. The status is also automatically changed 14 days after the payment withdrawal.
Refunded Payments for which a refund has been issued are transferred to this status. Upon issuing a refund, a refund fee is charged. The fee is deducted from the withdrawal amount.

Withdrawals

When you go to this section, a list of your withdrawals will open.

Withdrawals list

The last used filter is stored for the user. That is, the next time you enter the page, the last used filter will be applied automatically. Filters are available for the list of withdrawals:

  • Columns - display only selected columns in the withdrawal list.
  • Status - display only withdrawals that are in the selected statuses.

The list of columns in the withdrawals table:

  • # - unique sequence number of the withdrawal. It is assigned to the withdrawal automatically when withdrawal saved. You can click on the link to view the details of the withdrawal.
  • Status - the withdrawal status. (see Withdrawal status)
  • Created - the date of the withdrawal request.
  • Amount - the amount of withdrawal.
  • Withdrawal - the date the withdrawal was sent.
  • Buttons for actions with withdrawals. For example, confirmation.

You can confirm the withdrawal when it is in the Sent status.

Withdrawal status

During its lifecycle, the withdrawal goes to different states, which can be tracked by the withdrawal status.

Status Description
Pending Status is assigned to withdrawals at creation, for which no actions were performed.
Canceled The status is assigned to cancelled withdrawals. Cancellations can be made for a variety of reasons. For example, the method of receiving funds is not specified. All payments from this withdrawal go to Available status and are available for withdrawal again.
Sent The status is set for the withdrawal of funds when it is sent.
Completed The status is set for manual withdrawal when it is received by the developer to confirm receipt. Or automatically in 14 days after sending.
Refused The status is set for withdrawal when the bank or payment system returns funds after sending. All payments from this withdrawal go to Available status and are available for withdrawal again.

API

Overview

API PayToUse performs the following functions:

  1. Checks the activation status of an unlock code and activates it if necessary.
  2. Retrieves blood glucose data from the NightScout app.
  3. Retrieves current weather data for a specified location.

All information can be requested and returned in a single request.

API Endpoints

You can use one of the following endpoints:

  • https://api.pay-to-use.com
  • https://api.p2u.io

Both endpoints handle GET and POST requests.

Request Parameters

  • device: string (required) — unique device identifier
  • app: integer (required) — your Application ID
  • model: string (optional) — device model code, needed for collecting and displaying statistics for devices using the app
  • code: string (optional) — unlock code
  • bg: associative array (optional) — data for requesting blood glucose levels from the NightScout app
    • url: string (optional) — address of the NightScout app
  • weather: associative array (optional) — data for requesting current weather
    • appid: string (optional) — weather API access key
    • lat: float (optional) — latitude
    • lon: float (optional) — longitude
    • provider: integer (optional) — weather provider

List of Supported Weather Providers

1. OpenWeatherMap

  • Description: OpenWeatherMap provides global weather data, including real-time weather, historical data, and 16-day forecasts. With wide geographic coverage and frequent updates, OpenWeatherMap is a popular choice for applications requiring both current weather and extended forecasts.
  • Data Provided: Real-time temperature, humidity, wind speed, air quality, precipitation probability, and more. Offers both current and forecast data, including minute-by-minute weather data for select locations.
  • Provider Selection: Include provider = 1 in the weather section of your request to select OpenWeatherMap as the weather provider.
  • Usage Notes: Offers free and paid tiers, with data accessible via API key authentication. Advanced data layers and premium features are available in paid plans.
  • API Documentation: Available here.

2. QWeather

  • Description: QWeather, also known as HeWeather, provides comprehensive weather data focused on China but includes international data as well. It offers extensive details such as real-time weather, forecasts, air quality information, and alerts.
  • Data Provided: Current temperature, humidity, UV index, pollution levels, daily and hourly forecasts, as well as warnings for severe weather conditions. Known for its granular air quality data and its real-time updates on changing weather conditions.
  • Provider Selection: Include provider = 2 in the weather section of your request to select QWeather as the weather provider.
  • Usage Notes: QWeather offers API access with free and premium tiers. The free tier provides limited data, while premium options expand to cover additional data points and locations.
  • API Documentation: Available here.

3. MET Weather (MET Norway)

  • Description: The MET Weather API, provided by MET Norway, gives access to a variety of open meteorological data, including forecasts, historical data, and specific data for Norway and the Nordic regions. Known for its accuracy and transparency, MET Weather is ideal for applications in need of highly reliable weather data.
  • Data Provided: Current weather conditions, forecasts, precipitation, temperature, wind data, and UV index. MET Weather offers specialized data for the Nordic regions but also supports global weather information.
  • Provider Selection: Include provider = 3 in the weather section of your request to select MET Weather as the weather provider.
  • Usage Notes: All data provided by MET Weather is freely available for use under a Creative Commons license, allowing both non-commercial and commercial applications without cost. MET Norway is renowned for its environmental data, making it a trusted provider, particularly in Europe.
  • API Documentation: Available here.

Example Request

/source/background.mc
function onTemporalEvent() as Void {
	var ds = System.getDeviceSettings();
	if (!ds.phoneConnected) { // Checks that the device is connected to the phone for sending the request
		return;
	}

	var id = ds.uniqueIdentifier;
	if (id == null) { // Verifies that the device has been assigned a unique identifier
		return;
	}

	var request = {};

	var lockCheck = Application.Storage.getValue("LastCodeCheckTimestamp");
	if (lockCheck == null || lockCheck <= Time.now().value()) { // Sends the code if necessary
		request.put("code", Application.Properties.getValue("UnlockCode"));
	}

	var ns_url = Application.Properties.getValue("NS");
	if (!ns_url.equals("")) { // Sends the NightScout app URL if needed
		request.put("bg", { "url" => ns_url });
	}

	var wP = Application.Properties.getValue("Weather");
	if (wP != 0) { // Sends weather request parameters if needed
		var lat = Application.Properties.getValue("latitude");
		var lon = Application.Properties.getValue("longitude");
		if (!lat.equals("") && !lon.equals("")) {
			request.put("weather", {
				"appid" => Application.Properties.getValue("appID"),
				"lat" => lat,
				"lon" => lon,
				"provider" => wP
			});
		}
	}

	if (!request.isEmpty()) {

		// Fills in the required request parameters
		request.put("device", id);
		request.put("app", p2uAppID); // your Application id
		request.put("model", ds.partNumber);

		Toybox.Communications.makeWebRequest(
			"https://api.p2u.io", // API Endpoint
			request,
			{
				:method => 3, // Communications.HTTP_REQUEST_METHOD_POST
				:headers => {
					"Content-Type" => 1 // Communications.REQUEST_CONTENT_TYPE_JSON
				},
				:responseType => 0 // Communications.HTTP_RESPONSE_CONTENT_TYPE_JSON
			},
			method(:onReceive)
		);
	}
}

API Response

The API returns a JSON object with information on unlock status, glucose level, and weather.

Response Parameters

Unlock Code Verification Results (if a request was sent):

  • response: integer — return code
  • msg: string — message about the verification result
  • expires: integer — expiration timestamp of the code in UNIXTIMESTAMP format
  • qr: array — QR code for purchase or serial number verification, if applicable

NightScout App Response (if a request was sent):

  • bg: associative array — formatted response from the NightScout app
    • value: integer — blood glucose level in mg/dL
    • date: integer — timestamp of the code expiration in UNIXTIMESTAMP format
    • direction: string — trend in blood glucose level change

Weather API Response (if a request was sent):

  • weather: associative array — formatted response from the Weather API
    • provider: integer — weather provider identifier
    • weather: array — current weather conditions. May return one or two values; if two values are returned, they represent day and night conditions
    • temp: float — current temperature in Celsius
    • feels_like: float — feels-like temperature in Celsius
    • pressure: integer — atmospheric pressure in hPa
    • humidity: integer — humidity in %
    • precipitation: integer — precipitation probability in %
    • wind: integer — wind direction in degrees
    • wind_speed: float — wind speed in m/s
    • temp_low: float — today’s low temperature in Celsius
    • temp_high: float — today’s high temperature in Celsius
    • sunrise_today: integer — today’s sunrise timestamp in UNIXTIMESTAMP format
    • sunset_today: integer — today’s sunset timestamp in UNIXTIMESTAMP format
    • sunrise_tomorrow: integer — tomorrow’s sunrise timestamp in UNIXTIMESTAMP format
    • sunset_tomorrow: integer — tomorrow’s sunset timestamp in UNIXTIMESTAMP format
    • aqi: associative array — air quality index
      • level: integer — air quality index level
      • value: integer — air quality index value

Example Response

https://api.p2u.io
{
	"response": 103,
	"msg": "Free for beta tester",
	"expires": 0,
	"qr": [
		"11111110111011010110101111111",
		"10000010111001001101001000001",
		"10111010101100110110101011101",
		"10111010110101000001001011101",
		"10111010000001010100001011101",
		"10000010100110001101001000001",
		"11111110101010101010101111111",
		"00000000010010110111100000000",
		"11001110000100100100100101111",
		"11111100011011011010011111111",
		"01111011100111111100101000001",
		"01111100101100110111011011011",
		"00110110101010100101110000010",
		"11001000010001011000001011111",
		"01101010001001110100000001101",
		"10111101100010100101100110011",
		"01010111111100110100100100010",
		"10000100111011011000101111011",
		"00000110110110110100100000101",
		"00111100011100001100101100011",
		"11110111110010100111111111001",
		"00000000111001011101100010001",
		"11111110010001011111101011101",
		"10000010100010100111100010010",
		"10111010101101100111111111001",
		"10111010010010110000010000001",
		"10111010001111111110000001111",
		"10000010111101011111101101011",
		"11111110100011011110110010010"
	],
	"bg": {
		"value": -102,
		"date": 1730546101,
		"direction": ""
	},
	"weather": {
		"provider": 1,
		"weather": [
			89
		],
		"temp": 0.27,
		"feels_like": -3.14,
		"pressure": 999,
		"humidity": 78,
		"precipitation": 0,
		"wind": 120,
		"wind_speed": 2.96,
		"temp_low": -3.8,
		"temp_high": 0.27,
		"sunrise_today": 1730527969,
		"sunset_today": 1730551770,
		"sunrise_tomorrow": 1730614492,
		"sunset_tomorrow": 1730638051,
		"aqi": {
			"level": 1,
			"value": 38
		}
	}
}

Notes

  • Requests with bg require a connection to the NightScout app.
  • For every request with a code, the API automatically checks the code status and activates it if inactive.
  • Please note that API parameters may be updated or modified over time to improve functionality, compatibility, and security. It is recommended to periodically review the API documentation for any changes that might affect integration or usage.

Garmin

ID Description Day Night
0 Clear
0x53

0x54
40 Fair
23 Mostly clear
0x55

0x56
1 Partly cloudy
0x57

0x58
22 Partly clear
2 Mostly cloudy
0x59
52 Thin clouds
20 Cloudy
0x5A
45 Cloudy chance of rain
31 Drizzle
0x3E
14 Light rain
0x42
24 Light showers
3 Rain
0x43
25 Showers
27 Chance of showers
0x46
11 Scattered showers
15 Heavy rain
26 Heavy showers
28 Chance of thunderstorms
0x36

0x37
12 Scattered thunderstorms
0x38
6 Thunderstorms
0x39
8 Fog
0x4E
9 Hazy
29 Mist
39 Haze
30 Dust
0x4F
35 Sand
33 Smoke
38 Volcanic ash
37 Sandstorm
13 Unknown precipitation
5 Windy
0x52
36 Squall
48 Flurries
32 Tornado
0x50
41 Hurricane
42 Tropical storm
50 Sleet
0x45
7 Wintry mix
18 Light rain snow
19 Heavy rain snow
21 Rain snow
49 Freezing rain
44 Chance of rain snow
47 Cloudy chance of rain snow
34 Ice
51 Ice snow
43 Chance of snow
0x4C

0x4D
16 Light snow
46 Cloudy chance of snow
0x4A
4 Snow
17 Heavy snow
0x4B
10 Hail
0x3A

Open Weather Map

ID Description Day Night
2xx Thunderstorm
200 Thunderstorm with light rain
0x36

0x37
201 Thunderstorm with rain
0x38
202 Thunderstorm with heavy rain
210 Light thunderstorm
211 Thunderstorm
0x39
212 Heavy thunderstorm
0x3B
221 Ragged thunderstorm
230 Thunderstorm with light drizzle
0x3A
231 Thunderstorm with drizzle
232 Thunderstorm with heavy drizzle
3xx Drizzle
300 Light intensity drizzle
0x3C

0x3D
301 Drizzle
0x3E
302 Heavy intensity drizzle
0x3F
310 Light intensity drizzle rain
0x40
311 Drizzle rain
312 Heavy intensity drizzle rain
0x41
313 Shower rain and drizzle
314 Heavy shower rain and drizzle
321 Shower drizzle
5xx Rain
500 Light rain
0x42
501 Moderate rain
0x43
502 Heavy intensity rain
0x44
503 Very heavy rain
504 Extreme rain
511 Freezing rain
0x45
520 Light intensity shower rain
0x46
521 Shower rain
522 Heavy intensity shower rain
531 Ragged shower rain
6xx Snow
600 Light snow
0x4C

0x4D
601 Snow
0x4A
602 Heavy snow
611 Sleet
0x45
612 Light shower sleet
613 Shower sleet
615 Light rain and snow
616 Rain and snow
620 Light shower snow
0x4B
621 Shower snow
622 Heavy shower snow
7xx Atmosphere
701 Mist
0x4E
711 Smoke
0x4F
721 Haze
731 Sand/ dust whirls
741 Fog
751 Sand
0x4F
761 Dust
762 Volcanic ash
771 Squalls
0x52
781 Tornado
0x50
800 Clear
800 Clear sky
0x53

0x54
80x Clouds
801 Few clouds 11-25%
0x55

0x56
802 Scattered clouds 25-50%
0x57

0x58
803 Broken clouds 51-84%
0x59
804 Overcast clouds 85-100%
0x5A

QWeather

You can check out the original set of weather icons by clicking here

ID Description Day Night
302 Thundershower
0x36

0x37
303 Heavy Thunderstorm
0x38
310 Rainstorm
0x39
317 Rainstorm to Heavy Rainstorm
304 Hail
0x3A
311 Heavy Rainstorm
0x3B
312 Severe Rainstorm
318 Heavy to Severe Rainstorm
309 Drizzle Rain
0x3C

0x3D
404 Sleet
0x3E
305 Light Rain
0x42
314 Light to Moderate Rain
306 Moderate Rain
0x43
315 Moderate to Heavy Rain
399 Rain
308 Extreme Rain
0x44
316 Heavy Rain to Rainstorm
313 Freezing Rain
0x45
405 Rain and Snow
300 Shower Rain
0x46
301 Heavy Shower Rain
307 Heavy Rain
350 Shower Rain
351 Heavy Shower Rain
400 Light Snow
0x4C

0x4D
408 Light to Moderate Snow
499 Snow
401 Moderate Snow
0x4A
402 Heavy Snow
409 Moderate to Heavy Snow
410 Heavy Snow to Snowstorm
403 Snowstorm
0x4B
406 Shower Rain and Snow
407 Snow Flurry
456 Shower Rain and Snow
457 Snow Flurry
503 Sand
0x4E
504 Dust
507 Duststorm
508 Sandstorm
511 Moderate Haze
512 Heavy Haze
513 Severe Haze
500 Mist
0x4F
501 Fog
502 Haze
509 Dense Fog
510 Strong Fog
514 Heavy Fog
515 Extra Heavy Fog
100 Sunny
0x53

0x54
150 Clear
101 Cloudy
0x55

0x56
151 Cloudy
102 Few Clouds
0x57

0x58
152 Few Clouds
103 Partly Cloudy
0x59
153 Partly Cloudy
104 Overcast
0x5A

MET Weather

ID Description Day Night
lightrainshowers Light rain showers
0x36

0x37
lightrainshowersandthunder Light rain showers and thunder
rainshowersandthunder Rain showers and thunder
heavyrainshowersandthunder Heavy rain showers and thunder
heavyrainandthunder Heavy rain and thunder
0x38
rainandthunder Rain and thunder
lightrainandthunder Light rain and thunder
0x39
heavysleetandthunder Heavy sleet and thunder
0x3B
lightsleetandthunder Light sleet and thunder
0x3A
lightssleetshowersandthunder Light sleet showers and thunder
sleetandthunder Sleet and thunder
lightsleetshowers Light sleet showers
0x3C

0x3D
sleetshowers Sleet showers
sleetshowersandthunder Sleet showers and thunder
heavysleetshowers Heavy sleet showers
heavysleetshowersandthunder Heavy sleet showers and thunder
lightsleet Light sleet
0x3E
sleet Sleet
0x3F
heavysleet Heavy sleet
0x45
lightrain Light rain
0x42
rain Rain
0x43
heavyrain Heavy rain
0x44
rainshowers Rain showers
0x46
heavyrainshowers Heavy rain showers
heavysnow Heavy snow
0x4B
heavysnowandthunder Heavy snow and thunder
snow Snow
snowandthunder Snow and thunder
lightsnowshowers Light snow showers
0x4C

0x4D
lightssnowshowersandthunder Light snow showers and thunder
snowshowers Snow showers
snowshowersandthunder Snow showers and thunder
heavysnowshowers Heavy snow showers
heavysnowshowersandthunder Heavy snow showers and thunder
lightsnow Light snow
0x4A
lightsnowandthunder Light snow and thunder
fog Fog
0x4F
clearsky Clear sky
0x53

0x54
fair Fair
0x55

0x56
partlycloudy Partly cloudy
0x57

0x58
cloudy Cloudy
0x59