GithubHelp home page GithubHelp logo

pi-platform-docs's Introduction

Frontend Javascript SDK

The JS SDK is the frontend SDK, designed to be used in your HTML pages or Single-Page Apps, served in the Pi Browser.

In order to enable the SDK to function correctly, you need to declare your apps on the Developer Portal (open develop.pi in the Pi Browser to access the Developer Portal).

This SDK is not for a server-side NodeJS app.

Installation

Add the following script tags to all pages where you need to call the Pi Apps SDK:

<script src="https://sdk.minepi.com/pi-sdk.js"></script>
<script>Pi.init({ version: "2.0" })</script>

This will load the Pi Network JS SDK as a global window.Pi object.

Usage

Authenticate a user

You cannot perform any user-related operations (e.g read the user's info, request a payment from them) until you have successfully authenticated the user. The first time, they will be presented with a dialog asking for their consent to share their data with your app.

// Authenticate the user, and get permission to request payments from them:
const scopes = ['payments'];

// Read more about this callback in the SDK reference:
function onIncompletePaymentFound(payment) { /* ... */ };

Pi.authenticate(scopes, onIncompletePaymentFound).then(function(auth) {
  console.log(`Hi there! You're ready to make payments!`);
}).catch(function(error) {
  console.error(error);
});

Request a payment (User-To-App)

The createPayment method enables you to request a payment from the current user to your app's account.

The user will be prompted with a modal provided by the Pi Wallet, enabling them to sign the transaction and submit it to the Pi Blockchain.

Pi.createPayment({
  // Amount of ฯ€ to be paid:
  amount: 3.14,
  // An explanation of the payment - will be shown to the user:
  memo: "...", // e.g: "Digital kitten #1234",
  // An arbitrary developer-provided metadata object - for your own usage:
  metadata: { /* ... */ }, // e.g: { kittenId: 1234 }
}, {
  // Callbacks you need to implement - read more about those in the detailed docs linked below:
  onReadyForServerApproval: function(paymentId) { /* ... */ },
  onReadyForServerCompletion: function(paymentId, txid) { /* ... */ },
  onCancel: function(paymentId) { /* ... */ },
  onError: function(error, payment) { /* ... */ },
});

Request a payment (App-To-User)

If you want to send Pi from your app to a user, you need to use one of Pi Network's backend SDKs, depending on the language your backend is written in. Refer to the Advanced payments guide for more information.

In order to make sure that all involved parties (your app, your server, the Pi servers, and the Pi Blockchain) are in sync, the payment needs to go through a Server-Side Approval flow (for User-to-App payment) and/or a Server-Side Completion flow (for all types of payments).

Please refer to:

pi-platform-docs's People

Contributors

aurelienshz avatar cryptoging avatar hklee93 avatar kokkalis avatar pasniczy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pi-platform-docs's Issues

Greetings

Can someone teach me about this app and how to pay

Pi Network Apps Platform Developer Sandbox | Question

Hey,

Is the Pi Network Apps Platform Developer Sandbox still available?
Yesterday I created a link to test my app in the developer sandbox, but the text is in Chinese, and I have no idea what it says.
I also don't know what I can do in this sandbox sins I can't navigate to URLs.

Could i get some more information about how to use the sandbox?

Greetings
Stan P
Schermafbeelding 2021-06-29 om 18 53 45

Account not found to complete payment.

When I want to complete a payment, I get an error that says "Account not found, Please check your passphrase again. A transaction was not submitted."

21-07-02-20-17-18.mp4

image

I tried reinstalling the pi-browser but I get the same results...
I also have this error on other people's applications.

Greetings
Stan P

Inconsistent timestamps

I have just noticed that the timestamps in wallet.pi are not consistent.

IMG_20210708_103946.jpg

IMG_20210708_104002.jpg

As you can see the timestamp on the payment history screen is my correct timezone (GMT) however the timezone when I click into the payment is UTC which makes the times an hour out.

500 error begin returned from /approve API endpoint.

I have created a second project as I cannot continue working on my first project until the pending project thing is sorted. Now when I try to call the /payments/paymentId/approve API its returning a 500 error

View code here

I'm doing the same thing as yesterday when the payment worked but I didn't complete it.

Is anyone else getting this error back from the /approve endpoint

Make PI games with unity?

Hi, I'm a unity game dev,(No published games yet) but I was wondering if there is a seperate api so I can make games for pi with unity?

Failed to execute 'postMessage' on 'DOMWindow'

Hello,

I was trying to use the pi-sdk with the example provided using the following HTML file

<!DOCTYPE html>
<html>
    <head>
        <!-- Pi SDK -->
        <script src="https://sdk.minepi.com/pi-sdk.js"></script>
    </head>
</html>
<script>
    const onOpenPaymentFound = (payment) => {
        console.log("in onOpenPaymentFound");
        console.log(payment);
    }

    const scopes = ["username", "payments"];

    Pi.authenticate(scopes, onOpenPaymentFound).then(function(auth) {
        console.log(`Hello ${auth.user.username}. Your unique ID is ${auth.user.pi_id}`);
    }).catch(function(error) {
        console.error(error);
    });
</script>

But I keep getting the following error in my console so I can't do anything with the pi-sdk.

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://app-cdn.minepi.com') does not match the recipient window's origin ('https://vhost.local.com').

https://vhost.local.com being my local domain but it gives me this error even on localhost and on the domain verified on Pi Developer Portal.

I saw a lot of solutions by using iframe but this will slow down the whole website and it still didn't work in my case.

Is this a problem I can fix from my side or is it something that should be fixed in the sdk?

Cannot complete payment

I have successfully completed the payment process and everything worked perfectly however my /complete API failed due to a code issue. I have fixed that problem but now I can't start another payment because I already have a pending payment.

IMG_20210701_184333.jpg

I know I could manually call the /complete endpoint with the paymentId but I didn't log it and lost the request output.

Here's the payment in my wallet:

IMG_20210701_184811.jpg

Does anyone know how long I will have to wait until I can make another payment?

P.s I will upload a server side guide to my github and share a link. I have done it using firebase cloud functions, node, express and axios for the API requests.

Refund

This is not an issue per se but a much needed functionality. Quite frequently an application would need to refund partial or full amount to the user ie the payer for many business reasons. Would this be provided in the SDK and API ? @aurelienshz
Thinking aloud could this be a negative amount in the Pi.createPayment call ?

Intercommunication between apps

When I redirect with location.href in JavaScript, from the domain app-domain1.com to the domain app-domain2.com, and both are registered domains in developer.pi, the functionalities of app-domain2.com, for payments, don't work.

Pi

Keep mining

Error! You already have a pending payment on this app, which needs an action from the developer.lf you're sure that you haven'talready made this payment, please try again later.

I have been able to place a normal order and pay successfully in PI browser. After an error was reported in a transaction last night, I could not continue the next transaction. I repeatedly prompted the following error, and I detected it and couldn't solve it. Now the situation is that my PI account can no longer place an order. Every time, the following prompt pops up to remind me that there is an order that has not been processed, but I have detected it and can't solve it. I need the project party to solve this @aurelienshz @kokkalis

Error!
You already have a pending
payment on this app, which needs an action from the developer.lf
you're sure that you haven'talready made this payment, please try again later.

onIncompletePaymentFound is called with payments with no txid / blockchain transaction

The documentation says that if you activated the function onIncompletePaymentFound() a PaymentDTO type must be given a response. The response should then also contain a txid , but it does not as you can see in the picture below.

I thought that the function onIncompletePaymentFound() would return a txid because it is written on the documentation.

Normally you should get this back:


  identifier: string, 
  user_uid: string, 
  amount: number, 
  memo: string, 
  metadata: Object,
  to_address: string,
  created_at: string, 
  
  status: {
    developer_approved: boolean,
    transaction_verified: boolean,
    developer_completed: boolean,
    cancelled: boolean,
    user_cancelled: boolean,
  },
  
  transaction: null
    txid: string,
    verified: boolean
    _link: string,
  },

