poorX

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

https://open.work.weixin.qq.com/api/doc#90000/90135/90236

 

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use Encode qw(encode_utf8);
use JSON::MaybeXS qw(encode_json decode_json);
use LWP::UserAgent;
use HTTP::Request ();
use HTTP::Response;
use HTTP::Request::Common;

my $tokenurl    = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?';
my $sendurl     = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?';
my $corpid      = '';
my $corpsecret  = '';
my $agentid     =;

sub get_response($) {
  my $req = shift;

  my $ua  = LWP::UserAgent->new(timeout=>10);
  my $res = $ua->request($req);
  # $res->decoded_content / $res->content
  if ( $res->is_success ) {
    my $res_data = decode_json($res->content);
    return (1, $res_data);
  }
  else {
    return (0, $res->status_line);
  }
}

sub get_token {
  my $token_url = $tokenurl . 'corpid=' .$corpid . '&corpsecret=' . $corpsecret;
  my $req = HTTP::Request->new('GET', $token_url);

  my ($r, $res_data) = get_response($req);
  if ( $r ) {
    return ($r, $res_data->{access_token});
  }
  else {
    return ($r, $res_data);
  }

}

sub send_data($$$) {
  my ($token, $user, $content) = @_;
  my $send_url = $sendurl . 'access_token=' . $token;
  my $send_data = {
    'touser'  => $user,
    'msgtype' => 'text',
    'agentid' => $agentid,
    'text'    => {'content' => $content},
    'safe'    => '0'
  };
  my $json = encode_utf8(encode_json($send_data));
  my $req = HTTP::Request->new('POST', $send_url);
  $req->content($json);

  my ($r, $res_data) = get_response($req);
  if ( $r ) {
    return ($r, $res_data->{errmsg});
  }
  else {
    return ($r, $res_data);
  }

}

my ($r, $send_token) = get_token();
print send_data($send_token, 'username', 'hello world');

 

posted on 2019-04-25 14:35  poorX  阅读(354)  评论(0编辑  收藏  举报