Can anyone share working hangout chat api example with php? [closed] - hangouts-chat

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I am looking for Google chat api code with service account. I tried following code but getting some errors, not sure what I am missing.
include_once BP."/lib/google-api/vendor/autoload.php";
$client = new Google\Client();
$client->setAuthConfig(BP."/scripts/hangout/mytee-products-e6e5368c4246.json");
$client->setApplicationName("Client_Library_Examples");
$client->setScopes(['https://www.googleapis.com/auth/chat.bot']);
try{
$service = new Google_Service_HangoutsChat( $client );
print_r($service->spaces->listSpaces());
}
catch(Exception $e){
print $e->getMessage();
}
{ "error": { "code": 404, "message": "Requested entity was not found.", "errors": [ { "message": "Requested entity was not found.", "domain": "global", "reason": "notFound" } ], "status": "NOT_FOUND" } }

Consideration
Note: A recent commit to the google-api-php-client Github repository updated class names with namespace notation.
You are using namespace notation (Google\Client()) while not activating it beforehand. You should adopt a different notation if you don't intend to use namespaces.
Solution
Please refer to this syntax to use Google_Client PHP Class methods in your PHP script:
include_once __DIR__ . '/path/to/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig(__DIR__."/path/to/credentials.json");
$client->setApplicationName("Your_Application_Name");
$client->setScopes(['https://www.googleapis.com/auth/chat.bot']);
try {
$service = new Google_Service_HangoutsChat( $client );
print_r($service->spaces->listSpaces());
} catch(Exception $e) {
print $e->getMessage();
}
References
PHP Namespaces
Google PHP API Service Account

Related

