<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anil Paudel on Medium]]></title>
        <description><![CDATA[Stories by Anil Paudel on Medium]]></description>
        <link>https://medium.com/@theanilpaudel?source=rss-166573ec047------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tBJPQAW7H-qLZ8Lh.jpg</url>
            <title>Stories by Anil Paudel on Medium</title>
            <link>https://medium.com/@theanilpaudel?source=rss-166573ec047------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:36:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theanilpaudel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Quick Start: Kafka KRaft with Java and Spring Boot]]></title>
            <link>https://medium.com/@theanilpaudel/quick-start-kafka-kraft-with-java-and-spring-boot-b0ebfecd99a4?source=rss-166573ec047------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ebfecd99a4</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kraft]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Anil Paudel]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 11:52:45 GMT</pubDate>
            <atom:updated>2025-07-22T11:52:45.244Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I am going to show how to quickly configure and start Kafka KRaft using Docker and Java for Spring Boot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Sm4w4uROujhI7ZnOCFj-Xw.png" /></figure><p>First, a few things about <strong>Kafka</strong>.</p><p>From <a href="https://kafka.apache.org/intro">official documentation</a></p><blockquote>Kafka is a distributed system consisting of <strong>servers</strong> and <strong>clients</strong> that communicate via a high-performance <a href="https://kafka.apache.org/protocol.html">TCP network protocol</a>. An <strong>event</strong> records the fact that “something happened” in the world or in your business. <strong>Producers</strong> are those client applications that publish (write) events to Kafka, and <strong>consumers</strong> are those that subscribe to (read and process) these events.</blockquote><p>An eli5 from ChatGPT</p><blockquote><em>You have a </em><strong><em>big notebook</em></strong><em> where people can write messages (like “Buy 10 apples” or “User logged in”). But many people want to write and read messages at the same time.</em></blockquote><blockquote>So, you:</blockquote><blockquote><em>Break the notebook into </em><strong><em>many pages</em></strong><em> (this is like Kafka </em><strong><em>partitions</em></strong><em>).</em></blockquote><blockquote><em>Put each page on a </em><strong><em>different desk</em></strong><em> (this is Kafka’s </em><strong><em>distributed servers</em></strong><em>).</em></blockquote><blockquote><em>People come in, write messages on the desks, and others come in to read them.</em></blockquote><p>And, few things about <strong>KRaft</strong>.</p><p>Initially, Kafka relied on Zookeeper for managing metadata, controllers and clusters. KRaft was introduced in Kafka 2.8. This completely eliminated the reliance on Zookeeper. KRaft is a built-in service based on Raft consensus protocol, so Kafka now is not relying on any external dependency to manage the metadata, controllers and clusters rather it manages it within itself.</p><p>Now, let’s setup a docker-compose.yml file for starting up Kafka</p><pre>services:<br>  kafka:<br>    image: confluentinc/cp-kafka:latest<br>    hostname: kafka<br>    container_name: kafka<br>    ports:<br>      - &quot;9092:9092&quot; # Maps Container Port 9092, default for Kafka client communication, to Host Port 9092<br>      - &quot;9093:9093&quot; # Maps Container Port 9093, used for advertised listeners for external clients, to Host Port 9092<br>    environment:<br>      KAFKA_KRAFT_MODE: &quot;true&quot;  # Enables KRaft mode in Kafka.<br>      KAFKA_PROCESS_ROLES: controller,broker  # Kafka acts as both broker and controller.<br>      KAFKA_NODE_ID: 1  # A unique ID for this Kafka instance.<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: &quot;1@localhost:9093&quot;  # Defines who can vote in the controller quorum; part of KRaft. Format nodeId@host:controllerPort<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093 # PLAINTEXT is for client communication. CONTROLLER is for internal controller communication<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092 # Producers and Consumers will connect to this address<br>      KAFKA_LOG_DIRS: /var/lib/kafka/data  # Path where Kafka stores its logs.<br>      KAFKA_AUTO_CREATE_TOPICS_ENABLE: &quot;false&quot; # Kafka will NOT automatically create a topic.<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1  # Since we’re running one broker, one replica is enough.<br>      KAFKA_LOG_RETENTION_HOURS: 168  # Keep logs for 7 days.<br>      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0  # No delay for consumer rebalancing.<br>      CLUSTER_ID: &quot;fQEKGPQsQtSJMUICvEYA9g&quot;  # A unique ID for the Kafka cluster.<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>      - ./data:/var/lib/kafka/data  # Store Kafka logs on your local machine.</pre><p>This is the docker compose file. On every line there’s a comment written to describe what the command does.</p><p>To generate a CLUSTER_ID run this command</p><pre>docker run --rm confluentinc/cp-kafka:latest kafka-storage random-uuid</pre><p>CLUSTER_ID is a base64-encoded UUID.</p><p>Then we run this docker compose up -d command and Kafka will be up and running in seconds.</p><p>Now, we jump over to Spring Boot.</p><p>This will be our configuration file application.yml</p><pre>spring:<br>  application:<br>    name: KafkaTutorial<br>  profiles:<br>    active: dev<br>  kafka:<br>    consumer:<br>      bootstrap-servers: localhost:9092 # The consumer will connect to Kafka broker at this address<br>      auto-offset-reset: earliest # Either earliest, latest or none.<br>      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer<br>      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer<br>      properties:<br>        spring.json.trusted.packages: com.theanilpaudel.kafkatutorial<br>    producer:<br>      bootstrap-servers: localhost:9092<br>      acks: -1 # Either 0,1 or -1. -1 waits for all replicas to acknowledge<br>      key-serializer: org.apache.kafka.common.serialization.StringSerializer<br>      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer</pre><p>Here again, there are comments on every line to briefly describe what they are.</p><p>For auto-offset-reset I suggest you follow this <a href="https://quix.io/blog/kafka-auto-offset-reset-use-cases-and-pitfalls">link</a> for a proper understanding.</p><p>Here, we are configuring both producer and consumer in a same Spring Boot project. We can always segregate them as a parts of microservices as well.</p><p>Now, let’s move to the Producer</p><pre>@Data<br>public class Event {<br>    String key;<br>    String value;<br>}</pre><pre>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class KafkaProducer {<br>    public static final String TOPIC = &quot;kafka_topic&quot;;<br><br>    private final KafkaTemplate&lt;String, Event&gt; kafkaTemplate;<br><br>    public void publish(Event event) {<br>        String key = event.getKey();<br>        kafkaTemplate.send(TOPIC, key, event);<br>        log.info(&quot;Sent message: {}&quot;, event);<br>    }<br>}</pre><pre>@Slf4j<br>@RequestMapping(&quot;/events&quot;)<br>@RestController<br>public class EventController {<br><br>    @Autowired<br>    private KafkaProducer kafkaProducer;<br><br>    @PostMapping(&quot;/publish&quot;)<br>    public ResponseEntity&lt;Event&gt; post(@RequestBody Event event) {<br>        kafkaProducer.publish(event);<br>        return ResponseEntity.ok(event);<br>    }<br><br>}</pre><p>Here, we defined a KafkaProducer that will produce or send events. The producer is triggered through an EventController.</p><p>A little bit more about Topics from the official documentation</p><blockquote>Events are organized and durably stored in <strong>topics</strong>. Very simplified, a topic is similar to a folder in a filesystem, and the events are the files in that folder. An example topic name could be “payments”. Topics in Kafka are always multi-producer and multi-subscriber: a topic can have zero, one, or many producers that write events to it, as well as zero, one, or many consumers that subscribe to these events.</blockquote><p>Now, over to the Consumer.</p><pre>@Slf4j<br>@Component<br>public class KafkaConsumer {<br><br>    /**<br>     * The group-id is for consuming partitions of data<br>     */<br>    @KafkaListener(topics = KafkaProducer.TOPIC, groupId = &quot;kafka-tutorial-group&quot;)<br>    public void listen(Event event) {<br>        log.info(&quot;Received event: {}&quot;, event);<br>    }<br>}</pre><p>Now, run the project and send a post request like in the cURL below</p><pre>curl - location &#39;http://localhost:8080/events/publish&#39; \<br> - header &#39;Content-Type: application/json&#39; \<br> - data &#39;{<br> &quot;key&quot;:&quot;1&quot;,<br> &quot;value&quot;:&quot;Inventory updated again.&quot;<br>}&#39;</pre><p>Back in your logcat, these will be printed</p><pre>KafkaProducer : Sent message: Event(key=1, value=Inventory updated again.)<br>KafkaConsumer : Received event: Event(key=1, value=Inventory updated again.)</pre><p>The producer sent the event Event(key=1, value=Inventory updated again.) and consumer consumed the event.</p><p>So this how we setup Kafka KRaft using docker and then produce and consume events using Java for Spring Boot.</p><p>If you have any queries, please comment or find me on <a href="https://bsky.app/profile/theanilpaudel.bsky.social">Bluesky</a>, <a href="https://twitter.com/theanilpaudel">Twitter</a> or <a href="https://www.linkedin.com/in/theanilpaudel/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ebfecd99a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginners guide to setting up Gitlab CI/CD with Docker for Spring Boot]]></title>
            <link>https://medium.com/@theanilpaudel/beginners-guide-to-setting-up-gitlab-ci-cd-with-docker-for-spring-boot-7b69e8390aec?source=rss-166573ec047------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b69e8390aec</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gitlab-ci-docker]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Anil Paudel]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 16:45:47 GMT</pubDate>
            <atom:updated>2022-06-30T16:45:47.770Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will be talking about how you can set up Gitlab CI/CD for a Spring Boot project using a Docker container. We will assume that you have a basic knowledge of Docker and that you already have a Spring Boot project ready for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1WWJvl3bpE13qkk.jpg" /></figure><p>Let’s first create a Dockerfile in the root directory of the project, which will look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f60086af9c219a2fc9bab0297d6fdda/href">https://medium.com/media/0f60086af9c219a2fc9bab0297d6fdda/href</a></iframe><p>This file is used to create a docker image while executing the codes mentioned in the file. So this file is saying, using openjdk:8<em> </em>create a myapp.jar file and copy and send it as an argument for docker.</p><p>We can push this docker image to Gitlab Container Registry for it to become available for us to pull from the server. We will use a command in our ci/cd for pushing it to the container registry.</p><p>Next, we will need a <em>.gitlab-ci.yml</em> file again in our root directory. This is a configuration file where we include all the codes for deployment.</p><blockquote>This file is used by <a href="https://docs.gitlab.com/ee/ci/runners/">GitLab Runners</a> to manage our project’s builds and deployments.</blockquote><p>.gitlab-ci.yml file looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e63ff331b540cca38f1d4f1ccad5641/href">https://medium.com/media/5e63ff331b540cca38f1d4f1ccad5641/href</a></iframe><p>I will now describe the contents of the file.</p><p>The variables are where we define our variables for the build environment and DOCKER_DRIVER: overlay is the storage driver for Linux distributions and there’s a new one with better performance overlay2</p><blockquote><a href="https://docs.docker.com/storage/storagedriver/select-storage-driver/">overlay2 is the preferred storage driver for all currently supported Linux distributions, and requires no extra configuration</a>.</blockquote><p>Then we have stages. This is where we define the lifecycle of our deployment. Currently, we have only 2 stages. We first build a jar file into a docker container and then deploy them.</p><p>Then there are <em>jobs</em>. <em>jobs</em> are what perform the operations in our <em>stages</em> so we assign them to a particular stage.</p><p>Here we have 2 jobs; maven-build-job and deploy-job</p><p>In<em> maven-build-job</em> we are building a jar file using maven which we have assigned in the Dockerfile at the beginning of this article. This job will basically run mvn packagecommand and build us a jar file.</p><p>In deploy-job</p><ul><li>we are first specifying a docker image</li><li>then specifying the stage of the job</li><li>docker:dindstarts a docker daemon</li><li>then we are building a docker container image to send to the gitlab container repository using the Dockerfile</li><li>then we are login into the gitlab container repository to upload the container image</li><li>and finally, we are pushing the image to the gitlab container repository</li></ul><p>Now if you look at gitlab.com; CI/CD and Editor you should see the yml file and in editor you should see the jobs that we have defined and at the top, you should see the branch associated with the yml file.</p><p>So from now on, whenever you need to deploy a docker container image in Spring Boot, just do a git add &lt;&gt;, git commit -m &lt;&gt;, git push &lt;to the branch associated with the yml file&gt; and your jobs will execute themselves and your container image is successfully uploaded.</p><p>From here on you can pull the image on your server and deploy the code or use Kubernetes to further configure the container orchestration for the automation.</p><p>And, this is it for this article. If there is something missing or you have any queries, please comment or find me on <a href="https://twitter.com/theanilpaudel">Twitter</a> or <a href="https://www.linkedin.com/in/theanilpaudel/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b69e8390aec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Refresh token and Logout using Firebase Authentication and OkHttp in Android.]]></title>
            <link>https://medium.com/@theanilpaudel/handle-refresh-token-and-logout-using-firebase-authentication-and-okhttp-in-android-b443b842d41c?source=rss-166573ec047------2</link>
            <guid isPermaLink="false">https://medium.com/p/b443b842d41c</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[okhttp]]></category>
            <dc:creator><![CDATA[Anil Paudel]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 14:53:03 GMT</pubDate>
            <atom:updated>2022-06-15T14:53:03.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*n6EWh-fj0IrKjRFJKRd4KQ.jpeg" /></figure><p>In this article, we will be talking about how we can handle Refresh token and Logout on Firebase Authentication in Android.</p><p>We will be assuming that you have already implemented signup and login for your app. If you haven’t then please go to <a href="https://firebase.google.com/docs/auth/android/start">Firebase Authentication</a> and add signup and login from there.</p><p>The code snippet below shows the code for login using email and password.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f9d6776b2c2c2c526fec1f37d4b7010/href">https://medium.com/media/8f9d6776b2c2c2c526fec1f37d4b7010/href</a></iframe><p>We don’t need to save any tokens here after login because the following code shows how we can pass the token in <em>TokenInterceptor</em> using Firebase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c126106561a267eb0f138454df80ea4/href">https://medium.com/media/0c126106561a267eb0f138454df80ea4/href</a></iframe><p><em>TokenInterceptor.kt</em> class extends from <em>Interceptor</em> class in <em>OkHttp</em>. So whenever we hit an API this class will intercept it, perform the operations we write on the <em>Intercept</em> method, and pass on the request to the server.</p><p>From line number 8–10 we are proceeding the request as it is because, for login which is a POST request, we don’t need to add any Authorization header.</p><p>From lines 12–19 we are requesting the <em>FirebaseUser</em> first; if it is null, proceed the request as it is. Then we are requesting the bearer token from <em>FirebaseUser</em>.</p><blockquote>user.getIdToken(false)</blockquote><blockquote>Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.</blockquote><blockquote>Returns the current token if it has not expired. Otherwise, this will refresh the token and return a new one.</blockquote><p>We then wait for max 20 seconds for the task to complete; that is, for the task to return us a bearer token. This is a synchronous process because we need the token right here. Finally, we proceed with the request by adding the token in the header.</p><p>To summarize the <em>TokenInterceptor</em> class, we are intercepting every request and adding nothing or something depending on the api requirement, hence the name <em>TokenInterceptor</em>.</p><p>Next, we have the <em>TokenAuthenticator.kt</em> class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b3abbb985b5dc9dc9b20995e640112/href">https://medium.com/media/37b3abbb985b5dc9dc9b20995e640112/href</a></iframe><p>Whenever our token expires, we get <em>401 UnAuthorized </em>error response, in that case, TokenAuthenticator is will be called automatically and if the response is not successful we need to log out the user, because the session has expired, else we continue with the flow.</p><p>From lines 8–10 we are using a <em>LocalBroadcastManger</em> to broadcast a message to the receiver, which will be in <em>BaseActivity.kt</em>, informing that the token/session has expired and we need to log out the user from the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d49f595c3e0fe2811c01fcd1f911926/href">https://medium.com/media/0d49f595c3e0fe2811c01fcd1f911926/href</a></iframe><p>So, in the above code, we receive the <em>LocalBrodcastReceiver</em> message in <em>BaseActivity.kt</em> class and log out the user from the app.</p><p>We wire up the <em>TokenInterceptor.kt</em> and <em>TokenAuthenticator.kt</em> class in <em>OkHttp</em> using <em>DaggerHilt</em> like below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9227ae0e1f1201506fd2b98299fb572/href">https://medium.com/media/b9227ae0e1f1201506fd2b98299fb572/href</a></iframe><p>This is it. If there is something missing or you have any queries, please comment or find me on <a href="https://twitter.com/theanilpaudel">Twitter</a> or <a href="https://www.linkedin.com/in/theanilpaudel/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b443b842d41c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the power of Retrofit, Okhttp and Dagger 2 for JWT token authentication]]></title>
            <link>https://medium.com/@theanilpaudel/using-the-power-of-retrofit-okhttp-and-dagger-2-for-jwt-token-authentication-ad8db6121eac?source=rss-166573ec047------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8db6121eac</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Anil Paudel]]></dc:creator>
            <pubDate>Thu, 28 Mar 2019 05:27:32 GMT</pubDate>
            <atom:updated>2019-08-27T05:39:55.438Z</atom:updated>
            <content:encoded><![CDATA[<p>In most of the cases, we are developing apps using JWT authentication mechanism.</p><p>JWT authentication is, whenever you login a token is returned back by the server and for every other <em>api</em> request, you have to either send the token as <em>header</em> parameter or a <em>POST</em> parameter.</p><p>For example,</p><blockquote><a href="https://powerfulapi.com/users/1">https://powerfulapi.com/users/1</a> with Header, Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhbmlsIiwiZXhwIjoxNo4y6xHjel_8y1dW7rSrYgwlo8x1cF18eOzcLz8FH5pFw — TU0NjA5NjAyfQ.ZIIxIN5X9UccRmz15swdAB9L766CT9fcgswAVBck</blockquote><p>In PostMan it looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpZgbIPwVAh3zqm7QdkGZQ.png" /></figure><p>Sometimes you have to send it as a parameter like this</p><blockquote>https://powerfulapi.com/users?token=Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhbmlsIiwiZXhwIjoxNo4y6xHjel_8y1dW7rSrYgwlo8x1cF18eOzcLz8FH5pFw — TU0NjA5NjAyfQ.ZIIxIN5X9UccRmz15swdAB9L766CT9fcgswAVBck</blockquote><p>In JWT authentication you have to do this for each and every url/api after you get the token.</p><p>So in Android, we have Okhttp and Retrofit that handles all these tasks very easily with the help of interceptors.</p><p>At first, I will demonstrate without using Dagger2</p><p>Let’s first create a TokenInterceptor class like this</p><pre><strong>class </strong>TokenInterceptor <strong>constructor</strong>(<strong>private val token</strong>:String) :Interceptor{<br>    <strong><br>    override fun </strong>intercept(chain: Interceptor.Chain): Response {<br><br>        <strong>val </strong>original = chain.request()<br><br>        <strong>if </strong>(original.url().encodedPath().<em>contains</em>(<strong>&quot;/login&quot;</strong>)&amp;&amp; original.method().equals(<strong>&quot;post&quot;</strong>)<br>                || (original.url().encodedPath().<em>contains</em>(<strong>&quot;/sign-up&quot;</strong>) &amp;&amp; original.method().equals(<strong>&quot;post&quot;</strong>))<br>                ) {<br>            <strong>return  </strong>chain.proceed(original)<br>        }<br><br>        <strong>val </strong>originalHttpUrl = original.url()<em><br>        </em><strong>val </strong>requestBuilder = original.newBuilder()<br>            .addHeader(<strong>&quot;Authorization&quot;</strong>,<strong>token</strong>)<br>                .url(https://medium.com/originalHttpUrl)<br><br>        <strong>val </strong>request = requestBuilder.build()<br>        <strong>return </strong>chain.proceed(request)<br>    }<br>}</pre><p>What we are doing in this part is</p><pre><strong>if </strong>(original.url().encodedPath().<em>contains</em>(<strong>&quot;/login&quot;</strong>)&amp;&amp; original.method().equals(<strong>&quot;post&quot;</strong>)<br>                || (original.url().encodedPath().<em>contains</em>(<strong>&quot;/sign-up&quot;</strong>) &amp;&amp; original.method().equals(<strong>&quot;post&quot;</strong>))<br>                ) {<br>            <strong>return  </strong>chain.proceed(original)<br>        }</pre><p>we don’t need token for ‘login’ and ‘sign-up’ which are POST methods so ignore them.</p><p>Then we are adding the header like this</p><pre><strong>val </strong>requestBuilder = original.newBuilder()<br>            .addHeader(<strong>&quot;Authorization&quot;</strong>,<strong>token</strong>)<br>                .url(https://medium.com/originalHttpUrl)</pre><p>We would now be setting up a method to add the interceptor to Okhttp and Okhttp to Retrofit</p><pre><strong>fun </strong>setupRetrofit(tokenInterceptor: TokenInterceptor,baseUrl:String){<br>    <strong>val </strong>interceptor = HttpLoggingInterceptor()<br>    interceptor.setLevel(HttpLoggingInterceptor.Level.<strong>BODY</strong>)<br>    <strong>val </strong>okhttpBuilder = OkHttpClient().newBuilder().addInterceptor(interceptor).addInterceptor(tokenInterceptor)<br>    <strong>val </strong>client= okhttpBuilder.build()<br>    <strong>val </strong>gsonBuilder = GsonBuilder()<br>    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.<strong>LOWER_CASE_WITH_UNDERSCORES</strong>)<br>    <strong>val </strong>gson =  gsonBuilder.create()<br>    Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson))<br>        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())<br>        .baseUrl(baseUrl)<br>        .client(client)<br>        .build()<br>}</pre><p>This is a method that you could set up in any way you want. I am just making a simplification of it.</p><p>We will be getting the token after Login/Register so we would be initializing the interceptor there and then calling the retrofit builder method above.</p><pre><strong>val </strong>tokenInterceptor = TokenInterceptor(&quot;TOKEN_FROM_LOGIN&quot;)<br>setupRetrofit(tokenInterceptor,<strong>&quot;https://powerfulapi.com/&quot;</strong>)</pre><p>Now for every other url/api you don’t need to add this token parameter every time.</p><p>Now the following method simplifies</p><pre>@GET(<strong>&quot;profile/{username}&quot;</strong>)<br><strong>fun </strong>getProfile(@Header(<strong>&quot;Authorization&quot;</strong>) authorization: String, @Path(<strong>&quot;username&quot;</strong>) <strong>username</strong>: String): Observable&lt;Response&lt;ProfileResponse&gt;&gt;</pre><p>to</p><pre>@GET(<strong>&quot;profile/{username}&quot;</strong>)<br><strong>fun </strong>getProfile(@Path(<strong>&quot;username&quot;</strong>) <strong>username</strong>: String): Observable&lt;Response&lt;ProfileResponse&gt;&gt;</pre><p>If you are using Dagger2 then you most likely have Modules defined and then injected. In such cases, you can provide the <em>TokenInterceptor</em> as the parameter for Okhttp</p><pre>@Module<br><strong>class </strong>NetModule(<strong>var baseUrl</strong>: String) {<br><br>    @Provides<br>    @Singleton<br>    <strong>fun </strong>provideGson(): Gson {<br>        <strong>val </strong>gsonBuilder = GsonBuilder()<br>        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.<strong>LOWER_CASE_WITH_UNDERSCORES</strong>)<br>        <strong>return </strong>gsonBuilder.create()<br>    }<br><br>    @Provides<br>    @Singleton //providing tokenInterceptor like this<br>    <strong>fun </strong>provideOkhttp(tokenInterceptor: TokenInterceptor): OkHttpClient {<br>        <strong>val </strong>interceptor = HttpLoggingInterceptor()<br>        interceptor.setLevel(HttpLoggingInterceptor.Level.<strong>BODY</strong>)<br>        <strong>val </strong>okhttpBuilder = OkHttpClient().newBuilder().addInterceptor(interceptor).addInterceptor(tokenInterceptor)<br>        <strong>return </strong>okhttpBuilder.build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    <strong>fun </strong>provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {<br>        <strong>return </strong>Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson))<br>            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())<br>            .baseUrl(<strong>baseUrl</strong>)<br>            .client(okHttpClient)<br>            .build()<br>    }<br><br>}</pre><p>Using Dagger2 there is a slight change in the interceptor class, you need to use token like below so that you can set a value to it later on.</p><pre>@Singleton<br><strong>class </strong>TokenInterceptor @Inject <strong>constructor</strong>() :Interceptor{<br>    <strong>var token</strong>:String=<strong>&quot;&quot;<br>    override fun </strong>intercept(chain: Interceptor.Chain): Response {<br><br>        <strong>val </strong>original = chain.request()<br><br>        <strong>if </strong>(original.url().encodedPath().<em>contains</em>(<strong>&quot;/login&quot;</strong>)&amp;&amp; original.method().equals(<strong>&quot;post&quot;</strong>)<br>                || (original.url().encodedPath().<em>contains</em>(<strong>&quot;/sign-up&quot;</strong>) &amp;&amp; original.method().equals(<strong>&quot;post&quot;</strong>))<br>                ) {<br>            <strong>return  </strong>chain.proceed(original)<br>        }<br><br>        <strong>val </strong>originalHttpUrl = original.url()<em><br>        </em><strong>val </strong>requestBuilder = original.newBuilder()<br>            .addHeader(<strong>&quot;Authorization&quot;</strong>,<strong>token</strong>)<br>                .url(https://medium.com/originalHttpUrl)<br><br>        <strong>val </strong>request = requestBuilder.build()<br>        <strong>return </strong>chain.proceed(request)<br>    }<br>}</pre><p>Then in Login/Register section where you get the token for the first time</p><p><em>inject</em> them like this</p><pre>@Inject<br><strong>lateinit var tokenInterceptor</strong>: TokenInterceptor<br></pre><pre>//inside onCreate<br>(<em>application </em><strong>as </strong>MainApplication).<strong>netComponent</strong>.inject(<strong>this</strong>)<br></pre><pre><strong>tokenInterceptor</strong>.<strong>token </strong>= &quot;TOKEN_FROM_LOGIN<strong>&quot; //setting up the value </strong></pre><p>And then you don’t need to use token in any other url/api.</p><p>Update:</p><p>There is also the case of token being expired after certain time duration. For that, we can use <em>Authenticator</em> like this</p><pre>@Singleton<br><strong>class </strong>TokenAutheticator @Inject <strong>constructor</strong>(<strong>private val tokenHolder</strong>: Lazy&lt;TokenHolder&gt;,<strong>private val tokenInterceptor</strong>: TokenInterceptor):Authenticator {<br>    <strong>override fun </strong>authenticate(route: Route?, response: Response): Request? {<br><em><br>        </em><strong>if </strong>(response.request().header(<strong>&quot;Authorization&quot;</strong>) != <strong>null </strong>|| !response.request().header(<strong>&quot;Authorization&quot;</strong>).<em>equals</em>(<strong>&quot;Bearer &quot;</strong>+<strong>tokenInterceptor</strong>.<strong>token</strong>)){<br>          //returning null means we have tried and the refresh failed so exit; this will also get you out of infinite loop resulting from retrying<br>            <strong>return null<br>        </strong>}</pre><pre>        //I am using tokenHoler to get the tokenService<br>        <strong>val </strong>tokenService = <strong>tokenHolder</strong>.get().<strong>tokenService<br><br>        var </strong>token = <strong>try </strong>{<br>            <strong>tokenInterceptor</strong>.<strong>token<br>        </strong>} <strong>catch </strong>(e: Exception) {<br><br>        }<br><em><br>        </em><strong>var </strong>body:ReloginResponse?=<strong>null<br>        try </strong>{<br>//The api I am using requires old token to be passed for a new refreshed token</pre><pre>            body = tokenService.relogin(<strong>&quot;Bearer &quot; </strong>+ token).execute()?.body()<br>        }<strong>catch </strong>(e:Exception){<br>           <br>        }<br><br>        <strong>val </strong>newToken = body?.<strong>token<br></strong>        <strong>tokenInterceptor</strong>.<strong>token </strong>= newToken!!<br>        //this is your new token<br>        <strong>return </strong>response.request().newBuilder().header(<strong>&quot;Authorization&quot;</strong>,<strong>&quot;Bearer &quot;</strong>+newToken).build()<br>    }<br><br><br>}</pre><p>TokenAuthenticator will be called automatically whenever there’s a <em>401 Not Authorized </em>response</p><p>And our <em>ProvideOkhttp</em> function will look like this</p><pre>@Provides<br>    @Singleton<br>    <strong>fun </strong>provideOkhttp(tokenInterceptor: TokenInterceptor, tokenAutheticator: TokenAutheticator): OkHttpClient {<em><br>        </em><strong>val </strong>logging = HttpLoggingInterceptor()<br>        logging.setLevel(HttpLoggingInterceptor.Level.<strong>BODY</strong>)<br>        <strong>val </strong>client = OkHttpClient.Builder()<br><br>                .authenticator(tokenAutheticator)<br>                .addInterceptor(logging)<br>                .addInterceptor(tokenInterceptor)<em><br>                </em>.build()<br><br>        <strong>return </strong>client<br>    }</pre><p>This is it. If there is something missing or you have any queries, please comment or find me on <a href="https://twitter.com/theanilpaudel">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8db6121eac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Play InAppBilling, the complete guide]]></title>
            <link>https://medium.com/@theanilpaudel/google-play-inappbilling-the-complete-guide-ef2e751296c4?source=rss-166573ec047------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef2e751296c4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Anil Paudel]]></dc:creator>
            <pubDate>Tue, 15 Aug 2017 11:23:54 GMT</pubDate>
            <atom:updated>2017-08-15T11:27:21.555Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I am trying to include all the necessary steps to implement Google Play InAppBilling in Android. I will try to cover all the parts, from the Google Play Console to the code.</p><p>There is a good tutorial about the implementation of InAppBilling in the app side available <a href="https://developer.android.com/google/play/billing/billing_integrate.html">here</a>.</p><p>Before we start, you need to setup the following things:</p><ol><li><a href="https://play.google.com/apps/publish">Google Play Developer Account</a> requires $25 to open it for lifetime</li><li><a href="https://payments.google.com/">Google Merchant Account</a> which you can also find at Settings and then like shown below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AINVZo5vXQ540Mg--W-yjw.png" /><figcaption>merchant account</figcaption></figure><p>Now, if you have setup those things we are ready to roll.</p><p>For implementing the inapp purchase you need to upload the apk as alpha release with some of the code part. So first, let’s take a dive into the code section. The following steps are the same as in the InAppBilling implementation section.</p><ol><li>Download the InAppBillingService.aidl file from <a href="https://github.com/googlesamples/android-play-billing/tree/master/TrivialDrive">here</a>.</li><li>Create a directory named aidl under src/main.</li><li>Add a new package com.android.vending.billing in this directory.</li><li>Import the aidl file from step 1 to this package in step 3.</li><li>Then in manifest file add this permission</li></ol><blockquote>&lt;uses-permission android:name=”com.android.vending.BILLING” /&gt;</blockquote><p>6. Now we need to create a ServiceConnection like this</p><pre>ServiceConnection <strong>mServiceConn </strong>= <strong>new </strong>ServiceConnection() {<br>        @Override<br>        <strong>public void </strong>onServiceDisconnected(ComponentName name) {<br>            <strong>mService </strong>= <strong>null</strong>;<br>        }<br><br>        @Override<br>        <strong>public void </strong>onServiceConnected(ComponentName name,<br>                                       IBinder service) {<br>            <strong>mService </strong>= IInAppBillingService.Stub.<em>asInterface</em>(service);<br><br>        }<br>    };</pre><blockquote>ServiceConnection is required to establish the connection with the InAppBilling service on Google Play.</blockquote><p>7. Then you need to bind this service in the onCreate() method of your Activity like this</p><pre>@Override <br>public void onCreate(Bundle savedInstanceState) {<br>  super.onCreate(savedInstanceState);<br>  setContentView(R.layout.activity_main);<br>  Intent serviceIntent =<br>      new Intent(&quot;com.android.vending.billing.InAppBillingService.BIND&quot;);<br>  serviceIntent.setPackage(&quot;com.android.vending&quot;);<br>  bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);<br>}</pre><p>8. Then on onDestroy() method you need to unbind this service like this</p><pre>@Override <br>public void onDestroy() { <br>    super.onDestroy(); <br>    if (mService != null) { <br>        unbindService(mServiceConn);<br>    } <br>}</pre><blockquote>If you don’t unbind, the open service connection could cause your device’s performance to degrade.</blockquote><p>Now, we are ready to publish your app for the alpha release. To publish the app, you need to make a release apk by signing it with the release keystore. You can find the details about signing <a href="https://developer.android.com/studio/publish/app-signing.html">here</a>.</p><p>Assuming that you have a release apk, now lets move onto the checklist required to publish your app as alpha release in the Play Store Console.</p><ol><li>512*512 icon</li><li>1024*500 image</li><li>At least 2 screenshots on mobile device</li><li>If you are using dangerous permissions, any of the permission below, then you need to provide a privacy url also</li></ol><pre>READ_CALENDAR<br>WRITE_CALENDAR<br>CAMERA<br>READ_CONTACTS<br>WRITE_CONTACTS<br>GET_ACCOUNTS<br>ACCESS_FINE_LOCATION<br>ACCESS_COARSE_LOCATION<br>RECORD_AUDIO<br>READ_PHONE_STATE<br>CALL_PHONE<br>READ_CALL_LOG<br>WRITE_CALL_LOG<br>ADD_VOICEMAIL<br>USE_SIP<br>PROCESS_OUTGOING_CALLS<br>BODY_SENSORS<br>SEND_SMS<br>RECEIVE_SMS<br>READ_SMS<br>RECEIVE_WAP_PUSH<br>RECEIVE_MMS<br>READ_EXTERNAL_STORAGE<br>WRITE_EXTERNAL_STORAGE</pre><p>If you have all these requirements above, then we are ready to publish the apk.</p><p>If you haven’t already bought the Google Play Developer account then buy it, if you have then go to this <a href="https://play.google.com/apps/publish">url</a>. I will list the steps involved in adding the app as alpha release in steps below.</p><blockquote>Remember, once we complete all the steps below and release the app as alpha, we cannot delete our application, we can unpublish it but we cannot delete it and if we need to publish the same app again we need to change it’s package name.</blockquote><ol><li>Create Application by clicking on the blue Create Application at right side of the console.</li><li>Select the default language and then give the name of your application as the Title and we are now redirected to the Store Listing section</li><li>In store listing section add the title, short description, full description then upload the 2 screenshots or more in the phone section and upload the hi-res icon and feature graphic icon, select the application type and category of your application and then give a url to the privacy policy part if you are using dangerous permission and click on save draft at the right top of the console. For content rating we need to upload to the apk first, so let’s do that.</li><li>Go to App Releases section and click on manage alpha, create release, upload the apk there, the apk must be signed apk, upload the apk there and there should be a green tick and if you press back button you should see a screen as shown at the bottom of these steps.</li><li>Now we to mange the testers, for testing method, I will choose Open Alpha Testing Method, and below will the opt-in url and we can share it to those who we want to become a tester for our app. I will add a screenshot below</li><li>Now to Content Rating, there will be certain sets of questionnaire about the app, appropriately tick them and apply that content rating.</li><li>Then to Pricing and Distribution, select and tick all those that are necessary for your app and save draft, there it will show what are the missing requirements for your app, if it shows any, fulfill them and publish your application. It might take certain hours for your app to get published.</li></ol><p>Screenshots for steps 4 and 5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmXP7U7ScJ3CxI1h_qMAQA.png" /><figcaption>Open Alpha Testing</figcaption></figure><p>Now, finally we will be diving into the real inapp purchase part.</p><p>First we have to add a product that our customers/users can buy, for that Goto Store Presence&gt;InAppProducts&gt;Add New Products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUrEB6sSkK3YlYEFWYsWNQ.png" /><figcaption>Adding new inapp product</figcaption></figure><p>There are two types of Product we can add on Google Play.</p><ol><li>Managed Product :</li></ol><blockquote>Managed in-app products are items that have their ownership information tracked and managed by Google Play. When a user purchases a managed in-app item, Google Play stores the purchase information for each item on a per-user basis. This enables you to later query Google Play at any time to restore the state of the items a specific user has purchased. This information is persistent on the Google Play servers even if the user uninstalls the application or if they change devices.</blockquote><blockquote>If you are using the In-app Billing API, you can also consume managed items within your application. You would typically implement consumption for items that can be purchased multiple times (such as in-game currency, fuel, or magic spells). Once purchased, a managed item cannot be purchased again until you consume the item, by sending a consumption request to Google Play.</blockquote><p>In a nutshell, managed products are those products which are purchased for one time purpose only and if we are to purchase the same item again, we need to consume it.</p><p>2. Subscription :</p><blockquote>A subscription is a product type offered in In-app Billing that lets you sell content, services, or features to users from inside your app with recurring monthly or annual billing. You can sell subscriptions to almost any type of digital content, from any type of app or game.</blockquote><blockquote>With the In-app Billing API, you can use the same purchase flow for buying subscriptions and retrieving subscription purchase information as with in-app products.</blockquote><blockquote>Unlike in-app products, subscriptions cannot be consumed.</blockquote><p>In a nutshell, subscription products are those products which are purchased for certain time, 7 days, 1 month etc and it will be expired and we need to buy it again, and we don’t need to consume it.</p><p><strong>Remember : We cannot delete the Subscription product once we create it but we can delete and modify a Managed product.</strong></p><p>So, now let’s select Managed Product and the <strong>Product ID</strong> is the <strong>SKU</strong>, which needs to be unique and we will need to specify this ProductID/SKU in the code. Add the title, description and the price for this product and activate it from the top right side corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_jrBCgcdaV8yL0-tqY0aA.png" /><figcaption>Activating a managed product</figcaption></figure><p>Now we are ready to implement the billing part in the app side.</p><p>I am assuming that you have a button or a view and on its onClick() you will be calling the InAppPurchase. We have already added the ServiceConnection class and also bound the InAppVendingBillingService at the beginning of this post. <br>Now, on onClick() of the view, first we need to check if the device supports the billing or not, like this</p><pre><strong>public boolean </strong>isBillingSupported() {<br>    <strong>int </strong>response = 1;<br>    <strong>try </strong>{<br>        response = <strong>mService</strong>.isBillingSupported(3, getPackageName(), <strong>&quot;inapp&quot;</strong>);<br>    } <strong>catch </strong>(RemoteException e) {<br>        e.printStackTrace();<br>    }<br>    <strong>if </strong>(response &gt; 0) {<br>        <strong>return false</strong>;<br>    }<br>    <strong>return true</strong>;<br>}</pre><p>The parameter 3, is the version of InAppBilling, and last one “inapp” is the string type for managed products, for subscription type we should use “subs”.</p><p>Now, I have a method which prompts the Google Play in app billing dialog.</p><pre><strong>private void </strong>purchaseItem(String sku) {<br>    <strong>try </strong>{<br><br>        <strong>if </strong>(isBillingSupported()) {<br><br>            Bundle buyIntentBundle = <strong>mService</strong>.getBuyIntent(3, getPackageName(),<br>                    sku, <strong>&quot;inapp&quot;</strong>, <strong>&quot;developer_payload&quot;</strong>);<br>            <br>            PendingIntent pendingIntent = buyIntentBundle.getParcelable(<strong>&quot;BUY_INTENT&quot;</strong>);<br><br>            <strong>try </strong>{<br>                startIntentSenderForResult(pendingIntent.getIntentSender(),<br>                        1001, <strong>new </strong>Intent(), Integer.<em>valueOf</em>(0), Integer.<em>valueOf</em>(0),<br>                        Integer.<em>valueOf</em>(0));<br>            } <strong>catch </strong>(IntentSender.SendIntentException e) {<br>                e.printStackTrace();<br>            }<br>        } <strong>else </strong>{<br>            alert(<strong>&quot;Billing is not supported&quot;</strong>);<br>        }<br>    } <strong>catch </strong>(RemoteException e) {<br>        e.printStackTrace();<br>    }<br>}</pre><p>The parameter, sku is the ProductID we have created in the Google Play Console, tv_show_55, in the screenshot above.</p><blockquote>The developer_payload String is used to specify any additional arguments that you want Google Play to send back along with the purchase information. Don’t use the developer_payload field for security validation purposes. This field isn&#39;t always available when completing tasks related to In-app Billing.</blockquote><blockquote>If you run the app, at this time, you will see the Google Play Billing dialog. There might be some error like, authentication or product not found for that the gmail account in the device you are testing needs to be a Tester by clicking Become a Tester in the opt in url.</blockquote><p>For testing purpose, we can use this as SKU <strong>android.test.purchased</strong> and if we run the app we will see a dialog like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*Ctx8p9M5QWMiNAqk.png" /><figcaption>Dialog when test sku is used</figcaption></figure><p>Now if we click the same item, the app will crash, to solve this hit this code in the terminal, the crash is because we need to consume a managed product</p><pre>adb shell pm clear com.android.vending</pre><p>startIntentSenderForResult will call the onActivityForResult() method of our Activity.</p><p>onActivityForResult will be like this</p><pre>@Override<br>    <strong>public void </strong>onActivityResult(<strong>int </strong>requestCode, <strong>int </strong>resultCode, Intent data) {<br>         <strong>if </strong>(requestCode == 1001) {<br>            <strong>int </strong>responseCode = data.getIntExtra(<strong>&quot;RESPONSE_CODE&quot;</strong>, 0);<br>            String purchaseData = data.getStringExtra(<strong>&quot;INAPP_PURCHASE_DATA&quot;</strong>);<br>            String dataSignature = data.getStringExtra(<strong>&quot;INAPP_DATA_SIGNATURE&quot;</strong>);<br>            <strong>if </strong>(resultCode == <strong><em>RESULT_OK</em></strong>) {<br>                <strong>try </strong>{<br>                    JSONObject jo = <strong>new </strong>JSONObject(purchaseData);<br>                    String sku = jo.getString(<strong>&quot;productId&quot;</strong>);<br>                    String purchaseToken = jo.getString(<strong>&quot;purchaseToken&quot;</strong>);<em><br>                    </em>alert(<strong>&quot;You have bought the &quot; </strong>+ sku + <strong>&quot;. Congratulations!&quot;</strong>);<br>                    consumeItem(purchaseToken);<br>                } <strong>catch </strong>(Exception e) {<br>                    alert(<strong>&quot;Failed to parse purchase data.&quot;</strong>);<br>                    e.printStackTrace();<br>                }<br>            }<br>        }<br>    }</pre><p>The value of jo JsonObject will be like this</p><pre><em>{&quot;packageName&quot;:&quot;com.packagename&quot;,&quot;orderId&quot;:&quot;transactionId.android.test.purchased&quot;,<br> &quot;productId&quot;:&quot;android.test.purchased&quot;,&quot;developerPayload&quot;:&quot;developer_payload&quot;,<br> &quot;purchaseTime&quot;:0,&quot;purchaseState&quot;:0,&quot;purchaseToken&quot;:&quot;inapp:com.packagename:android.test.purchased&quot;}</em></pre><p>This way, we purchase an item from the Google Play.</p><p>Now, if the product is Managed Product, we need to consume it, otherwise the app will crash. I have a method to consume a product like this</p><pre><strong>private void </strong>consumeItem(String purchaseToken) {<br>    <strong>int </strong>response = 0;<br>    <strong>try </strong>{<br>        response = <strong>mService</strong>.consumePurchase(3, getPackageName(), purchaseToken);<br>    } <strong>catch </strong>(RemoteException e) {<br>        e.printStackTrace();<br>    }<br>    Observable&lt;Integer&gt; consumeObs = Observable.<em>just</em>(response);<br>    consumeObs.subscribeOn(Schedulers.<em>io</em>()).observeOn(AndroidSchedulers.<em>mainThread</em>()).unsubscribeOn(Schedulers.<em>io</em>())<br>            .subscribe(<strong>new </strong>Observer&lt;Integer&gt;() {<br>                @Override<br>                <strong>public void </strong>onSubscribe(Disposable d) {<br><br>                }<br><br>                @Override<br>                <strong>public void </strong>onNext(Integer value) {<br>                    Timber.<em>d</em>(<strong>&quot;value of string in consume %s&quot;</strong>,value);<br><br>                }<br><br>                @Override<br>                <strong>public void </strong>onError(Throwable e) {<br>                    e.printStackTrace();<br>                }<br><br>                @Override<br>                <strong>public void </strong>onComplete() {<br><br>                }<br>            });<br><br>}</pre><p>The code part below is a network call so we need to run it asynchronously</p><pre>response = <strong>mService</strong>.consumePurchase(3, getPackageName(), purchaseToken);</pre><p>I have used RxJava for this purpose, if you find it difficult you can use AsyncTask also, by adding the above code snippet in the doInBackground() and returning the integer in the onPostExecute().</p><p>I am consuming the managed product as soon the customer/user buys it.</p><p>So, this is it, this is the complete tutorial on how to implement the Google Play InApp billing. If I had made some mistakes or misunderstood something, please comment. If you have any queries you can find me on <a href="https://twitter.com/theanilpaudel">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef2e751296c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programmers don’t delete, they #comment]]></title>
            <link>https://medium.com/@theanilpaudel/programmers-dont-delete-they-comment-29aae75ff2ff?source=rss-166573ec047------2</link>
            <guid isPermaLink="false">https://medium.com/p/29aae75ff2ff</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programmer]]></category>
            <dc:creator><![CDATA[Anil Paudel]]></dc:creator>
            <pubDate>Thu, 28 Apr 2016 17:41:41 GMT</pubDate>
            <atom:updated>2016-04-28T17:41:41.033Z</atom:updated>
            <content:encoded><![CDATA[<p>A little bit of background first. I’m an Android Developer working in an IT company in Nepal.</p><p>We were working on a project with some tight deadline and so we had to up our game to finish the project on time. The project was supposed to consist of 4 main modules, in the initial requirements and we were working very hard, literally, no Facebook, no Youtube in spare time. In fact, there was no spare time and after 10 days or so, we finally came up with a prototype and showed it to the client. By now you have already guessed what happened.</p><p>The client didn’t want 2 of the main modules instead they already had another company made a separate app for those 2 modules and asked us to replace those 2 modules with other modules. They also said that there might be a possibility in the future that we might need those 2 modules too, so, um, you know.</p><p>So it is at this time that strike me, Programmers don’t delete, they /*comment*/ to be precise. There is always the fear that we might need this code in the near future and either we are too lazy to write it again or we are too lazy to search it over Stackoverflow and incidents like this help those fear to prevail on our mind and the project looking messed up and lots of boilerplate code are just the perks. And to be honest, as a programmer we can’t help it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29aae75ff2ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>