Laravel with moneris - laravel-5.1

Can anyone advice me how can I add Moneris payment metnod with laravel 5.1 ?
I have a merchant account. But I am not sure if laravel supports monaris or not.
Thanks in advance.

Laravel by itself doesn't support Moneris (nor any payment processor). However, you can integrate Moneris (and the Moneris API) into your Laravel application by following the directives listed on their developer portal.
Compared to modern payment solutions, such as Stripe or Braintree, Moneris' API can be pretty tedious to use. If you are only using basic purchase, verify, preauth, capture, and refund operations, I suggest you to check out Keith Silgard's library.
However, if you need to implement other operations, such as adding a card to the Vault, you will have to follow Moneris' examples and adapt them to fit into your Laravel Application. For (a very rough) example:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use mpgClasses;
class PaymentController extends Controller
{
protected function addCardToMonerisVault(Request $request) {
/**************************** Request Variables *******************************/
$store_id=getenv('MONERIS_STORE_ID');
$api_token=getenv('MONERIS_API_KEY');
/************************* Transactional Variables ****************************/
$type='res_add_cc';
$cust_id= Auth::user()->id;
$pan=preg_replace('/\D/', '', $request->input('number'));
$expiry_date=$request->input('expiry_year') . $request->input('expiry_month');
$crypt_type='1';
$avs_street_number = '';
$avs_street_name = '';
$avs_zipcode = '';
/*********************** Transactional Associative Array **********************/
$txnArray=array('type'=>$type,
'cust_id'=>$cust_id,
'pan'=>$pan,
'expdate'=>$expiry_date,
'crypt_type'=>$crypt_type
);
/**************************** Transaction Object *****************************/
$mpgTxn = new \mpgTransaction($txnArray);
/****************************** Request Object *******************************/
$mpgRequest = new \mpgRequest($mpgTxn);
/***************************** HTTPS Post Object *****************************/
$mpgHttpPost =new \mpgHttpsPost($store_id,$api_token,$mpgRequest);
/******************************* Response ************************************/
$response = $mpgHttpPost->response;
return $response;
}
}

Related

How to handle API callbacks in ASP.NET MVC (Helloworks API in my case)

As per their documentation from link https://docs.helloworks.com/v3/reference#callbacks
"With the HelloWorks API you can use callbacks to be notified about certain events. Currently we support a callback to be registered when a step is started, the cancellation of a workflow, and the completion of a workflow.
The callback URL will be called according to the following:
curl -X POST https://your.domain.com/some/path
-H "X-HelloWorks-Signature: {signature}"
-H "Content-Type: application/json"
-d "{payload}
I am not able to figure out how can I handle the callback in ASP.NET MVC 4.0. The callback returns data on JSON format. Once I receive the data, I can format it as per my need and can save to database. But how can I get the data in my controller? Guidance from experts on APIs are highly appreciated. Thanks in advance.
I am not able to figure out how can I handle the callback in ASP.NET MVC 4.0.
You need to have an api controller that accepts POST requests. That api endpoint is then called by the HelloWorks api. The fancy word to describe this mechanism is a Webhook. A nice introduction can be found here.
The very basic would be a controller like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MyWebAPI.Controllers
{
public class WebHookController : ApiController
{
// POST: api/webhook
public void Post([FromBody]string value)
{
}
}
}
You will need to register the url https://yourwebsite.domain/api/webhook at the HelloWorks api so it knows where to send the data to.
You probably want to secure this endpoint so others cannot abuse this api. See the docs for some guidance.
For example, in your case you should check that a header named "X-HelloWorks-Signature" is send in the request to the endpoint. The value of that header is a hash that should match the value of a hash of the content you received. To calculate the hash code to match create a hash using the SHA-256 algorithm and base16-encode the result.
There is also documentation from Microsoft on how to create web apis
Peter your guidance worked. I appreciate that. It was straight forward, only the technical jargon are making it intimidating :). Below are the code that worked. I am still to secure it using signature.
[HttpPost]
public ActionResult Callback()
{
string rawBody = GetDocumentContents(Request);
dynamic eventObj = JsonConvert.DeserializeObject(rawBody);
Test newTest = new Test();
newTest.Response = "Bikram-1" + (string)eventObj.type;
var test = db.Tests.Add(newTest);
db.SaveChanges();
return Content("Success!");
}
private string GetDocumentContents(HttpRequestBase Request)
{
string documentContents;
using (Stream receiveStream = Request.InputStream)
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
documentContents = readStream.ReadToEnd();
}
}
return documentContents;
}

This endpoint requires at least one of the following scopes: profile, surge_accept, request, request.delegate

