본문 바로가기
윅스 (Wix) 홈페이지 만들기/Corvid by Wix (윅스 코딩 - 콜비드) 강의

윅스 (Wix) 코딩 고급 (Advanced) - 회원 관리 (Members Area) - 통합 (Integration)

by 라임쥬서(Lime Juicer) 2020. 6. 1.
반응형

윅스 (Wix) 코딩 고급 (Advanced) - 회원 관리 (Members Area) - 통합 (Integration)

윅스 (Wix) 코딩 고급 (Advanced) - 회원 관리 (Members Area) - 통합 (Integration)

강의 내용 요약

다음의 예제는 Wix 윅스 무료 홈페이지 만들기의 자바스크립트 (Javascript) 코딩 기능을 활용할 수 있는 Corvid by Wix (윅스 코딩 - 콜비드) 를 활용하여 만듭니다.

 

웹사이트 내에 회원 가입 이메일 주소를 확인하는 부분을 만듭니다. 

 

예제 보러가기 (View Example)

 

 

예제 에디터 확인하기 (Edit Now)

 

Log In | Wix

Login to Wix.com

users.wix.com

 

 

 

강의 내용 만드는법

만들고자 하는 윅스 사이트에 다음과 같은 구성 요소들이 필요합니다.

  • 라이트박스
  • 이미지
  • 상자
  • 입력란
  • 텍스트
  • 버튼

 

코드 (Code)

Admin

import wixData from 'wix-data';
import { addFile, getAllMembers } from 'backend/data.jsw';

let memberSelectedEmail = "";

$w.onReady(async function () {

	$w('#membersTable').rows = await getAllMembers()
	
	$w('#membersTable').onRowSelect(event => {
		memberSelectedEmail = event.rowData.loginEmail;
		$w("#uploadButton").enable();
	})

	$w('#uploadButton').onChange(async event => {
		try {
			const uploadedFile = await $w("#uploadButton").startUpload();
			const obj = {
				'file': uploadedFile.url,
				'loginEmail': memberSelectedEmail,
			}
			const result = await addFile(obj);
			if (result.insert) {
				$w('#successText').expand();
			} else {
				console.log('Failed to upload');
			}
		} catch (err) {
			console.log("err" + err);
		}

	})
});

 

My Account

import wixUsers from 'wix-users';
import wixData from 'wix-data';

$w.onReady(async function () {
	const userEmail = await wixUsers.currentUser.getEmail();
	const result = await wixData.query('members_tasks').eq('loginEmail', userEmail).find();
	if (result.items && result.items.length > 0) {
		$w('#fileLink').link = result.items[0].file;
	} else {
		$w('#fileLink').disable();
	}
});

 

Approve

import wixLocation from 'wix-location';
import wixUsers from 'wix-users';
import { continueRegister, continueLogIn, validateEmailToken } from 'backend/signIn.jsw';

$w.onReady(function () {
	let emailToken = wixLocation.query.tokenRegister;
	register(emailToken);
})

async function register(emailToken) {
	if (await validateEmailToken(emailToken)) {
		$w('#valid').expand();
		$w('#notValid').collapse();
		continueRegister(emailToken)
			.then(async (result) => {
				if (result.approved) {
					await wixUsers.applySessionToken(result.sessionToken);
					wixLocation.to("/home");
				} else {
					console.log("Not approved!");
				}
			}).catch(error => {
				console.log("error register");
			})
	} else {
		$w('#valid').collapse();
		$w('#notValid').expand();
	}
}

 

sendEmail.js

import wixCrm from 'wix-crm-backend';
const verificationEmailId = 'RzLTaFe';

export function sendEmailVerification(contactId, approvalToken){
	const obj ={
		'url': `https://corvid-examples.wixsite.com/members-area/approve?tokenRegister=${approvalToken}`
	}
	sendEmail(verificationEmailId, contactId, obj);
} 

function sendEmail(emailId, contactId, variables) {
	try {
		wixCrm.emailContact(emailId, contactId, {
			"variables": variables
		})
		.then(() => {
			console.log('email sent successfully');
		})
		.catch((err) => {
			console.log('err in sendEmail is ', err.toString());
		});
	} catch (err) {
		console.log("err", err.toString())
	}	
}

 

