Using DjangoPaypal for Subscriptions not working - python-3.x

Im have used Django-PayPal for one time payment and its work good. Now i want to convert it into Subscription that will automatically resubscribe the package on same day of next month or next year.
This is the code of one time payment which is working fine:
paypal_dict = {
'business': mailpaypal,
'amount': request.POST.get('amount'),
'item_name': 'Order {}'.format(pack.packagename),
'invoice': 'Package'+str(request.POST.get("package_id"))+str(genralsetting_views.systemtimezone(request)),
'custom': str(transactionid)+"_Package_"+str(request.POST.get("package_id"))+'_'+str(genralsetting_views.systemtimezone(request))+'_'+str(endtime)+ '_' + str(viddd)+'_'+str(request.session['id'])+'_'+str(request.session['currency']),
'currency_code': GeneralSetting.objects.get(userid__usertype="superadmin").currency,
"notify_url": request.build_absolute_uri('/') + 'SubscriptionPaypalIPN',
"return": request.build_absolute_uri('/') + 'index',
"cancel_return": request.build_absolute_uri('/') + 'RegistrationPackages',
}
form = PayPalPaymentsForm(initial=paypal_dict)
return render(request, 'Vendor/Packages/RegistrationPackages/paypalpayment.html', {'cur':GeneralSetting.objects.get(userid__usertype="superadmin").currency,"session": request.session, 'form': form,"Data":data})
In the Django-Paypal documentation they showed the way to do subscription,as shown below:
paypal_dict = {
"cmd": "_xclick-subscriptions",
"business": 'receiver_email#example.com',
"a3": "9.99", # monthly price
"p3": 1, # duration of each unit (depends on unit)
"t3": "M", # duration unit ("M for Month")
"src": "1", # make payments recur
"sra": "1", # reattempt payment on payment error
"no_note": "1", # remove extra notes (optional)
"item_name": "my cool subscription",
"notify_url": "http://www.example.com/your-ipn-location/",
"return": "http://www.example.com/your-return-location/",
"cancel_return": "http://www.example.com/your-cancel-location/",
}
# Create the instance.
form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe")
# Output the button.
form.render()
I have write the code same as they said in documentation
paypal_dict = {
"cmd": "_xclick-subscriptions",
"business": mailpaypal,
"a3": "9.99", # monthly price
"p3": 1, # duration of each unit (depends on unit)
"t3": "M", # duration unit ("M for Month")
"src": "1", # make payments recur
"sra": "1", # reattempt payment on payment error
"no_note": "1", # remove extra notes (optional)
"item_name": "my cool subscription",
"notify_url": request.build_absolute_uri('/') + 'SubscriptionPaypalIPN',
"return": request.build_absolute_uri('/') + 'index',
"cancel_return": request.build_absolute_uri('/') + 'RegistrationPackages',
}
form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe")
return render(request, 'Vendor/Packages/RegistrationPackages/paypalpayment.html', {'cur':GeneralSetting.objects.get(userid__usertype="superadmin").currency,"session": request.session, 'form': form,"Data":data})
But when i click on subscribe button ,paypal says "Things don't appear to be working at the moment. Please try again later."
when i click on subscribe button it redirects to this link "https://www.sandbox.paypal.com/cgi-bin/webscr" , while when doing one time payment it redirects to this link "https://www.sandbox.paypal.com/webapps/hermes?token=8F359638A8728725A&useraction=commit&mfid=159438098_a982*3bb48 "
Can anyone tell me the solution to how to do the subscription with paypal-django?

This error happens for a number of different reasons.
1- Are you using a sandbox to test ? if yes, did you use the appropriate email ids in the python dict as well as during login ? You need to use a sandbox business account in python dict and personal sandbox account email to login during making the test payment.
2- Did your sandbox accounts you setup have the correct currency configuration ?

Related

Acumatica REST API - StockItem - How to use UOMConversions from response