CORS issue asp.net core web api. No 'Access-Control-Allow-Origin' header is present [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am using asp net core 2.1 and I have an account controller with following methods:
[HttpPost("login")]
public async Task<object> Login([FromBody] IdentityUserForLoginDto userForLogin)
{...}
[HttpPost("register")]
public async Task<object> Register([FromBody] IdentityClientForRegistrationDto userForRegistration)
{...}
When I fetch data on login method, everything works fine and user normally logs in, but when I try to register new user I get CORS issue:
Access to fetch at 'http://localhost:53531/api/account/register' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and:
POST http://localhost:53531/api/account/register net::ERR_FAILED
In my backend I tried every possible combination of enabling CORS and for now I have this:
ConfigureServices:
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("http://localhost:3000", "http://localhost:3001")
.AllowAnyHeader().AllowCredentials()
.AllowAnyMethod();
}));
Configure
app.UseCors("ApiCorsPolicy");
Client-side data fetching:
fetch(`http://localhost:53531/api/account/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify(values)
})
.then(handleResponse)
.then(user => {
localStorage.setItem('currentUser', JSON.stringify(user));
currentUserSubject.next(user);
return user;
});
Both of them are placed before Add/UseMvc.
I've tried with AllowAnyOrigin, [EnableCors] etc..but always the same.
I want to point out that I've also tried with disabling cors from client but in that case I get text/plain media type and I explicitly want application/json.
Also, when I make the same request in postman everything works great..
Does anyone have any idea how to fix that issue?
I solved this. Problem was in data that was sent to server..it wasn't in format that server expected it to be

Integrate swashbuckle swagger with odata in ASP.Net Core [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have tried to implement both ( swagger and odata ) in asp.net core, but it's not working.
I'm unable to integrate the route given for odata.
I have the following Configuration and I receive a generic error.
This is the error
We ran into the same issue when adding OData to our .Net Core project. The workarounds shown in the code snippet on this post fixed our API error(s) when Swagger UI loads.
As far as I can tell, OData isn't supported in Swashbuckle for AspNetCore. So after adding the workaround code in the link above, our Swagger UI works, but none of the OData endpoints show.
Code snippet from the link:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOData();
// Workaround: https://github.com/OData/WebApi/issues/1177
services.AddMvcCore(options =>
{
foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var builder = new ODataConventionModelBuilder(app.ApplicationServices);
builder.EntitySet<Product>("Products");
app.UseMvc(routebuilder =>
{
routebuilder.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
// Workaround: https://github.com/OData/WebApi/issues/1175
routes.EnableDependencyInjection();
});
}
}
I was able to do this using a DocumentFilter. Create a class like the example below, then add it to your Swagger configuration as:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "Your title API v1.0", Version = "v1.0" });
options.DocumentFilter<CustomDocumentFilter>();
});
Github Example
You can integrate Swagger a couple of different ways. For barebones support, you can use the ODataSwaggerConverter provided by OData. This will effectively convert the EDM to a Swagger document. To wire this up to a Swagger generator library like Swashbuckle, you just need create and register a custom generator. The UI and client side of things should remain unchanged. If the generated Swagger document isn't sufficient, the base implementation of the ODataSwaggerConverter is still a reasonable start.
If you're using API Versioning for OData with ASP.NET Core, you need only add the corresponding API Explorer package. Swashuckle will light up with little-to-no additional work on your part. The ASP.NET Core with OData Swagger sample application has an end-to-end working example.

How to component test web api using in memory hosting framework while web api still runs on iis? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to create component testing project to test a Web API service and I would like to use in memory hosting solution such as OWIN, I would like to know is it possible and also is it possible that the Web API project would run with IIS and only the testing project will run in memory?
Is there any recommended in memory hosting framework?
You can use Owin to self host your api so you can perform test against a running version of your api. However, you should be able to test your controllers logic using unit tests without requiring your api's to be actually hosted.
Still, there might be valid reason to host them in a unit test so here we go:
Self hosting in a console application is explained here. If it can run in a console application it can run in a unit test project as well. An example could be (pseudo code):
using Microsoft.Owin.Hosting
using Owin
using System.Web.Http
using Microsoft.Owin.Cors
using System.Web.Http.Dispatcher
using System.Threading.Tasks
string service = "http://localhost:54321";
[TestMethod]
public async Task MyTest()
{
using (var webApp = WebApp.Start(service, BuildConfiguration))
{
var requestUrl = string.Format($"{service}/api/Foo/Bar");
var client = new HttpClient();
var response = await client.GetAsync(requestUrl);
Assert.IsTrue(response.IsSuccessStatusCode);
}
}
public void BuildConfiguration(IAppBuilder appBuilder)
{
var HttpConfiguration = new System.Web.Http.HttpConfiguration();
HttpConfiguration.Services.Replace(typeof(IAssembliesResolver), new AssembliesResolver());
HttpConfiguration.MapHttpAttributeRoutes();
HttpConfiguration.Routes.MapHttpRoute("DefaultApi",
$"api/{{controller}}/{{action}}/{{id}}", new { id = RouteParameter.Optional });
appBuilder.UseCors(CorsOptions.AllowAll);
appBuilder.UseWebApi(HttpConfiguration);
HttpConfiguration.EnsureInitialized();
}
[RoutePrefix("api/Foo")]
public class FooController : ApiController
{
[HttpGet]
[Route("Bar")]
public string GetBar()
{
return "Hello World";
}
}
public class AssembliesResolver : DefaultAssembliesResolver
{
private List<Assembly> assemblies;
public override ICollection<Assembly> GetAssemblies()
{
assemblies = new List<Assembly> { GetType().Assembly };
return assemblies;
}
}
Now, your controllers to test probably live in another assembly than in the test assembly. You might have to use an assemblies resolver for the unit test project to be able to discover your api's. You can write your own AssembliesResolver for that as shown in my answer.
Be aware though. Depending on your setup you have to make sure your test environment matches the real world scenario. There might be subtle differences between IIS and self hosted web api's when it comes to the different parameters required to set up the in memory hosting environment

smack 4.1 Openfire Sample example [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I have been using smack 3.4 for my web portal. Also used asmack 3.4 for my android app
(aSmack development stopped some years back but there where some unofficial jars that i used. Faced issues with file upload and group chat with this it so want to upgrade to official smack as it has andoid native support now).
But now there is a update on smack they have moved to 4.1(android native integrated):
https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide.
So i am looking for some code example/sample project/code snippet with SMACK 4.1 alpha integrated with android/web.
Please provide some helpful links.
Also advice on doing/or not doing this upgrade. As smack 4.1 is still not released.
Thanks.
Example of connection using SSL (smack-4.1.0-beta2-SNAPSHOT-2015-02-01) :
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
//For OLD STYLE SSL
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setUsernameAndPassword(USERNAME + "#" + DOMAIN, "PASSWORD");
config.setServiceName(DOMAIN);
config.setHost(DOMAIN);
config.setPort(PORT);
config.setDebuggerEnabled(true);
//OLD STYLE SSL
//config.setSocketFactory(SSLSocketFactory.getDefault());
try {
SSLContext sc = SSLContext.getInstance("TLS");
MemorizingTrustManager mtm = new MemorizingTrustManager(ctx);
sc.init(null, MemorizingTrustManager.getInstanceList(ctx), new SecureRandom());
config.setCustomSSLContext(sc);
config.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new IllegalStateException(e);
}
mConnection = new XMPPTCPConnection(config.build());
mConnection.setPacketReplyTimeout(10000);
try {
mConnection.connect();
mConnection.login();
} catch (SmackException | IOException | XMPPException e) {
e.printStackTrace();
}
https://github.com/ge0rg/MemorizingTrustManager/tree/master/src/de/duenndns/ssl
Chat creation example:
final ChatManager chatManager = ChatManager.getInstanceFor(mConnection);
chatManager.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean b) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
mServerResponse.gotMessage(message.getBody());
Log.d(TAG, message.toString());
}
});
}
});
Chat chat2 = chatManager.createChat(USERNAME + "#" + DOMAIN);
try {
chat2.sendMessage("text");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}

Google OAuth2 Service Accounts API Authorization

I'm trying to authenticate my server app through Google's service account authentication but, for some reason, it is just not pushing through.
In the API console, I already created the project, enabled the service I need (Admin SDK), and created a Service Account and Web Application API Access.
When I do use the web application access credentials I am able to authenticate and retrieve user records. But using service account authentication would keep giving me a login required message.
"error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" }
I forgot to add, I am testing this with the PHP client library.
public function init() {
$client = new Google_Client();
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
$key = file_get_contents(App::SERVICE_KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
App::SERVICE_ACCOUNT_NAME,
App::SERVICE_API_SCOPES,
$key)
);
$client->setClientId(App::SERVICE_CLIENT_ID);
debug($client, 'CLIENT');
if ($client->getAccessToken()) {
$this->access_token = $_SESSION['access_token'] = $client->getAccessToken();
debug($_SESSION['access_token'], 'TOKEN');
} else {
debug('NO TOKEN');
}
$this->client = $client;
}
As you can see, the code is basically about the same as the Google example. Am I missing an extra step?
One last thing, when I authenticate using the web app then access my service account script, the service account script can pick up the web app script's session and push through with the user record retrievals. Does that mean the Admin SDK API explicitly needs user interaction through web app authentication?
Instead of service account, I instead opted to use installed applications API Access.
This ruby gem actually helped my figure this out - https://github.com/evendis/gmail_cli
I was playing with it on the console and just followed the authorization steps in the readme, and found that installed applications is more simple when doing server admin apps.
Being a newb, I think I missed the important part the refresh token plays in the entire process. Going via the installed application approach helped me figure that out.
My config file now contains the client id, client secret, api scope, redirect uri, authorization code, and the refresh token; my initialization code now looks like:
public function init() {
$client = new Google_Client();
$client->setClientId(App::CLIENT_ID);
$client->setClientSecret(App::CLIENT_SECRET);
$client->setScopes(App::API_SCOPES);
$client->setRedirectUri(App::REDIRECT_URI);
if (!$client->getAccessToken()) {
$client->refreshToken(App::REFRESH_TOKEN);
}
$this->access_token = $client->getAccessToken();
$this->client = $client;
}