How to use callback_url in razorpay intergration? - callback

I want to log all failed and success response of payment. Handler option return payment id in the success case and nothing in the failure case. How to log failure payment id?
var options = {
"key": "API_KEY",
"amount": "2000", // 2000 paise = INR 20
"name": "Product",
"callback_url":"http://myweb.com/process.php",
"description": "Purchase Description",
"image": "https://myweb.com/images/image.png",
"handler": function (response){
alert(response.razorpay_payment_id);
},
"prefill": {
"name": "Harshil Mathur",
"email": "harshil#razorpay.com"
},
"notes": {
"address": "Hello World"
},
"theme": {
"color": "#F37254"
}
};
var rzp1 = new Razorpay(options);
document.getElementById('rzp-button1').onclick = function(e){
rzp1.open();
e.preventDefault();
}

There is a concept called webhook in razorpay
You can get every response to that hook and you can capture anything from there
Please goahead Razorpay webhook

Related

PayPal Invoicing API - VALIDATION_ERROR

I am developing an application that communicates with PayPal's API to create invoices.
This is my Request Body:
{
"detail": {
"currency_code": "USD",
"note": "Thank you for using my services!"
},
"invoicer": {
"name": {
"given_name": "Shreyas",
"surname": "Ayyengar"
},
"email_address": "{email}",
"website": "{website}"
},
"primary_recipients": [
{
"billing_info": {
"email_address": "{client_email}"
}
}
],
"items": [
{
"name": "{invoice_name}",
"description": "{invoice_description}",
"quantity": "1",
"unit_amount": {
"currency_code": "USD",
"value": "{invoice_amount}"
},
"tax": {
"name": "PayPal Service Tax",
"percent": "7.25"
}
}
],
"configuration": {
"partial_payment": {
"allow_partial_payment": false
},
"allow_tip": true
}
}
While there are placeholders like: {client_email}, I can guarantee that they are replacing properly and as expected.
However I'm thrown a VALIDATION_ERROR which I am not able to understand: {"name":"VALIDATION_ERROR","message":"Invalid request - see details.","information_link":"https://developer.paypal.com/docs/api/invoicing/#errors","details":[{"field":"merchant_info","issue":"cannot be null."},{"field":"items[0].unit_price","issue":"null"}]}
From what I can minimally understand, this error says that I have missing information like Items[].unit_price and merchant_info however I have no idea where this is supposed to be in my Request Body. I am following the direct documentationhere but I cannot see anything that mentions unit_price or merchant_info.
Submit your request to the correct API endpoint, https://api-m.sandbox.paypal.com/v2/invoicing/invoices
Note the major version number. See the Invoicing API reference for details.

How to create a variable recurring payment in paypal in node.js

