Jul 132012
 
photo

After I downloaded  iOS6 on my iPhone last week, the first icon I clicked on was Passbook only to find that Apple had not put any example passes in there. Since Passbook was the primary reason I had downloaded iOS6, I dug into the API and learned how to create a pass myself. It was a great learning experience that I want to share with others. I also provide a shell script to automate the pass generation process and also present to you, iPass.pk, a user-friendly GUI-based service to create passes.

What is a pass? 

A pass is in fact a regular zip archive a .pkpass extension. It contains the following files:

1. logo.png (optional): The file to be used as the logo.

2. background.png (optional): The file to be used as the pass’ background.

3. icon.png (optional): The file to be used as the icon.

4. manifest.json (required):This file contains a JSON object with SHA1 hashes of all files in the pass except the signature file (as its generated using manifest.json) and the manifest.json file itself. The file has the following format:

{
  "pass.json" : "<sha1 pf pass.json file>",
  "logo.png" : "sdfqefqefqef",
  ...
}

For reference, the easiest way to create a SHA1 hash in Linux is to use the command:

openssl SHA1 <filename>

5. signature (required): File created by signing the manifest.json file with the certificate

6. pass.json (required): It contains a JSON object which specifies the type, formatting, and the data to be displayed on the pass. Apple’s reference is available here, however, it is far from complete and is missing several important details. The only real way to understand pass.json is trial-and-error:  try to generate lots of passes with different options and see the outputs on iOS6 itself. So, that what I was doing for the last two weeks.I developed a few tools to helps me iterate through these options really fast. First it a C-shell script to generate passes from the command-line and second is a pass designer at iPass.pk that allows you to change the values/labels of fields in a reasonable GUI.

Let me give you a few examples of what I have learned that was not mentioned any where in Apple’s docs.  First, to privde some context, lets take a look at a sample pass file and its JSON object with a description of each field.

Screenshot of a boarding pass

Boarding Pass

The most interesting fields are: logoText, and primary, secondary, auxiliary, and header fields.  They are all labelled in this annotated screenshot. I have filled each field with <field type abbreviation><field number in the corresponding fields array>. Thus. P1 implies Primary Filed 1, i.e., the first primary field in the primaryFields array. Similarly S* denotes secondary fields, A* auxiliary fields, and H* header fields. Note their positions, font-sized, and styles. To checkout the other fields, try creating some passes using the following procedure or use the GUI at iPass.pk.

 

How to generate passes manually?

In case, you don’t want to use the GUI to iterate through the passes, you can use my C-shell script. The C-shell script in effect performs the following steps.

Step 1: Generate the Apple Developer Certificate

Go to the Apple Developer Portal and request a pass type identifier and your certificate. Export a .p12 file from the Key chain.

Step 2:  Generate key.pem and certificate.pem

openssl pkcs12 -in "My PassKit Cert.p12" -clcerts -nokeys -out certificate.pem
openssl pkcs12 -in "My PassKit Cert.p12" -nocerts -out key.pem

Step 3: Gather files 

Copy pass.json and any logo/icon/background image files in a folder.

Step 4: Generate manifest.json 

The goal is to generate JSON object which contains the SHA1 hashes of all the files your gathered in Step 3. I used the following csh script to generate manifest.json

 set MANIFEST = ../manifest.json
 echo '{' > $MANIFEST
 foreach i (*)
   set sha1 = `openssl sha1 $i | cut -d' ' -f2`
   echo \'$i\' : \'$sha1\', >> $MANIFEST
 end
 echo '}' >> $MANIFEST
 cp $MANIFEST .

Step 5: Generate signature

Execute the following csh commands to get a signature file:

set PASSWORD = xxxx
openssl smime -passin pass:$PASSWORD  -binary -sign -signer $CWD/certificate.pem -inkey $CWD/key.pem -in manifest.json -out signature xs-outform DER

Now email this file to yourself, and open it. Cool?

Step 6: Zip the pass

zip test.pkpass *

 

Now email test.pkpass to yourself and see the magic.

 

