How to generate oauth signature when post json body in php?

dm
oauth
directmessages
php

#1

I’m tryng send message to Twitter user, I have access to Direct Messages feature, can’t send post request with json body.

Here is Twitter api link https://api.twitter.com/1.1/direct_messages/events/new.json
Could u please show curl examples or give some tips?

Here is my code:

<?php
    $twitter_consumer_key = '';
    $twitter_consumer_secret = '';
    $twitter_access_token = '';
    $twitter_access_token_secret = '';
    $twitter_version = '1.0';
    $sign_method = 'HMAC-SHA1';

    $post = '{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"123"},"message_data":{"text":"Hello world"}}}}';

    $url = 'https://api.twitter.com/1.1/direct_messages/events/new.json';
    $param_string = 'oauth_consumer_key=' . $twitter_consumer_key .
        '&oauth_nonce=' . time() .
        '&oauth_signature_method=' . $sign_method .
        '&oauth_timestamp=' . time() .
        '&oauth_token=' . $twitter_access_token .
        '&oauth_version=' . $twitter_version;

    //Generate a signature base string for POST
    $base_string = 'POST&' . rawurlencode($url) . '&' . rawurlencode($param_string);
    $sign_key = rawurlencode($twitter_consumer_secret) . '&' . rawurlencode($twitter_access_token_secret);

    //Generate a unique signature
    $signature = base64_encode(hash_hmac('sha1', $base_string, $sign_key, true));
    $curl_header = 'OAuth oauth_consumer_key=' . rawurlencode($twitter_consumer_key) . ',' .
      'oauth_nonce=' . rawurlencode(time()) . ',' .
      'oauth_signature=' . rawurlencode($signature) . ',' .
      'oauth_signature_method=' . $sign_method . ',' .
      'oauth_timestamp=' . rawurlencode(time()) . ',' .
      'oauth_token=' . rawurlencode($twitter_access_token) . ',' .         'oauth_version=' . $twitter_version;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $curl_header, 'content-type: application/json'));
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, rawurlencode($post));
    $request = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    print_r($request);
    print_r($httpcode);

#2

I suggest using this simple code : https://github.com/J7mbo/twitter-api-php
Or read it. I think you will get the answer from it.