I've signed up to a paypal business account. I've been trying to create a variable recurring payment using paypal. But with no luck. I could not find any working code that can accomplish this.
Things I've tried:
Subscriptions: I've checkout subscriptions too but subscriptions seem to be having fixed amount.
Paypal-rest-sdk: Paypal rest sdk won't let me change the payment_definitions most probably because it is just creating a standard subscription and not a variable one
(async function() {
const paypal = require("paypal-rest-sdk");
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': process.env.PAYPAL_CLIENT_ID,
'client_secret': process.env.PAYPAL_SECRET_KEY
});
var billingPlanAttributes = {
"description": "Create Plan for Regular",
"merchant_preferences": {
"auto_bill_amount": "yes",
"cancel_url": "http://www.cancel.com",
"initial_fail_amount_action": "continue",
"max_fail_attempts": "1",
"return_url": "http://www.success.com",
"setup_fee": {
"currency": "USD",
"value": "25"
}
},
"name": "Testing1-Regular1",
"payment_definitions": [
{
"amount": {
"currency": "USD",
"value": "100"
},
"charge_models": [
{
"amount": {
"currency": "USD",
"value": "10.60"
},
"type": "SHIPPING"
},
{
"amount": {
"currency": "USD",
"value": "20"
},
"type": "TAX"
}
],
"cycles": "0",
"frequency": "MONTH",
"frequency_interval": "1",
"name": "Regular 1",
"type": "REGULAR"
}
],
"type": "INFINITE"
};
const createdBillingPlan = await new Promise((resolve, reject) => {
paypal.billingPlan.create(billingPlanAttributes, function (error, createdBillingPlan) {
if (error) {
reject(error);
} else {
resolve(createdBillingPlan)
}
});
});
// update
var billing_plan_update_attributes = [
{
"op": "replace",
"path": "/",
"value": {
"payment_definitions": [
{
...createdBillingPlan.payment_definitions[0],
"amount": {
"currency": "INR",
"value": 100
}
}
]
}
}
];
console.log(billing_plan_update_attributes);
paypal.billingPlan.update(createdBillingPlan.id, billing_plan_update_attributes, function (error, response) {
if (error) {
console.log(error.response);
throw error;
} else {
paypal.billingPlan.get(createdBillingPlan.id, function (error, updatedBillingPlan) {
if (error) {
console.log(error.response);
throw error;
} else {
console.log(JSON.stringify(updatedBillingPlan));
}
});
}
});
})();
Above code throws
{ name: 'BUSINESS_VALIDATION_ERROR',
details:
[ { field: 'payment_definitions',
issue: 'patch is not supported for this field.' } ],
message: 'Validation Error.',
information_link:
'https://developer.paypal.com/docs/api/payments.billing-plans#errors',
debug_id: 'someid',
httpStatusCode: 400 }
Some links I've found interesting are:
https://www.paypal-community.com/t5/Merchant-services-Archive/Subscription-with-variable-amount-per-month/td-p/49864
https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECRecurringPayments/#
If some one could help me with some working code that creates a new recurring payment subscription / plan I'd really appreciate it.
No, you are wrong subscriptions are not fixed price. There is an option like seat-based pricing in subscriptions. All you need to do is modify your JSON when you creating a plan. Here is an example plan JSON for 1 USD base price.
{
"product_id": "PROD-60L70341GH758414Y",
"name": "Basic Plan",
"description": "Basic plan",
"billing_cycles": [
{
"frequency": {
"interval_unit": "MONTH",
"interval_count": 1
},
"tenure_type": "REGULAR",
"sequence": 1,
"total_cycles": 12,
"pricing_scheme": {
"fixed_price": {
"value": "1",
"currency_code": "USD"
}
}
}
],
"payment_preferences": {
"service_type": "PREPAID",
"auto_bill_outstanding": true,
"setup_fee_failure_action": "CONTINUE",
"payment_failure_threshold": 3
},
"quantity_supported": true
}
The most important part in here is quantity_supported": true, it indicates that you can give quantity property when creating a subscription. Lets say you want to create a subscription with 12 USD then all you need to do is give quantity as 12. When creating a subscription your JSON may like this
'plan_id': 'P-6AG14992W7150444HLUYGM5I',
'quantity': "12"
Hope it helps.

How can I trigger a `action.intent.INTENT_NAME` intent from my webhook?

