Perl获取微信小程序二维码

微信小程序API:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html

# 参数 $path即页面路径,比如:"pages/index?query=1"

sub get_wxa_code {

    my ($fid, $path) = @_;

    my $ret = get_access_token();  #获取access_token

    my $image_fid = "";

    my $json = JSON->new();

    if (length($ret->{access_token})) {

        my $post_data;

        $post_data->{path} = $path;

        #$post_data->{width} = 430;

        #$post_data->{auth_color} = 1;

        #$post_data->{line_color} = {"r"=>"0","g"=>"0","b"=>"0"};

        my $param_json_str =$json->encode($post_data);

        my $header = HTTP::Headers->new( Content_Type => 'application/json; charset=utf8', );

        my $http_request = HTTP::Request->new( POST => "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$ret->{access_token}, $header, $param_json_str );

        my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0x00 });

        $ua->timeout(3);

        my $response = $ua->request($http_request);

        if ($response->message ne "OK" && $response->is_success ne "1") { #出错,或者timeout了

                return "timeout";

        } else { # 如果成功,则返回的是图片对应的二进制内容,这里直接写到文件保存

                my $file = "/var/www/wechat/files/".$fid;   #目录要有读写权限

                open(LOCAL, ">$file");

                binmode(LOCAL); #内容为二进制格式

                print LOCAL $response->content();

                close LOCAL;

                if (-s $file ) { #判断是否写成功

                        $image_fid = $fid;

                } else {

                        return "write file failed";

                }

        }

    } else {

        return "get access_token failed";

    }

    return $image_fid;

}

猜你喜欢

转载自lzqustc.iteye.com/blog/2396586