In Acumatica REST API - StockItem
I am using the url https://sandbox.kimballinc.com/AcumaticaERP/entity/Default/18.200.001/StockItem?$filter=InventoryID eq '12345' & $expand=UOMConversions
In the response i am getting UOMConversions object as
"UOMConversions": [
{
"rowNumber": 1,
"note": null,
"ConversionFactor": {
"value": 1
},
"FromUOM": {
"value": "EACH"
},
"MultiplyDivide": {
"value": "Multiply"
},
"ToUOM": {
"value": "FOOT"
}
}
]
I want to know how ConversionFactor, FromUOM, MultiplyDivide, ToUOM is used and possible values for these fields.
can you please help me in understand these fields. Thanks
In order to find more information on that , I would recommend that you connect to the Acumatica site in the browser, Navigate to the Stock Item screen and go to the help page for that screen(Tools -> Help).
Once on the help screen, search for the "Unit Conversion Table" you will then find more information about these fields.
For the values that are available, I would recommend once again to go to the browser and the screen itself. Open the selector for the "From Unit" field and the drop-down for the "Multiply/Divid" field. The "Conversion" being just a decimal number and the "To Unit" being a read only field that take for value the base unit of the Stock Item.

DynamoDB Flask API : retrieve the result for particular item and iterate over the item

Need help on how to retrieve the result from dynamodb and iterate over the result
{
"Count": 1,
"Items": [
{ "userID" :100,
"userVisits": [
{
"Accomapnied_relation": "Accomapnied Test relation",
"Accompanied_By": "Accompanied by test",
"Additional_Notes": "Additional notes Test",
"Advance_Directive": "Advance_Directive for visit id 123",
"Chief_Complaints": "Test Chief_Complaints for Visit Id 123",
"Condition_at_discharge": "Test Condition_at_discharge",
"Course_in_the_hospital": [
{
"Dose": "test Dose",
"Drug": "Test Drug",
"Duration": "3months",
"Given_DTTM": "Givend DTTM",
"Schedule": "Schedule Test"
}
],
"mode_of_admission": "Test Attempt",
"userVisitId": "135"
},
{
"Accomapnied_relation": "Accomapnied Test relation",
"Accompanied_By": "Accompanied by test",
"Additional_Notes": "Additional notes Test",
"Advance_Directive": "Advance_Directive for visit id 123",
"Chief_Complaints": "Test Chief_Complaints for Visit Id 123",
"Condition_at_discharge": "Test Condition_at_discharge",
"Course_in_the_hospital": [
{
"Dose": "test Dose",
"Drug": "Test Drug",
"Duration": "3months",
"Given_DTTM": "Givend DTTM",
"Schedule": "Schedule Test"
}
],
"mode_of_admission": "Suicide Attempt",
"userVisitId": "134"
}
]
}
],
}
I want to write an API which get the result from the above dynamodb,
API GET : /api/users//visits/
the below is the code which i have written in flask
#app.route("/api/users/<userID>/visits/<visitID>")
def getUserVisits(userID,visitID):
userID = int(userID)
visitId = str(visitId)
result = table.query(
ProjectionExpression="#userID, userVisits",
ExpressionAttributeNames={ "#userID": "userID" }, # Expression Attribute Names for Projection Expression only.
KeyConditionExpression=Key('userID').eq(userID)
)
if not result['Items']:
raise InvalidUsage('No User Visits Details found with User :{} and visit Id :{} '.format(userID, visitID), status_code=410)
for item in result['Items']:
if not item:
raise InvalidUsage('No USer Visits Details found with User :{} and visit Id :{} '.format(userID, visitID), status_code=410)
for visits in item['userVisits']:
if(visitId == visits['visitId']):
return jsonify(visits), 200
if not visits:
raise InvalidUsage('No User Visits Details found with User :{} and visit Id :{} '.format(userID, visitID), status_code=410)
raise InvalidUsage('No User Visits Details found with User :{} and visit Id :{} '.format(userID, visitID), status_code=410)
The above is working fine but its taking lot time , is there any functionality in dynamoDB get the userVisits for that userID and visitID, can we improve the above code , I am new tho the Flask and DynamoDb , can you please help me on this to improve the code any best parctices.
Thanks a lot!!
Firstly, you have mentioned that it takes lot of time without mentioning how long (in msecs) it took. There are only two operations in the visits API.
1) Dynamodb query to get the item. The Dynamodb Query API should not take more time as you are querying the table by partition key
2) Loop through the array to find the userVisits by userVisitId. Typically, this iteration shouldn't make more time for the medium size array. Also, Dynamodb item size can be only 400 KB maximum. So, I presume that the iteration should not take more time.
Still, if you think that the above solution takes more time. I would propose an alternate solution for the above data model.
Please restructure the data model using the below table definition. So that you can query the table directly using the partition and range key in KeyConditionExpression.
Partition Key : userID
Range Key : userVisitId
The alternate solution will eliminate the iteration step to match the userVisitId.