I want to create a chatbot with Dialogflow and Google Assistant along with Google Transactions API for enabling a user to order a chocolate box. For now my agent contains the following four intents:
Default Welcome Intent (text response: Hello, do you want to buy a chocolate box?)
Default Fallback Intent
Int1 (training phrase: Yes, I want, fulfilment: enabled webhook call)
Int2 (event: actions_intent_TRANSACTION_REQUIREMENTS_CHECK )
I am using Dialogflow Json instead of Node.js to connect my agent with Transactions API. I want to test that the user meets the transaction requirements (when ordering the chocolate box) by using the actions.intent.TRANSACTION_REQUIREMENTS_CHECK action of Google actions. For this reason, following Google docs, when Int1 is triggered I am using a webhook which connect Google Assistant to the following python script (back-end):
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import requests
app = Flask(__name__)
CORS(app)
#app.route("/", methods=['POST'])
def index():
data = request.get_json()
intent = data["queryResult"]["intent"]["displayName"]
if (intent == 'Int1'):
return jsonify({ "data": {
"google": {
"expectUserResponse": True,
"isSsml": False,
"noInputPrompts": [],
"systemIntent": {
"data": {
"#type": "type.googleapis.com/google.actions.v2.TransactionRequirementsCheckSpec",
"paymentOptions": {
"actionProvidedOptions": {
"displayName": "VISA-1234",
"paymentType": "PAYMENT_CARD"
}
}
},
"intent": "actions.intent.TRANSACTION_REQUIREMENTS_CHECK"
}
}
}
})
else:
return jsonify({'message': 'HERE'})
if __name__== "__main__":
app.run(debug=True)
The json which I return above when intent = 'Int1' is the one specified at Google docs for "Checking requirements with your own payment method".
According to Google docs, this must be done next:
Receiving the result of a requirements check
After the Assistant fulfills the intent, it sends your fulfillment a
request with the actions.intent.TRANSACTION_REQUIREMENTS_CHECK intent
with the result of the check.
To properly handle this request, declare a Dialogflow intent that's
triggered by the actions_intent_TRANSACTION_REQUIREMENTS_CHECK event.
For this reason, I defined Int2 and as its event the actions_intent_TRANSACTION_REQUIREMENTS_CHECK.
However, I do not receive anything at my back-end like a result of the check and therefore I do not know if the action actions.intent.TRANSACTION_REQUIREMENTS_CHECK is really triggered. Why is this happening?
In general, how can I trigger one actions.intent.INTENT_NAME intent from my webhook/back-end?
When I am using the v2 version of Dialogflow, I am getting the following info/message about the webhook on Dialogflow when Int1 is triggered:
"webhookStatus": {
"code": 3,
"message": "Webhook call failed. Error: Failed to parse webhook JSON response: Cannot find field: data in message google.cloud.dialogflow.v2.WebhookResponse."
}
In the same case, I am getting the following info/message about the webhook on Google Assistant simulator when Int1 is triggered:
"responseMetadata": {
"status": {
"code": 14,
"message": "Webhook error (206)"
}
Finally, let me mention that I am testing all this with Python and ngrok at my local computer so perhaps this poses a problem because at the beginning of Google docs the following is mentioned:
Warning: The Actions Web Simulator should not be used to test an app
with transactions. Please use an Assistant-enabled Android or iOS
device to accurately test your app during development.
I finally solved this problem.
I had to replace the key "data" in the json which I was sending back when Int1 was triggered with the key "payload". In other words, I had to adjust my fulfilment response to the v2 version of Dialogflow.
Therefore, now I do get a second post request at my back-end which is sent because of the trigger of actions.intent.TRANSACTION_REQUIREMENTS_CHECK and of Int2.
Specifically, I get the following:
{
"responseId": "*****************************",
"queryResult": {
"queryText": "actions_intent_TRANSACTION_REQUIREMENTS_CHECK",
"parameters": {},
"allRequiredParamsPresent": true,
"fulfillmentText": "HERE",
"fulfillmentMessages": [
{
"text": {
"text": [
"HERE"
]
}
}
],
"outputContexts": [
{
"name": "*****************************"
},
{
"name": "*****************************"
},
{
"name": "*****************************"
},
{
"name": "*****************************"
},
{
"name": "*****************************"
},
{
"name": "*****************************",
"parameters": {
"TRANSACTION_REQUIREMENTS_CHECK_RESULT": {
"#type": "type.googleapis.com/google.actions.v2.TransactionRequirementsCheckResult",
"resultType": "OK"
}
}
}
],
"intent": {
"name": "*****************************",
"displayName": "Int2"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {},
"languageCode": "en-us"
},
"originalDetectIntentRequest": {
"source": "google",
"version": "2",
"payload": {
"isInSandbox": true,
"surface": {
"capabilities": [
{
"name": "actions.capability.WEB_BROWSER"
},
{
"name": "actions.capability.MEDIA_RESPONSE_AUDIO"
},
{
"name": "actions.capability.SCREEN_OUTPUT"
},
{
"name": "actions.capability.AUDIO_OUTPUT"
}
]
},
"inputs": [
{
"rawInputs": [
{
"inputType": "KEYBOARD"
}
],
"arguments": [
{
"extension": {
"#type": "type.googleapis.com/google.actions.v2.TransactionRequirementsCheckResult",
"resultType": "OK"
},
"name": "TRANSACTION_REQUIREMENTS_CHECK_RESULT"
}
],
"intent": "actions.intent.TRANSACTION_REQUIREMENTS_CHECK"
}
],
"user": {
"lastSeen": "2018-05-16T11:15:14Z",
"locale": "en-US",
"userId": "*****************************"
},
"conversation": {
"conversationId": "1526470000479",
"type": "ACTIVE",
"conversationToken": "[]"
},
"availableSurfaces": [
{
"capabilities": [
{
"name": "actions.capability.SCREEN_OUTPUT"
},
{
"name": "actions.capability.AUDIO_OUTPUT"
}
]
}
]
}
},
"session": "*****************************"
}
I think your response object is incorrect. the intent attribute should be inside the systemIntent object
"data": {
"google": {
"expectUserResponse": true,
"isSsml": false,
"noInputPrompts": [],
"systemIntent": {
"intent": "actions.intent.TRANSACTION_REQUIREMENTS_CHECK",
"data": {
"#type": "type.googleapis.com/google.actions.v2.TransactionRequirementsCheckSpec",
"paymentOptions": {
"actionProvidedOptions": {
"displayName": "VISA-1234",
"paymentType": "PAYMENT_CARD"
}
}
}
}
}
}

How to create a Subscription payment using Paypal client-side rest api?

The Client-side REST integration documentaion describes about creating a express checkout for one or more items.
How can i use the same for creating a subscription or Recurring payment? How should the following be modified?
payment: function(data, actions) {
return actions.payment.create({
transactions: [
{
amount: { total: '1.00', currency: 'USD' }
}
]
});
},
I found a similar Rest api for Node. Not sure how it would be on JS.
First you need to create a billing plan:
billing_plan_attributes = {
"name": PLAN_NAME_HERE,
"description": PLAN_DESCRIPTION,
"merchant_preferences": {
"auto_bill_amount": "yes", # yes if you want auto bill
"cancel_url": "http://www.cancel.com", # redirect uri if user cancels payment
"initial_fail_amount_action": "continue",
"max_fail_attempts": "1",
"return_url": RETURN_URL,
"setup_fee": {
"currency": CURRENCY,
"value": VALUE # how much do you want to charge
}
},
"payment_definitions": [
{
"amount": {
"currency": request.form['currency'],
"value": request.form['amount']
},
"cycles": CYCLES, # how much time this subscription will charge user
"frequency": FREQ, # month, day
"frequency_interval": INTERVAL, # per month or per three month or so on
"name": NAME,
"type": TYPE
}
],
"type": TYPE
}
billing_plan = BillingPlan(billing_plan_attributes)
if billing_plan.create():
print("success")
The attributes used have literal meaning here. Now since you have created a billing plan you need to give users some interface so that they can subscribe with it. Below is a sample code for this:
billing_agreement = BillingAgreement({
"name": "Organization plan name",
"description": "Agreement for " + request.args.get('name', ''),
"start_date": (datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ'),
"plan": {
"id": request.args.get('id', '')
},
"payer": {
"payment_method": "paypal"
},
"shipping_address": {
"line1": "StayBr111idge Suites",
"line2": "Cro12ok Street",
"city": "San Jose",
"state": "CA",
"postal_code": "95112",
"country_code": "US"
}
})
if billing_agreement.create():
for link in billing_agreement.links:
if link.rel == "approval_url":
approval_url = link.href
In the last line you get the approval link which can be given to user.
Next you have to setup an endpoint which will be the callback url if user approves the payment.
billing_agreement_response = BillingAgreement.execute(payment_token)
payment_token is sent by paypal to your callback url.

Record saves, promise rejects with custom REST adapter

I'm writing an ember-data adapter for the DreamFactory services platform and am running into an issue I think is related to my adapter.
When updating an existing record the promise resulting from model.save() is ALWAYS rejected with an error of
Assertion Failed: An adapter cannot assign a new id to a record that already has an id. <App.Event311:1> had id: 1 and you tried to update it with null. This likely happened because your server returned data in response to a find or update that had a different id than the one you sent
Thing is - the request to the REST API and the response back from the REST API have the same ID!
Request (PUT)
{
"record": {
"id": "1",
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
}
Response
{
"record": [
{
"id": 1,
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
]
}
The really weird thing is the record still updates properly both in the store AND in the database!
I have a working JSBin at http://emberjs.jsbin.com/mosek/1/edit that illustrates the problem. My custom adapter is on GitHub at https://github.com/ultimatemonty/ember-data-dreamfactory-adapter. The JSBin as well as my app are using Ember 1.7.0 and ED 1.0.0-beta.9
EDIT
The JSBin is attached to my personal hosted instance of DreamFactory - I haven't done anything with it outside of allowing access from JSBin but please be gentle :)
* EDIT #2 *
The updateRecord code is accessible on GitHub at https://github.com/ultimatemonty/ember-data-dreamfactory-adapter/blob/master/lib/ember-data-dreamfactory-adapter.js#L106 but here is the full method for reference:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
The adapter/serializer you're using is expecting you to return a response without the type in it:
{
"id": 1,
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
Example: http://emberjs.jsbin.com/tigiza/1/edit
You can see it here in the extractSingle, where it tries to wrap the payload in in another object with the type specified
EmberDreamFactoryAdapter.Serializer = DS.RESTSerializer.extend({
extractArray: function(store, primaryType, payload) {
var namespacedPayload = {};
namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.record;
return this._super(store, primaryType, namespacedPayload);
},
extractSingle: function (store, primaryType, payload, recordId) {
var namespacedPayload = {};
namespacedPayload[primaryType.typeKey] = payload;
return this._super(store, primaryType, namespacedPayload, recordId);
},
Your response looks like this:
{
"record": [
{
"id": 1,
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
]
}
Then the serializer kicks in, and it looks like this:
{
event:{
"record": [
{
"id": 1,
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
]
}
}
When really, the serializer should have it looking like this:
{
event:{
"id": 1,
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
}
You can see from the second example, the serializer wraps it in the type, then Ember Data says, hey, give me the id, so it looks at event.id which is undefined, because it lives under event.record[0].id