How to get the email subscription status of a member/contact and display it on the website

Question:
How to get the email subscription status of a member/contact and display it on the website either with a text element or with an input element (like a switch or checkbox)

Product:
Wix Studio Editor

What are you trying to achieve:
So I want to display the current subscription status to email marketing (subscribed, unsubscribed, never subscribed) of the current member/contact on a page on my website. I am unable to access that value through Velo. Here is my code to which I would like to add a new const called marketing and have the email subscription status of the member/contact.

What have you already tried:
I’ve looked at the Velo documentation, and even tried the Wix AI Code generator with no success. I’ve tried to call extended fields and import contacts from wix-crm.v2, did not seem to work either.

I’ve also looked at this thread but it was no help unfortunately:

Here is my functional code so far to get the firstName and loginEmail for my current member.

import { currentMember } from 'wix-members-frontend';

$w.onReady(function () {
  currentMember.getMember()
    .then((member) => {
      const firstName = member.contactDetails.firstName;
      const email = member.loginEmail;

      $w('#nameText').text = firstName;
      $w('#emailText').text = email;
      
    })

});

Additional information:
I’ve looked at the getMember and appendOrCreateContact doc, but is the subscription status of a member/contact even available to use?

Edit

So I’ve figured out how to get the extendedField for email subscription, but I can’t make my code work. Any clue on what I’m doing wrong?

import { currentMember } from 'wix-members-frontend';
import { contacts } from 'wix-crm.v2';

$w.onReady(function () {
    currentMember.getMember()
        .then((member) => {
            const contactId = member.contactId;
            const firstName = member.contactDetails.firstName;
            const email = member.loginEmail;
            const courriels = member.contactDetails.customFields['custom.preferences-notifications'].value;

            $w('#nameText').text = firstName;
            $w('#emailText').text = email;

            if (courriels === 'Oui') {
                $w("#checkbox1").checked = true;
            }

            const options = { suppressAuth: true }; // Add suppressAuth option
            return contacts.getContact(contactId, options) // Pass options
                .then((contact) => {
                    console.log("Contact:", contact);
                    const marketing = contact.info.extendedFields['emailSubscriptions.subscriptionStatus'];
                    
                        $w("#marketing").text = marketing;
                    
                })
                
        })
      
});

You are still walking trough the dark → because you do not use the CONSOLE!
I can’t see any logs on your CODE!

Investigate, what happens on the underground.
What do you get back as response for each little step?
Try to understand each little step → fully.

The CONSOLE → is your best friend.

Hi! Thanks for your answer. So I did use the console to log the member details and I was able to find the key for the field I wanted to use. :slight_smile:

I’m also using console.log(“Contact:”, contact);
but I can’t figure out what is wrong unfortunately, which is why I’m asking for insights or help.

Also what’s weird to me is that I’m using the code from the Velo doc

const options = { suppressAuth: true }; // Add suppressAuth option
            return contacts.getContact(contactId, options)

But in the console, it returns that options cannot be used with getContact. It got me confused since this is from the Velo doc. How could I pass the suppressAuth option then?

I also tried creating a backend file to run this function since I thought it might be the problem, but the console returns a Method not allowed mention.

SUPRESS-AUTH ← —> works on BACKEND-ONLY

Well, but API for Wix-CRM has changed as i can see and the one which was working well in the past, is now depricated…

2024-01-07 22_42_46-getContactById - Velo API Reference - Wix.com

How the new V2.API-version works, i can’t tell you, you will have to test it out.

But taking a quick look onto the API-description…

…also vinnysantini recognized his failure.

You are running it on FRONTEND, where it will not work.

I also tried creating a backend file to run this function since I thought it might be the problem, but the console returns a Method not allowed mention.

Try one more time and show the code.

You are right, I just tried running it on the backend.

Here is my page code on the frontend

import { currentMember } from 'wix-members-frontend';
import { myElevatedGetContactFunction } from 'backend/getContact.jsw'


let contactId

$w.onReady( function() {
 currentMember.getMember()
  .then((member) => {
    contactId = member.contactId;
    console.log(member);
	
  })
  .catch((error) => {
    console.error(error);
  });
  myElevatedGetContactFunction()
	.then( (myContact) => {
  console.log(myContact);
}) });

and here is my backend code for the getContact

import { contacts } from 'wix-crm.v2';
import * as wixAuth from 'wix-auth';


 export async function myElevatedGetContactFunction(contactId) {    
  const elevatedGetContact = wixAuth.elevate(contacts.getContact);

  try {
    const myContact = await elevatedGetContact(contactId);


    console.log('Success! Got contact:', myContact);
    return myContact;
  } catch (error) {
    console.error(error);
    // Handle error
  }  
}

The only thing I can see in the console is this, nothing else…
The currentMember function does work properly, but not the getContact function in the backend.

Return the error in the error-handler on your backend and take a look which error you get.

At momemt you get undefined, because you do not return anything in the error-handler.

While reading some other post → i think he has found you a solution…

Okay so I got the backend function to work :tada:

I’m having a hard time understanding how to pass something from a backend function to a frontend function, and vice-versa.

  1. So the first thing, now I would like to be able to use the value of the extended field (emailSubscription.subcriptionStatus) on my page (I would like a text element to display the value) but I can’t make this work. Is there a way to access a value from a backend function on the front end? I really tried everything to the maximum of my knowledge.

  2. Also, how can I send the contactId of the current member into the backend function to retrieve the contact information for the current member (in the code I added a contactID manually for testing only)

Here is my backend code

import { contacts } from 'wix-crm-backend';


export function myGetContactFunction() {
  const contactId = "faa8b1c6-c7cc-434f-ba0f-bf8d027f3e82";
  const options = {
    suppressAuth: true
  };

  return contacts.getContact(contactId, options)
    .then((contact) => {
      console.log(contact)
      return contact.info.extendedFields
      
    })
    .catch((error) => {
      console.error(error);
    });
}

Here is my frontend code

import { currentMember } from 'wix-members-frontend';
import { myGetContactFunction } from '/backend/getContact.jsw';

$w.onReady(() => {
  currentMember.getMember()
    .then((member) => {
      let contactId = member.contactId;
      console.log(member);
      console.log(contactId);
      
      // Call the functions inside the .then() block
      
    myGetContactFunction()
     .then((marketing) => {
    const email = marketing; // Extracting the 'marketing' value from the response

    console.log(email); // Output the retrieved 'marketing' value to the console

    // Set the retrieved 'marketing' value to the frontend element (assuming '#marketing' is an element ID)
    $w('#marketing').text = email;
  })

  .catch(error => {
    console.error('Error fetching marketing value:', error);
  });

    })})

Here is what I got in the console, the data is shown correctly

Thanks in advance for your support :pray:

Ok, to keep the whole thing simple.

FRONT-END-CODE:

import { authentication } from 'wix-members-frontend';
import { get_CurrentMember, get_ContactData } from 'backend/vnLoginMGM';

$w.onReady(async()=> {
    //----------------------
    const currentMember = await check_LoginState(); 
    console.log('Current-Member: ', currentMember);
    const loginEmail =  currentMember.loginEmail; 
    console.log('Login-Email: ', loginEmail);
    const contactID = currentMember.contactId; 
    console.log('Contact-ID: ', contactID);
    //----------------------
    const contactData = await get_ContactData(contactID); 
    console.log('Contact-Data: ', contactData);
    //----------------------
});

//-------------------- [ LOGIN-CHECK ] -----------------------
async function check_LoginState() {console.log('-----CHECK-----');
    const isLoggedIn = authentication.loggedIn();		
    if(isLoggedIn) {
        let currentMember = await get_CurrentMember({fieldsets:['FULL']});		
        if(currentMember) {return currentMember;} else {return undefined}						
    } else { } 
}

.
.
.

BACKEND-CODE:

import { contacts } from 'wix-crm-backend';
import { currentMember } from 'wix-members-backend';

export function get_ContactData(contactID) {
  return contacts.getContact(contactID,  {suppressAuth:true})
    .then((contact)=> {return contact})
    .catch((error) => {return error;});
}

So the whole code will return you something like…

And do not use the V.2-Version —> seems to be buggy !!!
----> //import { contacts } from ‘wix-crm.v2’; <----- NOT GOOD !!!

So now you have a basic simple setup, which checks right from loading on your current page, if a user is logged-in or not.

If logged-in → get MEMBERS-DATA → GET CONTACT-ID → GET-CONTACT-DATA
If not → Do WHAT YOU WANT !

So, you just were able to provide the CONTACT-ID from FRONTEND to send it to BACKEND → to get CONTACT-INFO back to FRONTEND.

What exactly you want to provide on FRONTEND → it’s on your choice.
In this example i just sent the whole CONTACT-DATA back to frontend.

And i think your question about of how to use the values on FRONTEND is already replied with this example.

Oh!!! And do not forget…
→ my BACKEND-MODULE has a different name → ‘backend/vnLoginMGM’;

EDIT: Forgot that in my version everything is running on backend…so the whole BACKEND-setup one more time…

import { contacts } from 'wix-crm-backend';
import { currentMember } from 'wix-members-backend';

export function get_CurrentMember(options) {
	return currentMember.getMember(options)
    .then((member) => {return member;})
	.catch((error)=> {console.error(error);});
}

export function get_ContactData(contactID) {
  	return contacts.getContact(contactID,  {suppressAuth:true})
    .then((contact)=> {return contact})
    .catch((error) => {return error;});
}

And always keep your code and it’s structure clean, then you will understand your own setup better (including COSOLE-LOGS).

In your previous codes → you have used …CONTACTS from WIX-CRM.V2

I did the same → but i was not able to get —> suppressAuth to work.
It only worked for ADMIN, not for ordinary user.

Switching back to the old (current API version) everything worked perfectly, for ADMIN and for ORDINARY-USER.

And additionaly INFO: Of course there would be even a third option you could use, if those first 2 ones would not work. You could simply use the old and depricated Wix-Users-API (but surely not recommended at all anymore)…

// Get USER-DETAILS....
async function get_UserDetails(userID) {
	return wixUsersBackend.getUser(userID).then((user)=> { 
	return (user);}).catch((error)=> {console.log(error);})
;}