Docusign send envelope from template not showing tabs (node) - node.js

I'm trying to send an envelope from a template in a webhook listener. I'm using node.js with .mjs files. When I send the envelope via the docusign dashboard it has the tabs - full name, SSN, phone number, address. But when the API sends the envelope, it has those words but no fields next to them. This is a problem because we need that info and there's nowhere for the signer to input it. What could be causing the tabs to not appear when the envelope is sent from the api?
Here's the code to create an envelope and use a template (based off docs):
import docusign from 'docusign-esign';
export function makeEnvelope(args){
// Create the envelope definition
let env = new docusign.EnvelopeDefinition();
env.templateId = args.templateId;
// Create template role elements to connect the signer and cc recipients
// to the template
// We're setting the parameters via the object creation
let signer1 = docusign.TemplateRole.constructFromObject({
email: args.signerEmail,
name: args.signerName,
roleName: 'signer'});
// Create a cc template role.
// We're setting the parameters via setters
let cc1 = new docusign.TemplateRole();
cc1.email = args.ccEmail;
cc1.name = args.ccName;
cc1.roleName = 'cc';
// Add the TemplateRole objects to the envelope object
env.templateRoles = [signer1, cc1];
env.status = 'sent'; // We want the envelope to be sent
return env;
}
export async function useTemplate(args) {
let dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
let envelopesApi = new docusign.EnvelopesApi(dsApiClient);
// Make the envelope request body
let envelope = makeEnvelope(args.envelopeArgs);
// Call Envelopes::create API method
// Exceptions will be caught by the calling function
let results = await envelopesApi.createEnvelope(
args.accountId, {envelopeDefinition: envelope});
return results;
};
Here's the code for the webhook listener where I call useTemplate (please excuse the commented out code and the console logs - I'm still in the midst of figuring it all out):
import express from 'express';
import { useTemplate } from '../request/docusign/docusign-methods.mjs';
import opportunities from '../request/prosperworks/opportunities.mjs';
import people from '../request/prosperworks/people.js';
import customFields from '../request/prosperworks/custom-fields.mjs';
import { findTemplateIdByCohortName } from '../request/docusign/templates.mjs';
import { findSentEnvelopesByStudentEmail, voidEnvelope, findTemplateFromEnvelopeTemplateUri } from '../request/docusign/envelopes.mjs';
import { createJWT, getAccessTokenFromJWT } from '../request/docusign/token.mjs';
import { getAccessToken } from '../request/quickbooks/tokens.mjs';
import { findCustomerByEmail } from '../request/quickbooks/customer.mjs';
import { createCustomer } from '../request/quickbooks/customer.mjs';
import { createInvoice, sendInvoice } from '../request/quickbooks/invoice.mjs';
import { findItemByName } from '../request/quickbooks/item.mjs';
const router = express.Router();
export default router
.post('/copper/opportunity/updated', express.json(), async (req, res, next) => {
const { body } = req;
console.log('webhook received', body);
if(!Object.keys(body.updated_attributes).length) return res.send('irrelevant webhook');
const cohortChanged = !!body.updated_attributes?.custom_fields?.['94620']
console.log('cohort changed?', cohortChanged);
const interviewScheduledToAccepted = !!(body.updated_attributes?.stage?.[0] === 'Interview Scheduled' && body.updated_attributes?.stage?.[1] === 'Accepted')
console.log('interview scheduled to accepted?', interviewScheduledToAccepted);
const fullConditional = cohortChanged || interviewScheduledToAccepted;
console.log('full conditional', fullConditional);
if(fullConditional) {
try {
const jwt = await createJWT();
const docusign_access_token = await getAccessTokenFromJWT(jwt);
const opportunity = await opportunities.get(body.ids[0]);
const cohortId = opportunity?.custom_fields?.find(field => field.custom_field_definition_id === 94620)?.value || null;
const cohortName = customFields.getCohortNameById(cohortId);
console.log('cohort name', cohortName);
const templateId = await findTemplateIdByCohortName(cohortName, docusign_access_token);
const person = await people.findById(opportunity.primary_contact_id);
const email = person.emails[0].email;
console.log('email', email);
const { name } = person;
// if(interviewScheduledToAccepted) {
// const quickbooks_access_token = await getAccessToken();
// let customer = await findCustomerByEmail(email, quickbooks_access_token);
// if(customer === null) {
// customer = await createCustomer(cohortName, person, quickbooks_access_token);
// };
// console.log('customer', customer);
// const product = await findItemByName('Deposit', quickbooks_access_token);
// const invoice = await createInvoice(customer, product, cohortName, quickbooks_access_token);
// const sentInvoice = await sendInvoice(email, invoice.Invoice.Id, quickbooks_access_token)
// console.log('sent invoice', sentInvoice);
// }
const sentEnvelopes = await findSentEnvelopesByStudentEmail(email, docusign_access_token);
await Promise.all(
sentEnvelopes.filter(envelope => {
return envelope.emailSubject.includes('Enrollment Agreement');
})
.map(envelope => {
if(envelope.status === 'sent') return voidEnvelope(envelope.envelopeId, docusign_access_token);
})
);
const sentEnvelopesTemplates = await Promise.all(
sentEnvelopes
.filter(envelope => {
return envelope.status !== 'voided'
})
.map(envelope => {
return findTemplateFromEnvelopeTemplateUri(envelope.templatesUri, docusign_access_token);
})
);
const templateAlreadyUsedCheck = sentEnvelopesTemplates.reduce((outerAcc, templateArr) => {
if(templateArr.reduce((innerAcc, template) => {
if(template.templateId === templateId) innerAcc=true;
return innerAcc;
}, false)) {
outerAcc=true;
}
return outerAcc;
}, false);
if(templateAlreadyUsedCheck) return res.send('envelope already sent');
const envelopeArgs = {
templateId: templateId,
signerEmail: email,
signerName: name
}
console.log(envelopeArgs);
const envelope = await useTemplate({
basePath: process.env.DOCUSIGN_BASE_PATH,
accessToken: docusign_access_token,
accountId: process.env.DOCUSIGN_ACCOUNT_ID,
envelopeArgs
});
return res.send(envelope);
}
catch(err) {
console.log(err.message);
next(err);
}
} else {
return res.send('irrelevant webhook');
}
});

