首页> 实战笔录 >PHP开发笔记 >PHP PHP

php调用阿里云实时汇率查询换算接口代码分享

作者:小萝卜吖 2019-09-16 浏览 5316

简介php调用阿里云实时汇率查询换算接口代码分享,第一步:去阿里云上面购买服务,第二部:购买服务之后获取appcode,这个接口api调用又两种方法1.API 身份认证调用方法(APPCODE)2.API 签名认证调用方法(AppKey & AppSecret),我们用的第一种。

php调用阿里云实时汇率查询换算接口代码分享

第一步:去阿里云上面购买服务

第二部:购买服务之后获取appcode,这个接口api调用又两种方法
              1.API 身份认证调用方法(APPCODE)
              2.API 签名认证调用方法(AppKey & AppSecret)
              我们用的第一种。

第三部:实现实时汇率转换

废话不多说,直接上代码:

<?php

class Commons {

	  public function __construct(){
		    parent::__construct();
	  }
      
      //设置一个方法获取汇率
      public function ali_rate($from,$to){
        $from = 'JPY';
        $to = 'BHD';
        $host = "http://exchange.market.alicloudapi.com";
        $path = "/exchange/currency";
        $method = "POST";
        $appcode = "你的appcode(购买服务之后会获取到)";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "from={$from}&to={$to}";
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $data = curl_exec($curl);
         
        $data = json_decode($data,true);
        
        curl_close($curl);
        //var_dump(json_decode($data,true));die;
        
        return $data;
    }
  
}


根据上面定义好的类,调用获取汇率方法:

//调用接口
$rate = new Commons();
$res = $rate->ali_rate('JPY','BHD');//这里的$from是当前货币(简称)如CNY  $to是目标汇率 如USD

打印结果:var_dump($res)
{
  "message": "查询成功",
  "result": [
    {
      "currencyF": "JPY",
      "currencyF_Name": "日元",
      "currencyT": "BHD",
      "currencyT_Name": "巴林第纳尔",
      "currencyFD": 1,
      "exchange": "0.0032685972",
      "result": "0.0032",
      "updateTime": "2014-11-07 13:58:02"
    },
    {
      "currencyF": "BHD",
      "currencyF_Name": "巴林第纳尔",
      "currencyT": "JPY",
      "currencyT_Name": "日元",
      "currencyFD": 1,
      "exchange": "305.9416445623",
      "result": 305.9416,
      "updateTime": "2014-11-07 13:58:01"
    }
  ],
  "status": "000000"
}
 

阿里云接口示例地址:https://market.aliyun.com/products/56928004/cmapi027048.html#sku=yuncode2104800003

很赞哦! (0)

文章评论

    高端网站建设