Angular .io + oAuth 1.0 - PullRequest
       40

Angular .io + oAuth 1.0

0 голосов
/ 03 августа 2020

У меня есть серверная часть WordPress с установленной Gravity Form. А для внешнего интерфейса я использую angular js 2.0. Итак, у меня есть простая форма, которую мне нужно разместить в Gravity в бэкэнде. Вот код, который я написал:

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";
import { BehaviorSubject, Observable } from "rxjs";
import { map } from "rxjs/operators";
import { MessageService } from "./message.service";
import { AuthenticationService } from "./authentication.service";
import * as oauth from "oauth-sign";
import { environment } from "../../environments/environment";
import * as globalVars from "../globals";

@Injectable({
  providedIn: "root",
})

export class ContactService {
  constructor(
    private http: HttpClient,
    private messageService: MessageService,
    private auth: AuthenticationService
  ) {}

  generateNonce = () => {
    let text = "";
    const possible =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (let i = 0; i < 11; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
  };

  generateTimestamp = () => {
    let timestamp = new Date().getTime().toString().slice(0, 10);
    return timestamp;
  };

  submitContact(fullname: string, email_address: string, message: string) {

    const oauth_nonce = this.generateNonce();
    const oauth_timestamp = this.generateTimestamp();

    const parameters = {
      oauth_consumer_key: globalVars.authKey,
      oauth_nonce: oauth_nonce,
      oauth_timestamp: oauth_timestamp,
      oauth_signature_method: globalVars.authSignMethod,
      oauth_version: globalVars.authVersion,
    };

    const encodedSignature = oauth.hmacsign(
      "POST",
      `${environment.apiUrlJson}/gf/v2/entries/`,
      parameters,
      globalVars.authSecret
    );

    /*console.log(encodedSignature);*/

    const authParam =
      'OAuth oauth_consumer_key="' +
      globalVars.authKey +
      '",oauth_token="' +
      globalVars.authSecret +
      '",oauth_timestamp="' +
      oauth_timestamp +
      '",oauth_nonce="' +
      oauth_nonce +
      '",oauth_signature_method="' +
      globalVars.authSignMethod +
      '",oauth_version="' +
      globalVars.authVersion +
      '",oauth_signature="' +
      encodedSignature +
      '"';

    const httpOptions = {
      headers: new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: authParam,
      }),
    };

    let body = new HttpParams();
    body = body.set("form_id", "1");
    body = body.set("created_by", "2");
    body = body.set("status", "active");
    body = body.set("2", fullname);
    body = body.set("3", email_address);
    body = body.set("4", message);

    return this.http
      .post(`${environment.apiUrlJson}/gf/v2/entries/`, body, httpOptions)
      .subscribe((data) => {
        console.log(data);
      });
  }
}

Это ответ, который я получаю:

code: "gform_rest_authentication_error"
data: {status: 401}
message: "Invalid signature - provided signature does not match."

Я новичок в angular, поэтому не знаю, Я написал все это правильно или нет, но помощь будет очень признательна. Прошло 15 дней с тех пор, как я этим занимаюсь, но пока не повезло.

Заранее спасибо!

...