issue in stripe connected account to bank transfer

i have an issue in transfer.
my stripe connected account available bal is $200.00 and i have an transfer my $200.00 and pandding balance is $150.00 balance to my bank account.
to showing error insuficient funds in your stripe connected account
see my code:
\Stripe\Stripe::setApiKey($_REQUEST['secret_id']);
$transfer = \Stripe\Transfer::create(array(
"amount" => 20000,
"currency" => "usd",
"destination" => "default_for_currency",
"description" => $_REQUEST['description'],
"source_type" => "bank_account"
));
see output :
{
msg = "You have insufficient funds in your Stripe account for this transfer. Your ACH balance is too low. You can use the the /v1/balance endpoint to view your Stripe balance (for more details, see stripe.com/docs/api#balance).";
status = 0;
}
i need solution please.
Your account actually has more than one balance -- funds are split by payment source type.
If you send a balance retrieval request, you will get a result similar to this:
{
"available": [
{
"amount": 20000,
"currency": "usd",
"source_types": {
"card": 12000,
"bank_account": 8000
}
}
],
"livemode": false,
"object": "balance",
"pending": [
{
"amount": 0,
"currency": "usd",
"source_types": {
"card": 0,
"bank_account": 0
}
}
]
}
When you create a transfer, you should specify the source type via the source_type attribute. E.g. in PHP, you'd do something like this:
\Stripe\Transfer::create(array(
"amount" => 8000,
"currency" => "usd",
"destination" => "default_for_currency",
"source_type" => "bank_account"
));
On an unrelated note, it seems you're setting the API key via a client-side parameter:
\Stripe\Stripe::setApiKey($_REQUEST['secret_id']);
You should never share the secret API key with your client-side code. It would be very easy for an attacker to retrieve it and use it to issue API requests on your behalf. They'd be able to look at your transactions, delete saved customers, etc.
When any charge is succeeded in stripe, it takes some time to actually available it in stripe account.
If You want to create the transfer based on any amount collected by any charge, then you can directly use the charge id.
So your code should be like:
\Stripe\Stripe::setApiKey("your_secret_key");
$transfer = \Stripe\Transfer::create(array(
"amount" => 1000,
"currency" => "usd",
"source_transaction" => "{CHARGE_ID}",
"destination" => "{CONNECTED_STRIPE_ACCOUNT_ID}",
));
By using source_transaction, the transfer request succeeds regardless of your available balance and the transfer itself only occurs once the charge’s funds become available.
It is documented here

Stripe testing subscription Lumen 5.1