signIn.jsw

 import wixUsersBackend from 'wix-users-backend';
 import wixData from 'wix-data';
 import { invalidateEmailToken, approveBy3rdParty } from 'backend/signIn.js';

 export const options = { "suppressAuth": true };

 export async function validateEmailToken(emailToken) {
 	let result = await wixData.query('tokens').eq('_id', emailToken).find(options);
 	return result.items.length > 0;
 }

 export async function doRegistration(contactInfo) {
 	try {
 		if (contactInfo.email && contactInfo.firstName && contactInfo.lastName && contactInfo.phone && contactInfo.password) {
 			await approveBy3rdParty(contactInfo);
 			return { 'approved': true };
 		} else {
 			throw new Error("invalid data")
 		}
 	} catch (err) {
 		return { 'approved': false, 'reason': err.message };
 	}
 }

 export async function continueRegister(emailToken) {
 	const item = await wixData.get("tokens", emailToken, options);

 	const result = await wixUsersBackend.register(item.email, item.password, {
 		"contactInfo": {
 			"firstName": item.firstName,
 			"lastName": item.lastName,
 			"phones": [item.phone],
 		}
 	});
 	const check = await invalidateEmailToken(emailToken);
 	return check ? { "sessionToken": result.sessionToken, "approved": true } : { "sessionToken": result.sessionToken, "approved": false };

 }

 export async function doLogIn(email, password) {
 	try {
 		const result = await wixData.query('Members/PrivateMembersData').eq('loginEmail', email).find(options);
 		if (result.items && result.items.length > 0) {
 			const sessionToken = await wixUsersBackend.login(email, password);
 			return { sessionToken, "approved": true };
 		} else {
 			return { "approved": false, "reason": "not member" };
 		}
 	} catch (err) {
 		return { "approved": false, "reason": 'err' };
 	}
 }

 

register

import wixUsers from 'wix-users';
import wixCrm from 'wix-crm';
import wixWindow from 'wix-window';
import { doRegistration, doLogIn } from 'backend/signIn.jsw';

$w.onReady(function () {
	wixUsers.currentUser.loggedIn ? wixWindow.lightbox.close() : init();
});

function init() {
	onClickLogIn();
	onClickSignIn();
	onClickBack()
}

function onClickBack() {
	$w('#backText').onClick(() => {
		presentLogInForm();
	})
}

function onClickLogIn() {
	$w('#emailLogIn').onChange(() => {
		$w('#loginButton').enable();
	})
	$w('#loginButton').onClick(async () => {
		$w('#loginButton').enable();
		const email = $w('#emailLogIn').value;
		const password = $w('#passwordLogin').value;
		const result = await doLogIn(email, password);
		if (result.approved) {
			await wixUsers.applySessionToken(result.sessionToken); //apply active
			wixWindow.lightbox.close();
		} else {
			if (result.reason === "not member") {
				presentSignInForm(email);
			} else {
				$w('#checkPassword').expand();
				console.log("error logIn");
			}
		}
	})
}

async function register() {
	const contactInfo = {
		'email': $w('#email').value,
		'firstName': $w('#firstName').value,
		'lastName': $w('#lastName').value,
		'phone': $w('#mobilePhone').value,
		'password': $w('#password').value,
	}
	const { approved } = await doRegistration(contactInfo);
	if (approved) {
		$w('#checkEmail').expand();
		$w('#signInBottun').disable();
	} else {
		console.log("Registration error");
	}
}

function presentSignInForm(email) {
	$w("#email").value = email;
	$w('#containerLogIn').collapse();
	$w('#containerRegister').expand();
	$w('#backText').show();
}

function presentLogInForm() {
	$w('#containerLogIn').expand();
	$w('#containerRegister').collapse();
	$w('#backText').hide();
}

function onClickSignIn() {
	$w('#signInBottun').onClick(async () => {
		if (checkValidation()) await register();
		else $w('#textValidation').expand();
	})
}

function checkValidation() { // you can add more validations as you wish
	return $w('#password').value === $w('#secondPassword').value;
}

 

data.jsw

import wixData from 'wix-data';