Inbar Gazit figured it out - it turns out I had student as the role name in the template and signer as the role name in my code so that's why it wasn't working.

Related

createClickwrap returns 404 Not Found

When I call createClickwrap method, I got 404 error Not Found. If I run this method through Quickstart generated demo project, I don't get this error. However, if I run it through my project I get the error. If I debug the demo app and my app, the functions parameters are the same.
This is the code in my app:
docusign controller:
const docuSignService = require('./docusign_esign_service');
const demoDocumentsPath = path.resolve(__dirname, '../demo_documents');
const { createClickwrap } = require('./createClickWrap');
async getDocusignRecieptService() {
const authResponse = await docuSignService.authenticate();
if (authResponse) {
const docTermsPdf = 'Term_Of_Service.pdf';
const docFile = path.resolve(demoDocumentsPath, docTermsPdf);
const { basePath, accessToken, apiAccountId } = authResponse;
const { clickwrapId } = await createClickwrap({ docFile, basePath, accessToken, accountId: apiAccountId });
const res = await activateClickwrap({ clickwrapId, basePath, accessToken, accountId: apiAccountId });
console.log({ res });
}
}
docuSignService.js
const SCOPES = ['signature', 'impersonation', 'openid', 'click.manage', 'click.send'];
const fs = require('fs');
const docusign = require('docusign-esign');
class DocusingService {
async authenticate() {
const jwtLifeSec = 10 * 60, // requested lifetime for the JWT is 10 min
dsApi = new docusign.ApiClient();
dsApi.setOAuthBasePath(process.env.dsOauthServer.replace('https://', '')); // it should be domain only.
let rsaKey = fs.readFileSync(process.env.privateKeyLocation);
try {
const results = await dsApi.requestJWTUserToken(
process.env.dsJWTClientId,
process.env.impersonatedUserGuid,
SCOPES,
rsaKey,
jwtLifeSec
);
const accessToken = results.body.access_token;
// get user info
const userInfoResults = await dsApi.getUserInfo(accessToken);
// use the default account
let userInfo = userInfoResults.accounts.find((account) => account.isDefault === 'true');
return {
accessToken: results.body.access_token,
apiAccountId: userInfo.accountId,
basePath: `${userInfo.baseUri}/restapi`
};
} catch (e) {
let body = e.response && e.response.body;
// Determine the source of the error
if (body) {
// The user needs to grant consent
if (body.error && body.error === 'consent_required') {
if (this.getConsent()) {
return this.authenticate();
}
} else {
// Consent has been granted. Show status code for DocuSign API error
this._debug_log(`\nAPI problem: Status code ${e.response.status}, message body:
${JSON.stringify(body, null, 4)}\n\n`);
}
}
}
}
getConsent() {
var urlScopes = SCOPES.join('+');
// Construct consent URL
var redirectUri = 'https://developers.docusign.com/platform/auth/consent';
var consentUrl =
`${process.env.dsOauthServer}/oauth/auth?response_type=code&` +
`scope=${urlScopes}&client_id=${process.env.dsJWTClientId}&` +
`redirect_uri=${redirectUri}`;
throw new Error(`Open the following URL in your browser to grant consent to the application: ${consentUrl}`);
}
getArgs(apiAccountId, accessToken, basePath, signerEmail, signerName, id, agreementData, redirect_uri) {
const envelopeArgs = {
signerEmail: signerEmail,
signerName: signerName,
status: 'sent',
signerClientId: id,
dsReturnUrl: redirect_uri,
agreement: agreementData
};
const args = {
accessToken: accessToken,
basePath: basePath,
accountId: apiAccountId,
envelopeArgs: envelopeArgs
};
return args;
}
}
module.exports = new DocusingService();
createClickWrap.js
const createClickwrap = async ({ docFile, clickwrapName = 'clickwrapName', basePath, accessToken, accountId }) => {
// Step 3. Construct the request Body
// Create display settings model
const displaySettings = docusignClick.DisplaySettings.constructFromObject({
consentButtonText: 'I Agree',
displayName: 'Terms of Service',
downloadable: true,
format: 'modal',
hasAccept: true,
mustRead: true,
requireAccept: true,
documentDisplay: 'document'
});
// Create document model
// Read and encode file. Put encoded value to Document entity.
// The reads could raise an exception if the file is not available!
const documentPdfExample = fs.readFileSync(docFile);
const encodedExampleDocument = Buffer.from(documentPdfExample).toString('base64');
const document = docusignClick.Document.constructFromObject({
documentBase64: encodedExampleDocument,
documentName: 'Terms of Service',
fileExtension: 'pdf',
order: 0
});
// Create clickwrapRequest model
const clickwrapRequest = docusignClick.ClickwrapRequest.constructFromObject({
displaySettings,
documents: [document],
name: clickwrapName,
requireReacceptance: true
});
// Step 4. Call the Click API
const dsApiClient = new docusignClick.ApiClient();
dsApiClient.setBasePath(basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + accessToken);
const accountApi = new docusignClick.AccountsApi(dsApiClient);
// Create a clickwrap
let result = null;
try {
result = await accountApi.createClickwrap(accountId, {
clickwrapRequest
});
} catch (e) {
debugger;
console.log(e);
}
debugger;
console.log(`Clickwrap was created. ClickwrapId ${result.clickwrapId}`);
return result;
};
module.exports = { createClickwrap };
Parameters look like this in the demo app and it works:
and these are the parameters in my app:
The first parameter accountId is the same. Why I am getting this issue in my app if function gets the same parameters?
"Error: Not Found
at Request.callback (/Users/and/test/node_modules/docusign-click/node_modules/superagent/lib/node/index.js:696:15)
at IncomingMessage.<anonymous> (/Users/and/test/node_modules/docusign-click/node_modules/superagent/lib/node/index.js:906:18)
at IncomingMessage.emit (node:events:539:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)"
Thanks to pointing out in the comments, when I changed basePath ${userInfo.baseUri}/restapi to ${userInfo.baseUri}/clickapi, it works now.

