1
votes

I'm looking for some advice as to how I might clean up these two methods and resolve this error? Right now, the getOptOut() is making a GET request to the API to obtain an email_token and returning the view and postOptOut() is making a POST request, with the email_token from the GET, and allowing a "customer" to opt out of the mailing list and then redirecting to customer home.

public function getOptOut(EmailOptingRequest $request)
{

    $customer = Customer::find(Auth::id());
    $email = $customer['attributes']['Email'];
    $token = "9asdfj48asdj48adja4r8";

    $client = new Client();

    $res = $client->request('GET', 
    'https://www.example.com/api/Services/Email/Opting', [
        'headers' => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $token
        ],
        'email' => $email,
        'http_errors' => false // add this to return errors in json
    ]);

    $emailToken = json_decode($res->getBody()->getContents(), true);
    $this->postOptOut($emailToken);

    return view('customer.email-opting', array(
        'customer' => $customer,
        'email' => $email,
        'token' => $token,
        'client' => $client,
        'res' => $res,
        'emailToken' => $emailToken
    ));
}

public function postOptOut($emailToken)
{
    $customer = Customer::find(Auth::id());
    $email_token = $emailToken[0]['token'];

    $client = new Client();

    $res = $client->request('POST', 'https://www.example.com/api/Services/Email/Opting', [
        'email_token' => $email_token,
        'category' => 'promotional',
        'status' => false
    ]);

    return view('customer.show', array(
        'customer' => $customer,
        'email_token' => $email_token,
        'client' => $client,
        'res' => $res ))
        ->with('success', 'You were removed from our mailing list.');
}

And my routes:

Route::get(   'customer/email-opting', 'CustomerController@getOptOut');
Route::post(  'customer/post-opt-out', 'CustomerController@postOptOut');

The hard coded token is temporary. I'm running into issues with the timing of the GET and POST calls and when the views are returning. Thanks!

1

1 Answers

1
votes
public function postOptOut(Request $request)
{
    $customer = Customer::find(Auth::id());
    $email_token = $request->emailToken[0]['token']; // this way you will get token

    $client = new Client();

    $res = $client->request('POST', 'https://www.example.com/api/Services/Email/Opting', [
        'email_token' => $email_token,
        'category' => 'promotional',
        'status' => false
    ]);

    return view('customer.show', array(
        'customer' => $customer,
        'email_token' => $email_token,
        'client' => $client,
        'res' => $res ))
        ->with('success', 'You were removed from our mailing list.');
}

Try this