BUT you get this back

  identifier: string,
  user_uid: string,
  amount: number, 
  memo: string, 
  metadata: object,uik
  to_address: string,
  created_at: string, 
  
  status: {
    developer_approved: boolean, 
    transaction_verified: boolean, 
    developer_completed: boolean, 
    cancelled: boolean,
    user_cancelled: boolean,
    transaction: null
  }

err

Error when calling the SDK

When i call Pi.authenticate i get this error:

main.js:8 Error: Pi Network SDK was not initialized. Call init() before any other method.
at k. (pi-sdk.js:1)
at pi-sdk.js:1
at Object.next (pi-sdk.js:1)
at pi-sdk.js:1
at new Promise ()
at Y (pi-sdk.js:1)
at k.authenticate (pi-sdk.js:1)

SDK2 does not provide Balance query

SDK1 implemented a Balance query api for app developer to know the current balance of his/her account. But SDK2 does not provide this. Is this being implemented, should be easy and quick to do? @aurelienshz

"Payment data is invalid. Please reach out to developer."

I'm having this issue. When I try to make a payment to the app, I have this messsage:

Title of the window: Error!
Message: "Payment data is invalid. Please reach out to developer."

I'm using these docs: https://github.com/pi-apps/pi-platform-docs

This is the code I'm using:
Example app (Pi Browser): https://piapp-example.latin-chain.com/
Code: https://github.com/rockcesar/PiNetworkDevelopments/blob/master/piapp-example/main.html