I am developing an application using Uber API, I used Retrofit library for retrieving data from API.
I have authorized my application using below endpoint:
https://login.uber.com/oauth/v2/authorize?client_id=<CLIENT_ID>&response_type=code
But when I tried to get estimates of products using below endpoint:
https://api.uber.com/v1.2/requests/estimate?start_latitude=37.7752278&start_longitude=-122.4197513&end_latitude=37.7773228&end_longitude=-122.4272052
Then I got an issue:
This endpoint requires at least one of the following scopes: profile, surge_accept, request.delegate.tos_accept, request, request.delegate","code":"unauthorized
Before implementing this endpoint I have completely done authorization & token procedure by following Uber official doc.
Also I'm showing my source code below please let me know where I'm going wrong:
----> Intializing UBER SDK <----
public void initializeUber() {
if (!UberSdk.isInitialized()) {
configuration = new SessionConfiguration.Builder().setClientId("LWOUTh3AUBkVtaI-cK58-t_pspsvRFfk").setServerToken("J5MNweewRs8vj4-dC0r9OMI4-qjibix0xv6gncGs").setRedirectUri("REDIRECT_URL").setScopes(Arrays.asList(Scope.REQUEST)).setEnvironment(SessionConfiguration.Environment.SANDBOX).build();
UberSdk.initialize(configuration);
accessTokenManager = new AccessTokenManager(context);
System.out.println("Configuration- ---->
"+configuration.toString());
loginManager = new LoginManager(accessTokenManager, new UberLoginCallback(context), configuration, LOGIN_CODE);
} else {
Log.i(TAG, "Uber SDK already initialized");
}
}
public LoginManager getLoginManager() {
PreferenceManager(context).setUberAuthToken(loginManager.getAccessTokenManager().getAccessToken().toString());
System.out.println("Is authenticated-+loginManager.getAccessTokenManager().getAccessToken());
return loginManager;
}
-----> Created API Interface <----
#POST("v1.2/requests/estimate?")
Call<RequestEstimateFare> getRequestEstimateFare(#Query("start_latitude") String start_latitude, #Query("start_longitude") String start_longitude, #Query("end_latitude") String end_latitude, #Query("end_longitude") String end_longitude);
----> Retrofit Library calling <-----
apiInterface = retrofitConfig.createService(ApiInterface.class);
retrofitConfig.changeApiBaseUrl("https://api.uber.com/");
apiInterface.getRequestEstimateFare ("37.7752315", "-122.418075", "37.7752415", "-122.518075").enqueue(new Callback<RequestEstimateFare>() {
#Override
public void onResponse(Call<RequestEstimateFare> call, Response<RequestEstimateFare> response) {
}
#Override
public void onFailure(Call<RequestEstimateFare> call, Throwable t) {
}
});
I'm still getting the same issue.
The problem is you have not requested the 'request' scope during the oauth authorization process.
like:
https://login.uber.com/oauth/v2/authorize?client_id=<CLIENT_ID>&response_type=code&scope=request
or if you want all scope then you need to pass all in link like:
https://login.uber.com/oauth/v2/authorize?client_id=<CLIENT_ID>&response_type=code&scope=request request_receipt history profile
Firstly, are you making this request as one of your 5 approved developer accounts? or have you requested FULL ACCESS?
https://developer.uber.com/docs/riders/references/api/v1.2/requests-estimate-post
Privileged Scope This endpoint requires a privileged scope to be used
in production by all Uber riders. You can use this endpoint
immediately when authenticated as yourself or any of your 5 registered
developers. When you are ready to distribute your application broadly
for use by all Uber riders, you may request FULL ACCESS. For more
information read about scopes.
Secondary to that I'm not sure how your request is working using query params instead of a JSON request body? I can only get your query working using
{"start_latitude": 37.7752278, "start_longitude": -122.4197513, "end_latitude": 37.7773228, "end_longitude":-122.4272052}

A simple ASP .NET MVC API controller using roles

I wrote a web application using ASP .NET MVC and authorization system by default. I configured IdentityRole and input through external providers. Using the current database I have created my data context. Now I want to write a Xamarin.Android app and connect to my database, I want a simple API. But the feature that you want to access this API was only available to user with a certain role. The API is really very simple and therefore do not want to add to the draft WCF or WebAPI project. How to do it best?
First, you don't need a separate project to use Web Api; you can use both MVC and Web Api in the same project. For one off endpoints for things like in-site AJAX requests, just creating MVC actions that return JSON or XML would be fine, but if you're talking about a true API, even if it's fairly simplistic, I'd say go Web Api.
You'd protect your Web Api actions much the same as you would your MVC actions, using the [Authorize] attribute. If you need to restrict by role, you just pass a role(s) to that. However, the big difference here, especially if you're serving a mobile app, is that you'll need pass the authorization along with the request. That's generally accomplished using the Authorization header along with a bearer token. Basically, you would need to set up an endpoint that signs a user in and returns a token. Then, each subsequent request that needs authorization includes that token in the header.
I want to finish and to fully answer this question and close this topic. I've been searching for how to add the ability for a mobile client to connect to an existing site on ASP.NET MVC. In my search, I came across a great article Justin Hyland on March 2, 2014
In principle, everything in this article is well and clearly written, but I want to make a tiny contribution for clarity.
Under Setup WebAPIConfig stated that the need
added in the following code to the WebApiConfig Register method
But if we consider the case ASP.NET MVC we don't have such file. It's all very simple, you just need such a file to create the folder App_Start. The contents of the file can be left exactly as it is in the article.
To get rid of the bugs which will inevitably appear we need to install two nuget package: Microsoft.AspNet.WebApi and Microsoft.AspNet.WebApi.Owin.
Excellent! Now we can turn to the method to obtain the token and then adding the token to the query we can get the needed data closed by the attribute [Authorize].
A small remark. If You need to access a method which is closed for a specific role that to the Authenticate method from the article should add a few lines of code. Immediately after the line:
identity.AddClaim(new Claim(ClaimTypes.Name, user));
add the line:
identity.AddClaim(new Claim(ClaimTypes.Role, role));
where role you can get the following, for example:
var userIdentity = UserManager.FindAsync(user, password).Result;
var role = RoleManager.FindById(userIdentity.Roles.First().RoleId).Name;
User and password you have to send a request.
I also want to give an example of code which will send request and receive response. To not have to look for and immediately start coding.
async Task<string> GetToken(string userName, string password)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>( "user", userName ),
new KeyValuePair<string, string> ( "password", password )
}
);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(APP_PATH + "/Authenticate", content);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
async Task<string> GetUserInfo(string token)
{
using (var client = CreateClient(token))
{
var response = await client.GetAsync(APP_PATH + "/ValidateToken");
return await response.Content.ReadAsStringAsync();
}
}
HttpClient CreateClient(string accessToken = "")
{
var client = new HttpClient();
if (!string.IsNullOrWhiteSpace(accessToken))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
return client;
}
All have only to call the appropriate methods in the correct order. I hope that is useful to someone.
P.S.
If You create a new project in Visual Studio to get this functionality you just need to tick:

How to do function tests for TWITTER API

I am creating a web app for a project. I want to allow my users to post there blogs onto twitter using the twitter API. they will generate a blog inside my website and if they would like to share their blog via twitter. No so much testing if the Twitter API works, more as if it works inside of my website, as in if my syntax is appropriate, and if how i am incorporating it is correct. Its for a class project.
Assuming you are using C# / ASP.NET, you would be writing a class to make your API calls which can be tested independently. I would suggest downloading the open source Twitterizer DLL and plugging that into your web project, mostly for the OAuth implementation.
So, if you were posting a Tweet, you could write a static method as follows:
public static bool CreateTweet(Twitterizer.OAuthTokens tokens, string tweetText)
{
var response = Twitterizer.TwitterStatus.Update(tokens, text);
return response.Result == Twitterizer.RequestResult.Success;
}
And your test code would look like this:
void Test()
{
var tokens = new Tw.OAuthTokens
{
_accessToken,
_accessTokenSecret,
_consumerKey,
_consumerSecret,
};
var testTweet = "test tweet text";
CreateTweet(tokens, testTweet);
}
You would need to obtain the tokens either via Twitter's login process or have them stored if you don't expect users to log in.
And then basically the test code above would be moved into the appropriate piece of code-behind in your ASP.NET application and it should just work!

Need to Authenticate the Users using Twitter, Google, Facebook Apis through oauth plugin?

First i briefly want to know how you can use oauth works. What we need to pass in this plugin and what this plugin will return. Do we have to customize the plugin for different php frameworks. I have seen that their is a different extension of oauth for different framework, why is that?
I need to authenticate the users using social networks in yii framework and I have integrated eouath extension of yii to use oauth and have made an action to use access the ads service of google user like this
public function actionGoogleAds() {
Yii::import('ext.eoauth.*');
$ui = new EOAuthUserIdentity(
array(
//Set the "scope" to the service you want to use
'scope'=>'https://sandbox.google.com/apis/ads/publisher/',
'provider'=>array(
'request'=>'https://www.google.com/accounts/OAuthGetRequestToken',
'authorize'=>'https://www.google.com/accounts/OAuthAuthorizeToken',
'access'=>'https://www.google.com/accounts/OAuthGetAccessToken',
)
)
);
if ($ui->authenticate()) {
$user=Yii::app()->user;
$user->login($ui);
$this->redirect($user->returnUrl);
}
else throw new CHttpException(401, $ui->error);
}
If I want to use other services like linkedin, facebook, twitter just to sign up the user should I just change the scope and parameters or also have to make some changes elsewhere. How do I store user information in my own database?
In simple case you may use the table "identities" with fields "*external_id*" and "provider". Every OAuth provider must give unique user identificator (uqiue only for that provider). To make it unique on your site you may use pair with provider predefined name (constant). And any other additional fields (if a provider gives it).
In the same table you should store identity data of internal authorization, with provider name 'custom' (for ex.). To store password and other data use a separate table, and PK from this table would be your "*external_id*". Universal scheme.
And PHP, something like this:
class UserIdentity extends CUserIdentity
{
protected $extUserID;
public function __construct($extUserID)
{
$this->extUserID = $extUserID;
}
...
public function authenticate()
{
...
//After search $this->extUserID as PK in users table (built-in authorization)
...
$identity = Identities::model()->findByAttributes(array(
'ext_id' => $this->extUserID,
'service' => 'forum',
));
if(!count($identity))
{
$identity = new Identities;
$identity->ext_id = $this->extUserID;
$identity->service = 'forum';
$identity->username = $userData['username'];
$identity->save();
}
$this->setState('id', $identity->id);
...
}
}

Resources