Issue with form data send to database using axios in react js?

Hello everyone I have an issue I am doing login and registration form using react and node and mongodb at one point I am stuck at registration please let me know the solution.
Now first start with back end
This my controller file
const users = require('../models/users');
var bcrypt = require('bcryptjs');
const userList = async (req,res) =>{
let data = await users.find();
res.json(data);
}
const userAdd = async (req,res)=>{
let {name,email,password,cpassword} = req.body;
let data = new users({name,email,password,cpassword});
let response = await data.save();
let myToken = await data.getAuthToken();
res.status(200).json({message: 'User added sucessfully', token:myToken});
}
const userLogin = async (req,res)=>{
if(!req.body.email || !req.body.password){
res.status(301).json({message: 'error',message:"Please enter email and password"});
}
let user = await users.findOne({email: req.body.email});
var responseType = {
message: "ok"
}
if(user){
var match = await bcrypt.compare(req.body.password, user.password)
if(match){
let myToken = await user.getAuthToken();
responseType.message = 'login sucessfully';
responseType.token = myToken;
}else
{
responseType.message = 'Invalid Password';
}
}else{
responseType.message = 'Invalid Email ID';
}
console.log(user);
res.status(200).json({message: 'ok', data: responseType});
}
module.exports = {
userList,
userAdd,
userLogin
};
Now come to Front-End part
This is my registration form
const Register = () => {
const [inputField, setInputField] = useState({
name: '',
email: '',
password: '',
cpassword: ''
})
const inputHandler = (e) =>{
setInputField({...inputField, [e.target.name] : e.target.value})
}
const submitButton = async () =>{
if(validForm()){
let url = 'http://localhost:8080/users/add'
let options={
method: "post",
url: url,
headers:{
},
data: inputField
}
try{
let response = await axios(options)
console.log("res",response);
if(response.status == 200){
toast.success("Added Sucessfully");
}
}
catch(e){
toast.error("Something went wrong..!");
}
}else{
toast.error("Form Invalid..!");
}
}
Data is not store in MongoDB database.
Thanks in advance.

How to send data from react editor to server?

I am trying to create an editor to update my backend data but I am stuck at sending data from client to backend
Here is my following front-end code:
import React, { useState } from "react";
import dynamic from "next/dynamic";
import { convertToRaw, EditorState, getDefaultKeyBinding } from "draft-js";
import draftToHtml from "draftjs-to-html";
const Editor = dynamic(
() => import("react-draft-wysiwyg").then((mod) => mod.Editor),
{ ssr: false }
);
const Missions = ({ teamData, editable }) => {
const { title, mission, teamId } = teamData;
const classes = useStyle();
const [missionContent, setMissionContent] = useState(mission);
const [editing, setEditing] = useState(false);
const [editorState, updateEditorState] = useState(EditorState.createEmpty());
const onEditorStateChange = (editData) => {
updateEditorState(editData);
};
const handleSave = async () => {
const selection = editorState.getSelection();
const key = selection.getAnchorKey();
const content = editorState.getCurrentContent();
const block = content.getBlockForKey(key);
const type = block.getType();
if (type !== "unordered-list-item" && type !== "ordered-list-item") {
if (
editorState.getCurrentContent().getPlainText("").trim().length !== 0
) {
const content = editorState?.getCurrentContent();
let html = await draftToHtml(convertToRaw(content));
await updateEditorState(EditorState.createEmpty(""));
setMissionContent(html.trim());
}
}
setEditing(false);
};
return (
<div className="team-mission-editor-container">
<Editor
wrapperClassName={"mission-editor-wapper"}
toolbarClassName={"mission-editor-toolbar"}
editorClassName={"mission-editor-editor"}
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbar={{...}}
/>
)
Here is my back-end router:
router.put(
"/team/:teamId",
restrictedRoute,
checkData,
catchErrors(checkTeamPermissions),
catchErrors(updateTeamData)
);
and here is my update function from backend:
exports.updateTeamData = async (req, res) => {
// Get userId
const userId = req.session.passport.user.id;
// Get teamId
const publicTeamId = req.params.teamId;
// Fetch private id for team
const teamId = await getTeamId(publicTeamId);
// The user making the request
const userPublicId = req.session.passport.user.publicId;
// The creator of the team
const creatorPublicId = req.body.creator;
// Check who is making the request
if (userPublicId !== creatorPublicId) {
res.status(401).json("msg: You cant update a team you did not create");
}
// Updates
const payload = {
title: req.body.title,
mission: req.body.mission,
inputs: req.body.inputs,
outputs: req.body.outputs,
duration_in_months: req.body.duration_in_months,
status: req.body.status,
mergedTo: teamId,
};
// Update team data
await models.Team.update(payload, {
where: {
id: teamId,
creatorId: userId,
},
});
res.status(200).json("msg: Updated team successfully");
};
How can I send data fromo my editor to backend and update it?
Thank you so much for helping me

Azure Bot Framework V4 (NodeJS) - LUIS recognizer returns error?

Using Azure Bot Framework and LUIS.ai to recognize user intent. Performing a get request to the endpoint with the text returns the json object I am expecting, however using the built-in Luis Recognizer I receive the following error: 'Cannot read property 'get' of undefined'. From the documentation here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-nodejs-tutorial-bf-v4 this appears to be the proper configuration so I am not sure what is going awry. Any ideas?
const { ComponentDialog, DialogSet, DialogTurnStatus, WaterfallDialog, ChoicePrompt, TextPrompt } = require('botbuilder-dialogs');
const { TopLevelDialog, TOP_LEVEL_DIALOG } = require('./topLevelDialog');
const { LuisRecognizer, QnAMaker } = require('botbuilder-ai');
const axios = require('axios');
const MAIN_DIALOG = 'MAIN_DIALOG';
const WATERFALL_DIALOG = 'WATERFALL_DIALOG';
const USER_PROFILE_PROPERTY = 'USER_PROFILE_PROPERTY';
const CHOICE_PROMPT = 'CHOICE_PROMPT';
const TEXT_PROMPT = 'TEXT_PROMPT';
class MainDialog extends ComponentDialog {
constructor(userState) {
super(MAIN_DIALOG);
this.userState = userState;
this.userProfileAccessor = userState.createProperty(USER_PROFILE_PROPERTY);
this.addDialog(new TextPrompt(TEXT_PROMPT));
this.addDialog(new TopLevelDialog());
this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
this.initialStep.bind(this),
this.askIfFinishedStep.bind(this),
this.finalStep.bind(this)
]));
this.initialDialogId = WATERFALL_DIALOG;
let luisConfig = {
applicationId: '',
endpointKey: '',
endpoint: '',
};
this.Luis = new LuisRecognizer(
luisConfig,
{
includeAllIntents: true,
log: true,
staging: false
},
true
);
}
async run(turnContext, accessor) {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(turnContext);
const results = await dialogContext.continueDialog();
if (results.status === DialogTurnStatus.empty) {
await dialogContext.beginDialog(this.id);
}
}
async initialStep(stepContext) {
let luisAnalysis = await this.Luis.recognize(stepContext);
let queryString = encodeURIComponent(stepContext.context._activity.text);
/*
Ignore this if statement - only in use with the get request
*/
if(luisResponse.data.topScoringIntent.intent === 'TrainingExpiry' && luisResponse.data.topScoringIntent.score > .75)
{
return await stepContext.beginDialog(TOP_LEVEL_DIALOG);
}
else
{
await stepContext.context.sendActivity("I'm sorry, that is not supported at this time or a high enough intent was not acknowledged.");
await stepContext.context.sendActivity("Top intent: " + luisResponse.data.topScoringIntent.intent + " Score: " + luisResponse.data.topScoringIntent.score);
return await stepContext.next();
}
}
async askIfFinishedStep(stepContext) {
const promptOptions = { prompt: 'Is there anything else I can assist you with?' };
return await stepContext.prompt(TEXT_PROMPT, promptOptions);
}
async finalStep(stepContext) {
if(stepContext.context._activity.text.toLowerCase() === 'no')
{
await stepContext.context.sendActivity("Good bye");
return await stepContext.endDialog();
}
else
{
return await stepContext.beginDialog(MAIN_DIALOG);
}
}
}
module.exports.MainDialog = MainDialog;
module.exports.MAIN_DIALOG = MAIN_DIALOG;
Note: The issue was in my parameter being passed to the recognizer, as #billoverton pointed out. The solution is to pass stepContext.context.
Looking at luisRecognizer.js from the botbuilder-ai module, the error is because the recognizer is expecting a turnContext (with turnState property) and you are sending a stepContext. turnState doesn't exist on stepContext, thus the get property is failing and causing your error. If you send stepContext.context instead, that will fix the issue, i.e. let luisAnalysis = await this.Luis.recognize(stepContext.context);