Im running Stripe in test mode.
I've created a Yearly billing plan for 100GBP amount, with a 7 days trial ( directly onto Stripe dashboard. )
However, to test the webhooks i've hardcoded the trial_end:
$trialEnd = new DateTime();
$trialEnd->setTimestamp(time()+120);
$user = Users::find($this->user()['user_id']);
$user->subscription($stripe_plan['stripe_plan'])->trialFor($trialEnd)->create($data['stripeToken'], [
'email' => $this->user()['email']
]);
$user->save();
Basically all goes well, but into stripe dashboard the first invoice for 0 GBP is shown, and after one minute i get the Subscription will end in a minute event. After all, the subscription become Active ( from Trialing ) state.
All the webhooks and even the first subscription add reponse i get the trial ends period instead subscription ends.
How can i get the subscription_ends_at timestamp ?
All webhook requests are having the following timestamps:
{
"id": "evt_18baRrIzJLF7fe6PMDPYD0NM",
"object": "event",
"api_version": "2016-07-06",
"created": 1469558315,
"data": {
"object": {
"id": "sub_8tNBbqy0AmSk8p",
"object": "subscription",
"application_fee_percent": null,
"cancel_at_period_end": false,
"canceled_at": null,
"created": 1469558268,
"current_period_end": 1469558384,
"current_period_start": 1469558268,
"customer": "cus_8tNB1tWYw3Jw7L",
"discount": null,
"ended_at": null,
"livemode": false,
"metadata": {
},
"plan": {
"id": "yearly_200",
"object": "plan",
"amount": 20000,
"created": 1469545724,
"currency": "gbp",
"interval": "year",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"name": "Full Club Membership - Pay Anually",
"statement_descriptor": "FULL MEMBERSHIP",
"trial_period_days": 7
},
"quantity": 1,
"start": 1469558268,
"status": "trialing",
"tax_percent": null,
"trial_end": 1469558384,
"trial_start": 1469558268
}
},
"livemode": false,
"pending_webhooks": 1,
"request": null,
"type": "customer.subscription.trial_will_end"
}
So if you look at trial_start and trial_end is same with current_period_start and current_period_end.
I've though initially that if this is the current period.. fine, but after trial expires the current period shouldn't be trials one.
There is any method to take the subscription_ends_at field from Stripe api ? And also, after the trial period ends, shouldn't send a invoice with the real amount ?
Also, i created a subscription plan with no trial period. That plan after a client subscribed, i get the correct timestamps.
Thanks in advance!
It looks like you figured it out. Basically, the delay comes from the fact that when the timestamp passes for your trial expiration, your request to create a new Invoice on that billing cycle gets added to a queue. Typically the queue will create the new invoice ~immediately, but it can sometimes go several minutes before triggering.
The first Invoice will always have timestamps for the current_period_* that map to the trial_period_* ones. Whereas, the second Invoice (that shows up with the invoice.created-event) will have the accurate timestamps for the billing period.
Oh, now i understand .. i will explain maybe will help someone :D.
Basically if a subscription got a trial period when you subscribe you will get a invoice for 0. Then, even if you set the trial to expire in 2 minutes with the request , the first payment will occur in about 10 minutes :D ( with that payment (if you set a webhook url) you will get a "type": "customer.subscription.updated" event who will contain all desired informations. At that time you can update your subscription_ends_at .
I didn't wait 10 minutes to see if the new invoice will be triggered.. and created -> removed -> recreated -> removed and so on for 4 hours with different tests.

Figure out last completed payment via Accounts.payments: list in AdSense Management API v1.4

I am successfully using Google's AdSense API to retrieve payments. The AdSense account I am testing the app with does not have any completed payments.
I am using Accounts.payments:list to retrieve the payments and currently I am only getting one row with Id = "unpaid". This entry specifies the amount that is available for payment.
My question here is what are the other possible entries in the result? Specifically how can I find last completed payment?
Thank you for your help.
items[] description: "The list of Payments for the account. One or both of a) the account's most recent payment; and b) the account's upcoming payment".
As far I can see id can be "unpaid", or date of the last payment (probably the "payment issued" date):
{
"kind": "adsense#payments",
"items": [
{
"kind": "adsense#payment",
"id": "unpaid",
"paymentAmount": "***.**",
"paymentAmountCurrencyCode": "***"
},
{
"kind": "adsense#payment",
"id": "****-**-**",
"paymentDate": "****-**-**",
"paymentAmount": "***.**",
"paymentAmountCurrencyCode": "***"
}
]
}
how can I find last completed payment?
In my understanding, that is exactly what Accounts.payments:list is (or will be) returning:
your account current balance
last payment (if there was any)

Resources