Search code examples
phpvk

Calculating signature for vkontakte.ru iframe app


Why does this short PHP script:

<?php

$args = array(
        'api_id'    => $_GET['api_id'],
        'method'    => 'getProfiles',
        'sid'       => $_GET['sid'],
        'uids'      => $_GET['viewer_id'],
        'v'         => '3.0',
);

$req = $_GET['api_url'] . '?sig=' . 
    calc_sig($_GET['viewer_id'], $args, $_GET['secret']);

foreach ($args as $key => $val)
        $req .= "&$key=$val";

$page = file_get_contents($req);

header('Content-Type: text/plain');
print_r($_GET);
print("\n\n req: " . $req);
print("\n\n page: " . $page);

function calc_sig($viewer_id, $arr, $secret) {
        $kv = array();
        foreach ($arr as $key => $val) {
                if ($key != 'sid')
                        $kv[] = "$key=$val";
        }
        sort($kv);

        $str = $viewer_id . join('', $kv) . $secret;
        print("\n\n str: " . $str);
        return md5($str);
}
?>

print the error:

str: 59751265api_id=1762950method=getProfilesuids=59751265v=3.0a551fa3416
req: http://api.vkontakte.ru/api.php?sig=490142d9c3eb65ee64045a2ea754266c&api_id=1762950&method=getProfiles&sid=1bc83d2ed0db52b8ad45d8ddf36780f52944d5f6340ffa47ad5fef9594&uids=59751265&v=3.0
page: <?xml version="1.0" encoding="utf-8"?>
<error>
 <error_code>4</error_code>
 <error_msg>Incorrect signature</error_msg>
......

?>

I keep reading the doc again and again...


Solution

  • Ok, this works:

    <?php
    
    define('VK_API_ID_TEST', 'XXX');
    define('VK_AUTH_SECRET_TEST', 'YYY');
    
    $args = array(
            'api_id'    => $_GET['api_id'],
            'format'    => 'json',
            'method'    => 'getProfiles',
            'uids'      => $_GET['viewer_id'],
            'v'         => '3.0',
    );
    
    $req = $_GET['api_url'] . '?sig=' . calc_sig($args);
    foreach ($args as $key => $val)
            $req .= "&$key=$val";
    
    $page = file_get_contents($req);
    $data = json_decode($page, true);
    
    header('Content-Type: text/plain');
    print("\n\n _GET:");
    print_r($_GET);
    print("\n\n req: " . $req);
    print("\n\n page: " . $page);
    print("\n\n data:");
    print_r($data);
    print("\n\n city: " . $data['response'][0]['name']);
    
    function calc_sig($arr) {
            $kv = array();
            foreach ($arr as $key => $val) {
                    if ($key != 'sig')
                            $kv[] = "$key=$val";
            }
            sort($kv);
    
            $str = join('', $kv) . VK_AUTH_SECRET_TEST;
            print("\n\n str: " . $str);
            return md5($str);
    }
    
    ?>