Code iOS Laravel

iOS In-app purchases and Laravel

It’s been a while since I’ve used IAP on iOS. This series of articles will follow my erratic thought process as I create the following:

  • A small web app, managing anonymous user accounts and their credit balance
  • An iOS application which allows you to top-up your account, restore purchases etc without the need to create an account.

This post will cover the authentication side of the app – I’m taking the new Laravel Sanctum functionality for a spin.

First thing I did was set up a new Laravel app, install Sanctum, and migrated all the things. I know I’m going to need an endpoint that accomplishes the following:

  • Handle a POST request with some JSON data
  • Check the request comes from a valid source
  • Creates an anonymous user
  • Issues a token for that user
  • Returns a JSON response with the user token

My function ended up looking like this:

public function token(Request $request){

    $validation = Validator::make($request->all(),[
        'key' => 'required',

        return response()->json(["errors"=>$validation->messages()], 200);

    //TODO: Something a bit more robust than this; probably use it to check against an Apps table or something like that
    if($request->key != "supersecretappidentifier")

    //Create anon user. You could use your own user model. I've stuck with the Eloquent one and faked the data, as I figure I may allow users to create an account at a later stage.
    $faker = Factory::create();
    try {

        $user = User::create([
            'name' => $faker->name,
            'email' => $faker->email,
            'password' => Hash::make($faker->password),

        //Create the Sanctum token; again you'd probably use the name of the App or something
        $token = $user->createToken($request->key);

        return response()->json(["token"=>$token->plainTextToken], 200);
    } catch (\Exception $e)
        return response()->json([
            "message" => $e->getMessage()
        ], 400);

Hit the endpoint with Postman and you’ll be given a shiny token to use in subsequent requests.


Great! Now to make an app do it. Swift’s not my strong suit at the moment – I’m still writing most of my iOS code in Objective-C – so please bear with me.

We need functionality that does the following:

  • Checks if there’s a token on the device
  • If not, makes a POST request to our web service
  • Retrieve and store the token in the iCloud Key-value storage

I’m using iCloud storage so that if my user uses the app on another device – say their iPad – they’ll be linked to the same account at the web service end, whilst remaining anonymous in the eyes of my application. You’ll need to add the iCloud Key-value storage capability to your app to make this work.

The code looks a little like this. I’m using AlamoFire to handle network requests.

let token = NSUbiquitousKeyValueStore.default.string(forKey: "laravelToken")
if(token == nil)
    let params: [String:String] = [
        "key": "supersecretappidentifier"
    AF.request("http://credits.test/api/auth/token",method: .post, parameters: params, encoding:JSONEncoding.default).responseJSON { response in
        switch response.result {
            case .success(let JSON):
                let response = JSON as! NSDictionary
                let token = response.object(forKey: "token")!
                NSUbiquitousKeyValueStore.default.set(token, forKey: "laravelToken")
            case .failure:

The first time you run the app, it’ll make the request and store the token. Subsequent runs will print out the stored token.

That’s it for today I think – to recap, we’ve created a web service which creates an anonymous user and a token for the app to retrieve and store.

In the next article, I’ll add some credits functionality to the user and display our balance on the iOS device.

Code Thoughts

Side projects

Over the years I’ve worked on hundreds of side projects that have never seen the light of day. There’s a number of reasons for this; sure some are abandoned, but others are just prototypes, others find their ideas repurposed for client work. Others are on the later-base.

They’re always fun to work on, give you a different perspective and ultimately make you better at your craft.

I’m hoping to follow more of my own advice and get a few more of them shipped.

First one I’m going to look at is an iOS client for HobbyScribe. It has a modest user base and a modest set of features, but should provide a couple of useful and re-usable elements for more apps I’ve got lying around.

Don’t want to make it some sort of app a month challenge, but I would like to get a couple more out there if only to try things out.

Bear with me.


WooCommerce: Don’t show variation attributes on the front-end

Recently imported many products, variations, attributes in to WooCommerce from a CSV file. All the attributes used for variations were set to show on the front-end – whoops!

Two options: Go through each product and uncheck “Visible on the product page” or this bit of code:

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1,

    $products = get_posts($args);
    foreach ($products as $post) {
        $update = false;
        $meta = get_post_meta($post->ID,'_product_attributes',true);
            foreach($meta as $k => $a)
                if($a['is_variation'] && $a['is_visible'])
                    $a['is_visible'] = 0;
                    $update = true;
                    $meta[$k] = $a;


                update_post_meta( $post->ID,'_product_attributes', $meta);

Loops through products, and changes the meta as if the box were unchecked. Use at your own peril – definitely not on a production site!