Stripe Payment of Course using FireStore Cloud Function

So I have made a page where students will get redirected to after choosing in which course they want to register themselves and on that page the students will provide their personal information and right after they'll click on 'continue for registration' button a stripe checkout form will open that will charge them the amount of that particular course and only then those students will get registered in the cloud firestor database collection. So i started learning from these tutorials link. However my cloud functions are written in NodeJS backend so i looked for some sample stripe apis for payment and found these sample apis on this github repo.
I am not sure how to hit these apis or if these are the right apis for me because my other functions are a little bit different then these stripe functions.
I would very much appreciate your help to know how can i implement this functionality. I am pasting the stripe fucntions here too.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const logging = require('#google-cloud/logging')();
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';
// [START chargecustomer]
// Charge the Stripe customer whenever an amount is created in Cloud Firestore
exports.createStripeCharge = functions.firestore.document('stripe_customers/{userId}/charges/{id}').onCreate(async (snap, context) => {
const val = snap.data();
try {
// Look up the Stripe customer id written in createStripeCustomer
const snapshot = await admin.firestore().collection(`stripe_customers`).doc(context.params.userId).get()
const snapval = snapshot.data();
const customer = snapval.customer_id
// Create a charge using the pushId as the idempotency key
// protecting against double charges
const amount = val.amount;
const idempotencyKey = context.params.id;
const charge = {amount, currency, customer};
if (val.source !== null) {
charge.source = val.source;
}
const response = await stripe.charges.create(charge, {idempotency_key: idempotencyKey});
// If the result is successful, write it back to the database
return snap.ref.set(response, { merge: true });
} catch(error) {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with StackDriver
console.log(error);
await snap.ref.set({error: userFacingMessage(error)}, { merge: true });
return reportError(error, {user: context.params.userId});
}
});
// [END chargecustomer]]
// When a user is created, register them with Stripe
exports.createStripeCustomer = functions.auth.user().onCreate(async (user) => {
const customer = await stripe.customers.create({email: user.email});
return admin.firestore().collection('stripe_customers').doc(user.uid).set({customer_id: customer.id});
});
// Add a payment source (card) for a user by writing a stripe payment source token to Cloud Firestore
exports.addPaymentSource = functions.firestore.document('/stripe_customers/{userId}/tokens/{pushId}').onCreate(async (snap, context) => {
const source = snap.data();
const token = source.token;
if (source === null){
return null;
}
try {
const snapshot = await admin.firestore().collection('stripe_customers').doc(context.params.userId).get();
const customer = snapshot.data().customer_id;
const response = await stripe.customers.createSource(customer, {source: token});
return admin.firestore().collection('stripe_customers').doc(context.params.userId).collection("sources").doc(response.fingerprint).set(response, {merge: true});
} catch (error) {
await snap.ref.set({'error':userFacingMessage(error)},{merge:true});
return reportError(error, {user: context.params.userId});
}
});
// When a user deletes their account, clean up after them
exports.cleanupUser = functions.auth.user().onDelete(async (user) => {
const snapshot = await admin.firestore().collection('stripe_customers').doc(user.uid).get();
const customer = snapshot.data();
await stripe.customers.del(customer.customer_id);
return admin.firestore().collection('stripe_customers').doc(user.uid).delete();
});
Angular Test Component(Not Sure about this)
import * as firebase from 'firebase';
import { Component, Input, OnInit, ViewChild } from '#angular/core';
import { AngularFireFunctions } from '#angular/fire/functions';
import { PaymentService } from './payment.service';
import { environment } from '../../../../environments/environment';
#Component({
selector: 'ngx-payment-request',
templateUrl: './payment-request.component.html',
styleUrls: ['./payment-request.component.scss'],
providers: [PaymentService]
})
export class PaymentRequestComponent implements OnInit {
// #Input() amount: 100;
// #Input() label: 'Course';
elements: any;
paymentRequest: any;
prButton: any;
handler: any;
amount: number = 500;
confirmation: any;
loading = false;
#ViewChild('payElement', { static: true }) payElement;
constructor(private pmt: PaymentService, private functions: AngularFireFunctions) { }
ngOnInit() {
// this.loadStripe();
// this.pmt.showId();
this.pmt.showId();
this.handler = StripeCheckout.configure({
// key: environment.stripeKey,
image: 'https://oc1.ocstatic.com/images/logo_small.png',
locale: 'auto',
token: token => {
this.pmt.processPayment(token, this.amount)
},
source: async (source) => {
this.loading = true;
const user = this.pmt.showId();
firebase.functions().useFunctionsEmulator('hxxxxxx.net')
const fun = this.functions.httpsCallable('stripeCreateCharge');
this.confirmation = await fun({ source: source.id, amount: this.amount}).toPromise();
this.loading = false;
}
});
}
handlePayment(e) {
const user = this.pmt.showId();
this.handler.open({
name: 'FireStarter',
description: 'Pay your Dues',
amount : this.amount,
});
e.preventDefault();
}
}

Resources