export async function addFile(obj) {
	try {
		const result = await wixData.query('members_tasks').eq('loginEmail', obj.loginEmail).find({ "suppressAuth": true });
		if (result.items && result.items.length > 0) {
			const itemToUpdate = result.items[0];
			itemToUpdate.file = obj.file;
			await wixData.update('members_tasks', itemToUpdate, { "suppressAuth": true })
		} else {
			await wixData.insert('members_tasks', obj, { "suppressAuth": true })
		}
		return { insert: true };
	} catch (err) {
		return { insert: false };
	}
}

export async function getAllMembers() {
	try {
		let tableArray = [];
		const result = await wixData.query('Members/PrivateMembersData').find({ "suppressAuth": true })
		if (result.items && result.items.length > 0) {
			result.items.forEach(obj => {
				const { loginEmail, firstName, lastName, picture } = obj;
				tableArray.push({ loginEmail, firstName, lastName, picture });
			})
			return tableArray;
		} else {
			throw new Error('No items in members collection')
		}
	} catch (err) {
		console.log(err.message);
	}
}

 

signIn.js

 import wixCrm from 'wix-crm-backend';
 import wixData from 'wix-data';
 import { sendEmailVerification } from 'backend/sendEmail';

 export async function invalidateEmailToken(emailToken) {
 	return await wixData.remove("tokens", emailToken, { "suppressAuth": true });
 }

 export async function approveBy3rdParty(contactInfo) {
 	const contactId = await wixCrm.createContact({ "emails": [`${contactInfo.email}`] });
 	const tokenForEmail = await createToken(contactInfo, contactId);
 	sendEmailVerification(contactId, tokenForEmail);
 }

 export async function createToken(contactInfo, contactId) {
 	let item;
 	const objToInsert = {
 		'email': contactInfo.email,
 		"firstName": contactInfo.firstName,
 		"lastName": contactInfo.lastName,
 		"phone": contactInfo.phone,
 		"password": contactInfo.password,
 		"contactID": contactId,
 	}
 	item = await wixData.insert('tokens', objToInsert, { "suppressAuth": true });
 	return item._id;
 }

 

API

Wix Users API

Wix Users Backend API

Wix Crm Backend API

 

Corvid by Wix (윅스 코딩 - 콜비드) 개발자 모드/도구 활성화하는 방법

윅스 (Wix) 코딩 - 개발자 도구를 활성화하기 (Wix Code: How to Enable Developer Tools)

 

윅스 (Wix) 코딩 - 개발자 도구를 활성화하기 (Wix Code: How to Enable Developer Tools)

윅스 (Wix) 코딩 - 개발자 도구를 활성화하기 (Wix Code: How to Enable Developer Tools) 설명) 개발자 도구를 활성화하기 위해서는 1. 에디터를 엽니다. 에디터 맨 위 상단 메뉴에서 코드를 클릭한 다음 개발�

limejuicer.tistory.com

 

 

 

 

연관된 토픽)

윅스 (Wix) 코딩 강의 중급 (Intermediate) - 샌드그리드 REST 인터페이스로 이메일 보내기 (Example: Send email with the SendGrid REST interface.) - 통합 (Integrations)

 

윅스 (Wix) 코딩 강의 중급 (Intermediate) - 샌드그리드 REST 인터페이스로 이메일 보내기 (Example: Send em

윅스 (Wix) 코딩 강의 중급 (Intermediate) - 샌드그리드 REST 인터페이스로 이메일 보내기 (Example: Send email with the SendGrid REST interface.) - 통합 (Integrations) 강의 내용 요약 다음의 예제는 Wix..

limejuicer.tistory.com

 

윅스 홈페이지 만들기 101

윅스 (Wix) 홈페이지 만들기 101 - E-Book - Index

 

윅스 (Wix) 홈페이지 만들기 101 - E-Book - Index

윅스 (Wix) 홈페이지 만들기 101 - E-Book - Index 윅스 (Wix.com) 윅스 ADI & 템플릿 (Wix ADI & 템플릿) 윅스 웹에디터 (Wix Editor) 윅스 코딩 (Wix Code - Corvid) 윅스 해커톤 (Wix Hackathon)

limejuicer.tistory.com

 

출처 :

콜비드 - 윅스 코딩 (Corvid by Wix)

 

Members Area | Corvid by Wix Examples | Wix.com

Custom member signup with email verification.

www.wix.com

 

반응형

댓글