I have other code with the same issue:
Pidoku app (Pi Browser): https://sudoku.latin-chain.com/
Code: https://github.com/rockcesar/PiNetworkDevelopments/blob/master/sudoku/pidoku/functions.js

Snake app (Pi Browser): https://snake.latin-chain.com/
Code: https://github.com/rockcesar/PiNetworkDevelopments/blob/master/snake/responsive-snake/example/js/functions.js

Another example for Odoo: https://apps.odoo.com/apps/modules/14.0/website_pinetwork_odoo/

Server side example in PHP: https://github.com/rockcesar/PiNetworkDevelopments/blob/master/server1.php
Server side example in Odoo 13 and 14 (Python3): https://github.com/rockcesar/PiNetworkDevelopments/blob/master/website_pinetwork_odoo/controllers/main.py

Image of error:
pi_dev

Error messages when signing in with Google Auth

I have noticed that Pi SDK somehow captures sent messages and logs them in the console. Something like this:

Received message with non-string data: {type: "webpackOk", data: undefined}

I tried to add the "Login with Google" functionality to my app today, and I suddently saw a lot of errors:

pi-sdk.js:1 Native messaging: error when handling incoming message (possible response?). Error is logged below.

pi-sdk.js:1 SyntaxError: Unexpected token ! in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.handleIncomingMessage (pi-sdk.js:1)
    at pi-sdk.js:1

pi-sdk.js:1 !_{"h":"I0_1625585678994"}

I am not sure, but I think this has to do with the messages captured and logged by the Pi SDK. Why are those messages being logged? Is it possible to fix this errors?

Thank you

HTTP/1.1 500 Internal Server Error at POST /payments/:payment_id/approve

When I want to post with the paymentId to https://api.minepi.com/v2/payments/SomeRandomPaymentId/approve I get the error below the data that I sent:

DATA that I send to the API.

POST /v2/payments/PR1qHuKAjgfMDs5WB9DdFoHiq3I6/approve HTTP/1.1
Host: api.minepi.com
Authorization: Key uc7jkx................................................................................

DATA that the API sends back to me:

- HTTP/1.1 500 Internal Server Error
- content-type: text/html; charset=UTF-8
- content-length: 1635
- status: 500 Internal Server Error
- vary: Origin
- x-request-id: e68ad09d-2a79-4776-a71a-b6444181d01f
- x-runtime: 0.020006
- date: Wed, 30 Jun 2021 23:38:31 GMT
- x-powered-by: Phusion Passenger 6.0.6
- server: nginx/1.14.0 + Phusion Passenger 6.0.6
<!DOCTYPE html>
<html>
<head>
  <title>We're sorry, but something went wrong (500)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  .rails-default-error-page {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  .rails-default-error-page div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  .rails-default-error-page div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  .rails-default-error-page h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  .rails-default-error-page div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body class="rails-default-error-page">
  <!-- This file lives in public/500.html -->
  <div class="dialog">
    <div>
      <h1>We're sorry, but something went wrong.</h1>
    </div>
    <p>If you are the application owner check the logs for more information.</p>
  </div>
</body>
</html>

These are the headers that the server with error code 500 sends back to me:

