I have followed the usage as per link below:
https://www.npmjs.com/package/react-native-paytm
This is my checksum generation code:
import Checksum
# initialize a dictionary
paytmParams = dict()
# put checksum parameters in Dictionary
paytmParams["MID"] = "*****************"
paytmParams["ORDER_ID"] = 'ORD001'
paytmParams["CUST_ID"] = 'CUST001'
paytmParams["INDUSTRY_TYPE_ID"] = 'Retail'
paytmParams["CHANNEL_ID"] = 'WAP'
paytmParams["TXN_AMOUNT"] = '1.00'
paytmParams["WEBSITE"] = 'WEBSTAGING'
paytmParams["EMAIL"] = '**************'
paytmParams["MOBILE_NO"] = '****************'
paytmParams["CALLBACK_URL"] = 'https://securegw-
stage.paytm.in/theia/paytmCallback?ORDER_ID=ORD001'
# Find your Merchant Key in your Paytm Dashboard at
https://dashboard.paytm.com/next/apikeys
checksum = Checksum.generate_checksum(paytmParams, "*************")
Code for react native:
import paytm from 'react-native-paytm';
import { Platform, DeviceEventEmitter, NativeModules,NativeEventEmitter} from 'react-native';
const paytmConfig = {
MID: '************',
WEBSITE: 'WEBSTAGING',
CHANNEL_ID: 'WAP',
INDUSTRY_TYPE_ID: 'Retail',
CALLBACK_URL: 'https://securegw-
stage.paytm.in/theia/paytmCallback?ORDER_ID=ORD001'
}
onPayTmResponse(response) {
// Process Response
// response.response in case of iOS
// reponse in case of Android
console.log(response);
}
runTransaction() {
const callbackUrl = 'https://securegw-
stage.paytm.in/theia/paytmCallback?ORDER_ID=ORD001'
const details = {
mode: 'Staging', // 'Staging' or 'Production'
mid: paytmConfig.MID,
industryType: paytmConfig.INDUSTRY_TYPE_ID,
website: paytmConfig.WEBSITE,
channel: paytmConfig.CHANNEL_ID,
amount: '1.00', // String
orderId: 'ORD001', // String
custId: 'CUST001', // String
email: '*****************', // String
phone: '***********', // S
checksumhash: '***********************************************', //From your server using PayTM Checksum Utility
callback: callbackUrl
};
paytm.startPayment(details);
}
The issue is that i cant even spot the error point here as there is no console. I could use some direction here. Need this for staging right now
in my cash use this npm #philly25/react-native-paytm and solved this error
are you sure onPaytmResponse is a paytm listener
like this:
componentWillMount() {
Paytm.addListener(Paytm.Events.PAYTM_RESPONSE, this.onPayTmResponse)
};
componentWillUnmount() {
Paytm.removeListener(Paytm.Events.PAYTM_RESPONSE, this.onPayTmResponse);
};
Related
Has anyone tried to use the new PaymentElement in Stripe?
According to the documentation, the payment_method_types need to be configured in the server side and the client side will automatically configure it after retrieving the client_secret . I've followed all the steps in the documentation and all other payment methods I've selected are working but the client side will not configure FPX
Here's a screenshot of the output. As you can see, it's configuring card payment, grabpay and alipay but it isn't configuring fpx payment:
Screenshot of Output
Reference to Stripe Documentation that I'm following: https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=elements
Backend view -Django
# stripe payment key
stripe.api_key = 'sk_test_<<SECRET_KEY>>'
#api_view(['POST'])
def test_payment(request):
data = request.data
amount = int(float(data['amount']) * 100)
intent = stripe.PaymentIntent.create(
amount=amount,
currency='myr',
payment_method_types=['card', 'fpx', 'grabpay', 'alipay', ],
)
return Response(status=status.HTTP_200_OK, data=intent)
placeorder.js
import React, {useState, useEffect} from 'react'
import axios from 'axios'
//UI components
import Message from '../components/Message'
import Loader from '../components/Loader'
//---------- STRIPE PAYMENT COMPONENTS -------------//
import {Elements} from '#stripe/react-stripe-js'
import {loadStripe} from "#stripe/stripe-js/pure"
import CheckoutForm from "../components/CheckoutForm"
//dev-based publishable key
const stripePromise = loadStripe('pk_test_<<PUBLISHABLE_KEY');
const PlaceOrder = () => {
/* .
.
bunch of other code
.
.
-----*/
const [amount, setAmount] = useState(0)
let [clientSecret, setClientSecret] = useState('')
useEffect(()=> {
if(cart.totalPrice > 0) {
setAmount(cart.totalPrice )
}
//get client_secret
(async () => {
if(amount>0 && clientSecret === ''){
//fetch client secret
const response = await axios.post('/api/orders/payment/test-payment/',
{'amount':amount}
)
// set client secret
const cs = await response.data.client_secret
setClientSecret(cs)
setStripeLoading(false)
}
})()
if(!stripeLoading){
setOptions({
clientSecret: clientSecret,
appearance : {
theme: 'stripe'
}
})
console.log("options2:", options)
}
},[amount, cart.totalPrice, stripeLoading])
return (
<>
{(options === '')
? <Loader/>
: <Elements stripe={stripePromise} options={options} >
<CheckoutForm amount={amount} method={paymentMethod}/>
</Elements>
}
</>)}
export default PlaceOrder
Checkout.js
import React, {useState, useEffect} from 'react'
//stripe componetns
import {useStripe, useElements, PaymentElement} from '#stripe/react-stripe-js';
//UI elements
import {Form, Button, Row, Col} from 'react-bootstrap'
import Message from './Message'
import Loader from './Loader'
const CheckoutForm = ({amount, method}) => {
const [error, setError] = useState('')
const [email, setEmail] = useState('');
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async (e) => {
//prevent default submission and page refresh
e.preventDefault();
if (!stripe || !elements) {
// Stripe.js has not yet loaded.
setError("Stripe or Stripe elements have not loaded yet")
return;
}
const {error} = await stripe.confirmPayment({
//`Elements` instance that was used to create the Payment Element
elements,
confirmParams: {
return_url: '/placeorder',
},
if (error) {
setError("Error: Something went wrong")
}
});
return (
<Form onSubmit={handleSubmit} className="stripe-form">
{/* display error message */}
{error && <Message variant="danger">{error}</Message>}
<PaymentElement id="payment-element"/>
<div className="d-grid">
<Button type="submit" variant="primary" className="my-3 mt-4" disabled={!stripe}>
Submit Payment
</Button>
</div>
</Form>
)
}
export default CheckoutForm
PS. I haven't yet configured stripe to accept payments yet. I'm still trying to figure out why it won't configure FPXPayments in the PaymentElement in the frontend.
Thanks in advance!
previously FPX wasn't available in the Payment Element, but it is now. You can see supported payment methods here.
I'm trying to retrieve data programmatically through websockets and am failing due to my limited knowledge around this. On visiting the site at https://www.tradingview.com/chart/?symbol=ASX:RIO I notice one of the websocket messages being sent out is ~m~60~m~{"m":"quote_fast_symbols","p":["qs_p089dyse9tcu","ASX:RIO"]}
My code is as follows:
from websocket import create_connection
import json
ws = create_connection("wss://data.tradingview.com/socket.io/websocket?from=chart%2Fg0l68xay%2F&date=2019_05_27-12_19")
ws.send(json.dumps({"m":"quote_fast_symbols","p"["qs_p089dyse9tcu","ASX:RIO"]}))
result = ws.recv()
print(result)
ws.close()
Result of the print:
~m~302~m~{"session_id":"<0.25981.2547>_nyc2-charts-3-webchart-5#nyc2-compute-3_x","timestamp":1558976872,"release":"registry:5000/tvbs_release/webchart:release_201-106","studies_metadata_hash":"888cd442d24cef23a176f3b4584ebf48285fc1cd","protocol":"json","javastudies":"javastudies-3.44_955","auth_scheme_vsn":2}
I get this result no matter what message I send out, out of the almost multitude of messages that seem to be sent out. I was hoping one of the messages sent back will be the prices info for the low and highs for RIO. Is there other steps I should include to get this data? I understand there might be some form of authorisation needed but I dont know the workflow.
Yes, there is much more to setup and it needs to be done in order. The following example written in Node.js will subscribe to the BINANCE:BTCUSDT real time data and fetch historical 5000 bars on the daily chart.
Ensure you have proper value of the origin field set in header section before connecting. Otherwise your connection request will be rejected by the proxy. I most common ws there is no way to do this. Use faye-websocket instead
const WebSocket = require('faye-websocket')
const ws = new WebSocket.Client('wss://data.tradingview.com/socket.io/websocket', [], {
headers: { 'Origin': 'https://data.tradingview.com' }
});
After connecting you need to setup your data stream. I don't know if all of this commands needs to be performed. This probably can be shrink even more but it works. Basically what you need to do is to create new quote and chart sessions and within these sessions request stream of the data of the prior resolved symbol.
ws.on('open', () => {
const quote_session = 'qs_' + getRandomToken()
const chart_session = 'cs_' + getRandomToken()
const symbol = 'BINANCE:BTCUSDT'
const timeframe = '1D'
const bars = 5000
sendMsg(ws, "set_auth_token", ["unauthorized_user_token"])
sendMsg(ws, "chart_create_session", [chart_session, ""])
sendMsg(ws, "quote_create_session", [quote_session])
sendMsg(ws, "quote_set_fields", [quote_session,"ch","chp","current_session","description","local_description","language","exchange","fractional","is_tradable","lp","lp_time","minmov","minmove2","original_name","pricescale","pro_name","short_name","type","update_mode","volume","currency_code","rchp","rtc"])
sendMsg(ws, "quote_add_symbols",[quote_session, symbol, {"flags":['force_permission']}])
sendMsg(ws, "quote_fast_symbols", [quote_session, symbol])
sendMsg(ws, "resolve_symbol", [chart_session,"symbol_1","={\"symbol\":\""+symbol+"\",\"adjustment\":\"splits\",\"session\":\"extended\"}"])
sendMsg(ws, "create_series", [chart_session, "s1", "s1", "symbol_1", timeframe, bars])
});
ws.on('message', (msg) => { console.log(`RX: ${msg.data}`) })
And finally implementation of the helper methods
const getRandomToken = (stringLength=12) => {
characters = 'abcdefghijklmnopqrstuvwxyz0123456789'
const charactersLength = characters.length;
let result = ''
for ( var i = 0; i < stringLength; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength))
}
return result
}
const createMsg = (msg_name, paramsList) => {
const msg_str = JSON.stringify({ m: msg_name, p: paramsList })
return `~m~${msg_str.length}~m~${msg_str}`
}
const sendMsg = (ws, msg_name, paramsList) => {
const msg = createMsg(msg_name, paramsList)
console.log(`TX: ${msg}`)
ws.send(createMsg(msg_name, paramsList))
}
Based off of https://stackoverflow.com/a/17981327/9614384:
import dbus
bus = dbus.SessionBus()
screensaver = bus.get_object('org.gnome.ScreenSaver', '/')
print(bool(screensaver.GetActive()))
I'm trying to access the screensaver since this has changed in Ubuntu 18.04, but this code gives me the following error:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: No such interface '(null)' on object at path /
Scott's EDIT produces an error on my Ubuntu 18.04 machine running python3:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NotSupported: This method is not implemented
I suppose the code for all available screensavers should read:
import dbus
session_bus = dbus.SessionBus()
screensaver_list = ['org.gnome.ScreenSaver',
'org.cinnamon.ScreenSaver',
'org.kde.screensaver',
'org.freedesktop.ScreenSaver']
for each in screensaver_list:
try:
object_path = '/{0}'.format(each.replace('.', '/'))
get_object = session_bus.get_object(each, object_path)
get_interface = dbus.Interface(get_object, each)
status = bool(get_interface.GetActive())
print(status)
except dbus.exceptions.DBusException:
pass
BTW, the same exercise in C results in the below code:
#include<dbus/dbus.h>
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int scrstat(DBusConnection* conn, const char* scrdbus) {
bool* retbl = NULL;
char* scrobj;
DBusMessage* msg;
DBusMessageIter MsgIter;
DBusPendingCall* pending;
int i;
scrobj = (char *) malloc((1+strlen(scrdbus))*sizeof(char));
strncpy(scrobj,"/", 2*sizeof(char));
strncat(scrobj,scrdbus,strlen(scrdbus)*sizeof(char));
for(i=0;i<strlen(scrobj);i++) {
if(scrobj[i] == '.') scrobj[i] = '/';
}
// create a new method call and check for errors
msg = dbus_message_new_method_call(scrdbus, // target for the method call
scrobj, // object to call on
scrdbus, // interface to call on
"GetActive"); // method name
if (NULL == msg) {
fprintf(stderr, "Message NULL.\n");
return(1);
}
// send message and get a handle for a reply
if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
fprintf(stderr, "Out of memory.\n");
return(1);
}
if (NULL == pending) {
fprintf(stderr, "Pending call NULL.\n");
return(1);
}
// free message
dbus_message_unref(msg);
// block until we recieve a reply
dbus_pending_call_block(pending);
if(!dbus_message_iter_init(msg, &MsgIter)) { //msg is pointer to dbus message received
fprintf(stderr, "Message without arguments.\n");
return(1);
}
if (DBUS_TYPE_BOOLEAN == dbus_message_iter_get_arg_type(&MsgIter)){
dbus_message_iter_get_basic(&MsgIter, &retbl);//this function is used to read basic dbus types like int, string etc.
fprintf(stdout, retbl ? "Screensaver status: on.\n" : "Screensaver status: off.\n");
}
// free the pending message handle
dbus_pending_call_unref(pending);
free(scrobj);
return(0);
}
int main() {
const char* scrdbus[5];
scrdbus[0] = "org.cinnamon.ScreenSaver";
scrdbus[1] = "org.freedesktop.ScreenSaver";
scrdbus[2] = "org.gnome.ScreenSaver";
scrdbus[3] = "org.kde.Screensaver";
scrdbus[4] = NULL;
DBusConnection* conn;
DBusError err;
int i=0;
// initialise the errors
dbus_error_init(&err);
conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
if (dbus_error_is_set(&err)) {
fprintf(stderr, "Connection error (%s).\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn) {
fprintf(stderr, "Connection NULL.\n");
return(1);
}
while(NULL != scrdbus[i]) {
scrstat(conn, scrdbus[i]);
i++;
}
dbus_connection_unref(conn);
return(0);
}
The above code compiles using gcc:
gcc -pthread -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -o scrstat scrstat.c -ldbus-1
The beauty of python3 lies in 17 lines of codes instead of 98 lines. The beauty of C lies in 10 milliseconds execution time instead of 128 milliseconds.
Taken from https://askubuntu.com/questions/623195/how-to-get-gnome-session-idle-time, I was able to answer my own question with this:
import dbus
session_bus = dbus.SessionBus()
gnome_screensaver = 'org.gnome.ScreenSaver'
object_path = '/{0}'.format(gnome_screensaver.replace('.', '/'))
get_object = session_bus.get_object(gnome_screensaver, object_path)
get_interface = dbus.Interface(get_object, gnome_screensaver)
status = bool(get_interface.GetActive())
object_path is created by replacing . with /, and gets the object with get_object,
What I was missing before was dbus.Interface, which is actually referenced at https://dbus.freedesktop.org/doc/dbus-python/tutorial.html#interfaces-and-methods
EDIT:
This catches all of the available screensavers:
import dbus
session_bus = dbus.SessionBus()
screensaver_list = ['org.gnome.ScreenSaver',
'org.cinnamon.ScreenSaver',
'org.kde.screensaver',
'org.freedesktop.ScreenSaver']
for each in screensaver_list:
try:
object_path = '/{0}'.format(each.replace('.', '/'))
get_object = session_bus.get_object(each, object_path)
get_interface = dbus.Interface(get_object, each)
status = bool(get_interface.GetActive())
print(status)
except dbus.exceptions.DBusException:
pass
i am trying to load an efi application from another efi application using loadimage and startimage protocols. but loadimage is getting succeeded,startimage failing with return value -1/0xffffffff. it would be very helpful if any one suggest some ideas, why it is failing. if there is any mistake in code please correct it.
EFI_STATUS LoadPythonBinary()
{
EFI_STATUS Status;
UINTN NumberOfFSHandles;
EFI_HANDLE *FSHandles;
EFI_GUID SimpleFileSystemGuid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
UINTN Index = 0;
EFI_BLOCK_IO *BlkIo;
EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *FileSysProtocol = NULL;
EFI_DEVICE_PATH_PROTOCOL *FilePath;
EFI_HANDLE ImageHandle2 = NULL;
// EFI_DEVICE_PATH_PROTOCOL *DevicePath;
// EFI_HANDLE DeviceHandle;
EFI_HANDLE Controller=NULL;
EFI_LOADED_IMAGE_PROTOCOL *ImageInfo;
EFI_GUID EfiDevicePathProtocolGuid = EFI_DEVICE_PATH_PROTOCOL_GUID;
EFI_GUID EfiBlockIoProtocolGuid = EFI_BLOCK_IO_PROTOCOL_GUID;
const CHAR16 *FileName = L"Python.efi";
EFI_GUID EfiLoadedImageProtocol = EFI_LOADED_IMAGE_PROTOCOL_GUID;
// EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
char temp[MAX_PATH];
CHAR16 CmdLineParams[MAX_PATH] = L"fs0:\\GK\\Temp\\UnzipBuildTools.py fs0:\\GK\\Temp\\EFI.zip fs0:\\Test";
strcpy(temp,(const char *)StrDup16to8(CmdLineParams));
Status = gBS->LocateHandleBuffer(ByProtocol, &SimpleFileSystemGuid,NULL, &NumberOfFSHandles, &FSHandles);
if(!EFI_ERROR(Status))
{
for(Index = 0; Index < NumberOfFSHandles; Index++)
{
Status = gBS->HandleProtocol(FSHandles[Index], &SimpleFileSystemGuid, &BlkIo);
if(!EFI_ERROR(Status))
{
FilePath = FileDevicePath(FSHandles[Index],FileName);
Status = gBS->LoadImage(TRUE, gImageHandle, FilePath, NULL, 0, &ImageHandle2);
printf("Load Image Status = %x", Status);
if(!EFI_ERROR(Status))
{
printf("Image Loaded Successfully\n");
Status = gBS->HandleProtocol(ImageHandle2, &EfiLoadedImageProtocol,(VOID**)&ImageInfo);
if(!EFI_ERROR(Status))
{
if(ImageInfo->ImageCodeType == EfiLoaderCode)
{
gBS->FreePool(FilePath);
}
printf("Options :%s\n",temp);
printf("LoadedImage->ImageSize = %x", ImageInfo->ImageSize);
ImageInfo->LoadOptions = CmdLineParams;
ImageInfo->LoadOptionsSize = (UINT32)(wcslen(CmdLineParams));
ImageInfo->DeviceHandle = gImageHandle;
}
}
printf("About to start image\n");
Status = gBS->StartImage(ImageHandle2, NULL, NULL);
printf("StartImage Status = %x", Status);
if(!EFI_ERROR(Status))
{
printf("StartImage success\n");
break;
}
}
}
}
return Status;
}
Possible problem: Probably your target image (Python.efi) is not a valid UEFI application and can't be loaded by EFI_BOOT_SERVICES.StartImage() interface. For more information please consult the valid types of UEFI images loadable by UEFI boot service, check the session 7.4 in UEFI Spec 2.7.
Solution: Make sure that in the target application .inf file, the field MODULE_TYPE is configured with UEFI_APPLICATION and its .c file has the entry point signature to an UEFI application similar to:
EFI_STATUS
EFIAPI
MyEntryPointName (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
...
}
A functional code example can be consulted in LoadImageApp. This application load and start a target application named
HelloImageEntryPoint.efi with success.
-1 is not a valid EFI_STATUS if you are on a 64-bit system EFI_STATUS is 64-bit. Also if you use Print() %r will print out a string for EFI_STATUS.
The EFI_STATUS values returned from EFI services are define in the EFI Spec:
EFI_INVALID_PARAMETER - ImageHandle is either an invalid image handle or the image has already been initialized with StartImage
EFI_SECURITY_VIOLATION - The current platform policy specifies that the image should not be started.
Exit code from image - Exit code from image.
So did the code you loaded return an error back to you?
I want to register the hotkey
So, I added key types
key_types.h
static const KeyID kKeyHangul = 0xEF31; /* Zenkaku/Hankaku */ //asmera modify to 0xef31 from 0xef26
key_types.cpp
keyNameMap[][]
{ "Hangul", kKeyHangul }
MSWindowsKeyState.cpp
/* 0x015 */ { kKeyHangul },
/* 0x115 */ { kKeyHangul },
and config script is
section: screens
server:
client1:
end
section: aliases
server:
YOO-Lab
client1:
YOO-SURFACE
end
section: links
# server:
# down = client1
# client:
# up = server
end
section: options
screenSaverSync = false
keystroke(control+1) = switchToScreen(server)
keystroke(control+2) = switchToScreen(client1)
#?? keystroke(ctrl+alt+space) = Hangul
end
I want to know how to convert (Ctrl+Alt+Space) to (Hangul)key
This works for me - Control+Alt+Space
Check out this reference for more keys: https://github.com/symless/synergy/blob/master/src/lib/synergy/key_types.cpp