Let me know if you if you have any questions/comments about passes, this tutorial, iPass.pk, or the shell script.

 

  59 Responses to “Generating passes for iOS6′s Passbook”

  1. icon.png and icon@2x.png are now required.

  2. Hi, thank you for your tutorial!
    I have followed the steps but the pass I get is not recognised by my iPhone (it’s running iOS6 beta 3, and passes from different sources usually work). The only difference I can see with working tickets is that my generated signature file is seen as a ‘document’ instead of a ‘Unix Executable File’… Would you have an idea of what’s going on?

    • @Georges – Is there any chance you were able to get yours working because I am having the exact same issue. When I mail it to myself, it is not being recognized like the other passes that I have downloaded off of the internet. I press it and an empty box pops up with only a ‘Cancel’ button visible. Any help would be… well… helpful :)

      Thanks! Mike

      • We have the same issue indeed. And unfortunately I could’t make it work yet…

      • Hey, my pass works now!
        And actually I didn’t change anything. I was just trying to upload my pass to a webserver, send it again by email (playing with the MIME type) etc… The last thing I did was to send both my pass and a working pass in the same email and both of them were recognised on my iPhone. Since that, I have no problems anymore – but I have no idea what solved the issue.
        The little difference in my signature file I mentioned seems not to be blocking.

  3. Hi, I was following your steps and when I tried to generate signature it says:

    unable to load certificate
    140735321534940:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:696:Expecting: TRUSTED CERTIFICATE

    is there anything I should do?

    Thanks!

  4. I can’t get your method to work correctly. When I drag the pkpass file into iOS Simulator, the passcard renders correctly, but clicking the ‘Add’ button causes the following error:

    Invalid data error reading card pass.votizen.membership/123456. Manifest signature did not verify successfully

    I am successfully able to package and add the passcard, if I create it using the signpass tool, so I’ve narrowed the culprits to the p12 file or something broken in the packaging tool. I noticed that the signature file created by the signpass tool is much different than the one created by your script, but don’t know if that’s important.

    I created the p12 file from the Pass Type Id certificate in my Keychain Access.

    Do you have any ideas what I could be doing wrong?

    thanks

  5. You are missing -certfile wwdr.pem when singing the manifest

  6. Hi
    Is it possible to download passbook for ipad mini and ios7?
    Thx
    E

  7. I do not know if it’s just me or if perhaps everybody else encountering
    problems with your blog. It seems like some of the written text within your posts
    are running off the screen. Can somebody else please comment and let me know if this is happening to them too?
    This might be a issue with my browser because I’ve had this happen previously.
    Kudos

  8. Amazing Webpage, Carry on the very good job. Thanks for your time!.

  9. Sustain the good job and bringing in the crowd!

  10. So insightful… look ahead to coming back

  11. I’m really enjoying the theme/design of your site. Do you ever run into any internet browser compatibility problems?
    A handful of my blog audience have complained about my blog
    not working correctly in Explorer but looks great in Firefox.

    Do you have any tips to help fix this issue?

  12. However, these gardens will take a lot more time and energy to create than koi waterfalls.

    Cystitis happens due to the penetration of bacteria into the urethra.
    Fortunately, nowadays you do not need to be like an emperor to adopt an indoor wall mounted waterfall sounds like.

  13. I am regular visitor, how are you everybody? This article posted at
    this website is genuinely pleasant.

  14. If you use a network of desktop computers,
    you connect the router directly to your systems.

  15. If somе ߋne wants Introduction to Business Wiley be updated
    with mmost recent technologiеs theгefore he
    must be pay a vusit this webb pаge and be up to date every day.

  16. Hі thete to all, it’s truly a gopod for mе to pay a visit tҺis site,
    it consists of pricfeⅼess Information.

    my blog post lesson plan [tbc.Businesscommunicationnetwork.com]

  17. Еxcellent post.Never knew this, thank you for letting me know.

    Аlso visitt my pаge: methods of teaching introduction to business

  18. Loving the information ⲟn tһis internet sіte, yyou havе done grreat job on tɦe pߋsts.

    my blog – Business and Administrative Communication

  19. Financing your business using personal savings (and
    paying back what you borrowed) can be a great option if you believe that you are disciplined enough
    to actually pay the money back in a timely manner.

  20. El resultado de la suma de las fuerzas ejercidas por
    la Luna y el Sol es una onda compuesta por 2 crestas, cuya situación depende de las situaciones relativas del
    Sol y de la Luna en un instante dado.

  21. Saiba que mel é considerado um fraco substituto a fim de que melaço,
    logo conclui-se que melaço poderá provocar alterações significativas dentro de sabor do sustento de mel.

  22. Ought to you discover yourself eager to enjoy a new
    Punisher recreation out on the Bayou, this one has your identify on it.

    Alsoo visit my blog … Mafia III download

  23. In a lump sum annuity you get all the money that is due to you after a deduction of taxes, charges,
    and any applicable penalties.

  24. I have a friend who is having a birthday this week and I knew this was the perfect card for him!

  25. Essa plataforma também garante a criação de páginas sem nenhuma dificuldade, tem
    recursos essenciais e também está entre as melhores enquanto matéria é preço.

  26. Blog, portanto, serve ao seu consumidor como porta de ingresso para a sua loja, oferecendo
    a ele todas e cada uma das informações que ajudarão na sua resolução de compra.

  27. Entenda-se por plataforma boa, algo que nos
    atenda em materia de recursos, sem bugs e também com respeito decente.

  28. Entretanto, é muito essencial saber como se cevar e a quantidade certa consumida.

  29. Tire suas conclusões pesquisando opiniões em fóruns e também faça contato com que já as utiliza,
    analisando desempenho, a facilidade de chegada ao suporte e nível de satisfação dele em relação à loja virtual que tem.

  30. É essencial ressaltar que não adianta só passar creme:
    é preciso passar da maneira correta, que é incessantemente com uma massagem mas vigorosa, de inferior a fim
    de cima, preferencialmente circundar, com duração média de
    10 minutos e duas vezes ao dia.

  31. Café também é utilizado a fim de elaborar cremes a fim de reduzir as estrias,
    da mesma maneira que será magnífico a fim de a celulite.Combinado com suco ácido do
    limão, seu poder de ação será maior.

  32. A panturrilha é uma localidade onde lona gorduroso subcutâneo
    costuma ser menor, por isso, é menos geral haver celulite.

  33. Que é grátis (e também geralmente open source) é sistema
    de loja virtual, como ela trabalha e também suas funcionalidades.

  34. Desta maneira já vimos que a celulite é uma gordura que precisa de
    ser queimada, que a atrofia muscular irá ajudar para a celulite se forme de modo não
    uniforme no nosso corpo e que a falta de hidratação no nosso corpo fará com que a celulite seja visível.

  35. Para eliminar a celulite do corpo, é preciso entender realmente que é a celulite,
    que a faz dificultar e também uma vez que trabalhar na desculpa do impecilho de uma forma efetiva.

  36. A celulite é sem questionamento um dos avós complicações que, maioritariamente a população feminina encontra enquanto se fala em
    situações de estética e também bem-estar, de antemão de mais a celulite é mas generalidade do que lhe pode parecer.

  37. Enorme dificuldade é a penetração dos ativos de tratamento que, geralmente,
    não conseguem chegar na camada gordurosa, que é onde entrave está concentrado.

  38. Magnificent website. Plenty of helpful information here.
    I am sending it to some pals ans additionally sharing in delicious.

    And of course, thanks in your sweat!

  39. Não é porque seu varejo não é físico ou porque você não está pensando em conseguir um contribuição financeiro,
    que não precisa de um projecto de negócios.

  40. Claro que nem todos os blogs, aliás a maior parte, não possui como alvo ganhar dinheiro acessível, mas anterior atingir outrem
    objetivos pessoais, que podem ser os mais variados.

  41. As empresas descobriram na Rede um supimpa caminho a fim de melhorar seus lucros e as vendas conectado
    dispararam, transformando a Rede em verdadeiros shoppings centers
    virtuais.

  42. Já sob a ótica de um rosto que possui três imóveis, mas morada de praia e plaino,
    fazendas e etc, este é só um pobre que melhorou para toda a vida.

  43. Princípios para as mães e pais: outro desafio para as infantes é aprender a impelir e
    também soltar com rato, para isto nós projetamos muitos
    jogos onde eles poderão praticar com os números, os autos, os dinossauros, formas ou reconhecer os pares e também as tramas.

  44. Get out of debt today. Bankruptfy is a dirty scary word.
    But ojce you learn the ins and outs of bankruptcy it iis not so scary
    anymore. In fact, you may conclude it is
    your best chance at starting a new future.

  45. A armadilha funciona da seguinte forma: Primeiro eles
    criam pelo menos 3 ou 4 tipos de cartão de crédito diferentes que utilizam nomes pomposos como Gold, Diamante, Platinum, Esmeralda, ou qualquer outro mineral ou
    metal precioso.

  46. Termo disfunção erétil foi proposto durante a realização de um consenso sobre insuficiência
    sexual realizado em 1992 tendo sido definido como: a incapacidade de obter e
    também sustentar ereção suficiente a fim de que
    uma relação sexual satisfatória”.

  47. Dividido em três módulos, que abordavam a começar de a introdução do Facebook dentro de mundo corporativo até a estudo de certos principais cases
    de sucesso da própria agência, curso contou com uma abordagem prática, descontraída e também consultiva, destacando
    aspectos fundamentais para a maximização dos resultados na plataforma, que nem a segmentação do público-branco.

  48. Magnificent beat ! I would like to apprentice whilst you amend your web site, how could i subscribe for a weblog web site?
    The account helped me a acceptable deal. I have been tiny bit familiar of this your broadcast offered shiny clear concept

  49. Essencialmente, você cria uma conta no interior de
    Facebook estrategicamente para vulgarizar e promover um info-resultado.

  50. Hahahaha… Parabéns pelo excelente e claro artigo, realmente a quantidade de informação aqui é digna de ser cobrada, porém, sabemos
    que atrair cliente com um docinho é mais facil que puxar ele pra dentro
    da loja!!!!

  51. The Rx Crocs will slow the progression of calluses,
    bunions and hammertoes, which will give you prettier feet,
    less pain and will pay off big time as you get older.

  52. Também, isso é essencial também para definir tipo de estudo de mercado que será mais apropriada para trepar ajudar.

    my site como investir em a

  53. Attractive section of content. I just stumbled upon your
    web site and in accession capital to assert that I acquire actually enjoyed
    account your blog posts. Anyway I will be subscribing to your augment and even I achievement you access consistently rapidly.

  54. A ereção é um dos fatores mais importante da libertinagem masculina,
    posto que diversos, para se sentirem homens, baseiam-se nela e na capacidade de manter pênis ereto.

    Feel free to visit my web blog: disfuncao
    eretil (Bruce)

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>