- content-type: text/html; charset=UTF-8
- content-length: 1635
- status: 500 Internal Server Error
- vary: Origin
- x-request-id: e68ad09d-2a79-4776-a71a-b6444181d01f
- x-runtime: 0.020006
- date: Wed, 30 Jun 2021 23:38:31 GMT
- x-powered-by: Phusion Passenger 6.0.6
- server: nginx/1.14.0 + Phusion Passenger 6.0.6

Some more information:

- Status:
- 500 (Internal Server Error)
- Time:
- 1686 ms
- Size:
- 1.60 kb

Schermafbeelding 2021-07-01 om 01 54 57

This is an error on the API I hope this information is clear and that the error will be fixed soon. ๐Ÿ‘
I hope this will be seen as urgent as this is a big problem with the API. @aurelienshz

Greetings.

Greetings

Can someone teach me about this app and how to pay

Payment window closed JavaScript event

Hey guys, does anyone know if the payment window sends a JavaScript event I can catch so I can do some stuff once the user has successfully competed the payment and goes back to the website?

Basically my cart is cleared via a Ajax call so when the user closes the pi payment flow the cart is still populated until the user refreshes so I just want to force a refresh but can't seem to do it in onReadyForServerCompletion

Access to XMLHttpRequest at 'https://socialchain.app/api/events' from origin 'https://app-cdn.minepi.com' has been blocked by CORS

Having an issue with CORS when calling the Pi.createPayment() method. Has anyone else experienced this?

pi

createPayment

As you can see in the console output the user is authenticated and ready to make payments then the CORS error then an output of the incomplete payment. In the code image you see I call createPayment() straight away after authenticating the user.

This is running in Pi Browser and USB debugging through ADB and chrome dev tools

.

.

Error 500: We're sorry, but something went wrong (500)

Server-side:

REQUEST RAW

POST /v2/payments/:wmsuEPgPVmHELIuvji7xrudeAUw5/approve HTTP/1.1
Authorization: key l7o0qh1tls.............................................................................................................................
Host: api.minepi.com
Content-Type: application/json
Content-Length: 0

RESPONSE RAW

HTTP/1.1 500 Internal Server Error
content-type: text/html; charset=UTF-8
content-length: 1635
status: 500 Internal Server Error
vary: Origin
x-request-id: aac6a1b6-ecb4-492f-b41a-a14e70ddc19d
x-runtime: 0.022898
date: Wed, 30 Jun 2021 15:21:29 GMT
x-powered-by: Phusion Passenger 6.0.6
server: nginx/1.14.0 + Phusion Passenger 6.0.6

<title>We're sorry, but something went wrong (500)</title> <style> .rails-default-error-page { background-color: #EFEFEF; color: #2E2F30; text-align: center; font-family: arial, sans-serif; margin: 0; }

.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}

.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}

.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}

.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>

We're sorry, but something went wrong.

If you are the application owner check the logs for more information.

Does a Authorization: Bearer <user access token> work with the payment API ?

On the 'Platform API,' it said that there are 2 methods of authorization.

But when I scroll down to the payment references, I see that the description says 'Authorization method: Server API Key'

Does this mean that a Bearer token can not be used with the payment API?
This is weird because at the top of the page it says that there are 2 methods of verification.

I ask this because I'm trying to do a test payment but it does not work.

You can see my code ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

window.Pi.authenticate(scopes, onIncompletePaymentFound).then(function (auth) {
        document.getElementById('pay-pi_button').addEventListener('click', () => {
            Pi.createPayment({
                amount: 3.14,
                memo: "This is the description.",
                metadata: { data: "This is a test object." },
            }, {
                onReadyForServerApproval: function (paymentId) { ApiRequest({ user_token: auth.accessToken, method: 'POST', paymentId, endPath: 'approve', txid: '' }) },
                onReadyForServerCompletion: function (paymentId, txid) { ApiRequest({ user_token: auth.accessToken, method: 'POST', paymentId, endPath: 'complete', txid }) },
                onCancel: function (paymentId) { },
                onError: function (error, payment) { },
            });
        })

    }).catch(function (error) {
        alert(error)
    });

    function ApiRequest(data) {
        let basepath = "api.minepi.com/v2"
        fetch(`${basepath}/payments/${data.paymentId}/${data.endPath}`, {
            method: data.method,
            headers: {
                "Authorization": `Bearer ${data.user_token}`
            },
            body: {
                "txid": data.txid
            }
        })
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.