京东联盟API的使用

By | 2016年10月4日

之前利用京东联盟API制作了一个推广链接查询工具(http://devonios.com/app/jd/),好多童鞋前来询问细节,在此把相关代码附上说明。

首先是要获取Token令牌数据,由于token存在有效期,所以不用每次都去请求获取token。

一、获取token,保存到本地文件中:token.php

<?php
session_start();
//common.php文件包含一些常用function
include("../lib/common.php");
$response_type = "code";
$grant_type = "authorization_code";
$client_id = "修改为自己的";
$client_secret = "修改为自己的";
$redirect_uri = "修改为当前token.php文件的完整http链接";
$state = "jdunion";
$codeurl = 'https://oauth.jd.com/oauth/authorize';
$tokenurl = "https://oauth.jd.com/oauth/token?";

$code = $_GET["code"];

if ($code != "")
{
	$fields = [
	  "grant_type" => urlencode($grant_type),
	  "client_id" => urlencode($client_id),
	  "redirect_uri" => urlencode($redirect_uri),
	  "code" => urlencode($code),
	  "state" => urlencode($state),
	  "client_secret" => urlencode($client_secret)
	];

	$fields_string = "";
	foreach($fields as $key=>$value) {
	 $fields_string .= $key.'='.$value.'&';
	}
	//$fields_string = rtrim($fields_string, '&');

	//send_get是发送get请求的function,在common.php文件中
	$result = send_get($tokenurl.$fields_string);
	
	//这里要把返回结果转换为utf-8,因为结果有用户昵称,如果是中文的就无法解析出token了
	$result = mb_convert_encoding($result,"UTF-8","GBK");
	
	$resuttjson = json_decode($result);

	//3种处理方式:
	
	//     1)直接输出结果
	// echo $resuttjson->{'access_token'};
	// exit();
	
	//     2)保存到session中
	//$_SESSION["jdtoken"] = $resuttjson->{'access_token'};
	//$_SESSION["jduid"] = $resuttjson->{'uid'};
	//$_SESSION["jdusernick"] = $resuttjson->{'user_nick'};
	
	//     3)token值写入本地文件中
	$file = fopen("token.txt", "w");
	fwrite($file, $resuttjson->{'access_token'});
	fclose($file);
	
	header("Location: index.php");
}
else
{
  header("Location: ".$codeurl."?response_type=".$response_type."&client_id=".$client_id."&redirect_uri=".$redirect_uri."&state=".$state);
}

二、有了token值就可以获取推广链接和商品信息了

<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
session_start();
define("APPKEY","修改为自己的");
define("APPSECRET","修改为自己的");
define("UNIONID","修改为自己的");
define("WEBID","修改为自己的");
define("SERVER","https://api.jd.com/routerjson");

//需要引入京东联盟api文件
require "./api/jd-jos/JdSdk.php";
//fucntion文件,见后面
include "common.php";

header("Content/Type: application/json");
$action = $_GET["action"];

//读取本地保存的token文件
$myfile = fopen("token.txt", "r");
$token = fread($myfile,filesize("token.txt"));
fclose($myfile);

$result = [];

//////////////////////////////////////////////查询推广链接
if(strstr($action,"link")){
	$url = $_GET["url"];
	$iswap = $_GET["iswap"];
	//GetLink是common.php文件的一个function
	$link = GetLink($token,$url,$iswap);
	if($link["resultCode"] == "0"){
		$result["link_ok"] = "1";
		$result["url"] = $link["url"];
	}else{
		$result["link_ok"] = "0";
		$result["link_errinfo"] =  $link["resultMessage"];
	}
}

//////////////////////////////////////////////查询商品信息
if(strstr($action,"info")){
	$url = $_GET["url"];
	$pid = "";
	
	if(strstr($url,"item.m.jd.com")){
		//wap链接
		$pid = GetBetween($url,"product/",".html");
	}else{
		//pc链接
		$pid = GetBetween($url,"com/",".html");
	}
	//GetProductInfo是common.php文件中的一个function
	$pinfo = GetProductInfo($token,$pid);
	
	if($pinfo["result"]){
		$result["info_ok"] = "1";
		
		$goodname = $pinfo["result"][0]["goodsName"];
		$unitPrice = $pinfo["result"][0]["unitPrice"];
		$wlunitPrice = $pinfo["result"][0]["wlUnitPrice"];
		$commisionRatioPc = $pinfo["result"][0]["commisionRatioPc"];
		$commisionRatioWl = $pinfo["result"][0]["commisionRatioWl"];
		$skuId = $pinfo["result"][0]["skuId"];
		$shopId = $pinfo["result"][0]["shopId"];
		$materialUrl = $pinfo["result"][0]["materialUrl"];
		$imgurl = $pinfo["result"][0]["imgUrl"];
		
		$result["imgurl"] = $imgurl;
		$result["pname"] = $goodname;
		$result["pid"] = $skuId;
		$result["price"] = $unitPrice;
		$result["wlprice"] = $wlunitPrice;
		
		$result["purl"] = $materialUrl;
		$result["ratePC"] = $commisionRatioPc;
		$result["rateWL"] = $commisionRatioWl;
		$result["shopType"] = ($shopId=="0"?"京东自营":"京东商家");
	}else{
		$result["info_ok"] = "0";
		$result["info_errinfo"] = "没有找到ID为 $pid 的产品信息!";
	}
	
}

echo json_encode($result,JSON_UNESCAPED_UNICODE);
?>

common.php文件的内容如下:

<?php
function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

function client($token){
	$c = new JdClient();
	$c->appKey = APPKEY;
	$c->appSecret = APPSECRET;
	$c->accessToken =$token;
	$c->serverUrl = SERVER;
	return $c;
}

function GetLink($token,$url,$iswap){

	$req = new ServicePromotionGetcodeRequest();
	$req->setPromotionType( 7 );
	$req->setMaterialId($url); 
	$req->setWebId(WEBID); 
	$req->setUnionId(UNIONID); 
	$req->setChannel($iswap==1?"WL":"PC"); 
	

	$client = client($token);
	$resp = $client->execute($req, $client->accessToken);
	$result = $resp->{"queryjs_result"};
	
	return  json_decode($result,true);
}

function GetProductInfo($token,$pid){

	$req = new ServicePromotionGoodsInfoRequest();
	$req->setSkuIds($pid);
	
	$client = client($token);
	$resp = $client->execute($req, $client->accessToken);
	$result = $resp->{"getpromotioninfo_result"};

	return json_decode($result,true);
}

?>

后台程序完成了,最后输出的是json内容,剩下的就是前台的显示了,可以自行查看页面源码。

附上本文用的SDK文件,由于现在改版了,这个旧版文件放在备份,需要的同学可以下载使用~

下载:jd-jos