介紹建立 API 的方法 – 2 前台會員權限

繼上一篇介紹了訪客權限後
這次繼續介紹如何建立 API – 前台會員權限
權限為 需有 前台登入權限 才能存取
取得 token
(每次取得的 token 皆不同)
url : http://{domain_name}/index.php/rest/V1/integration/customer/token
- get token by postman


注意: 若要用 curl 取得 token 須確定 domain_name 可由server 端連上
- get token by crul
<?php
$url = 'http://{domain_name}/index.php/rest/V1/integration/customer/token';
$data = array(
'username' => '[email protected]',
'password' => 'Password123'
);
$CURLOPT_HTTPHEADER = array('Content-Type: application/json' );
$data = json_encode($data);
$s = curl_init();
curl_setopt($s,CURLOPT_URL,$url);
curl_setopt($s, CURLOPT_HTTPHEADER, $CURLOPT_HTTPHEADER);
curl_setopt($s, CURLOPT_POST, 1);
curl_setopt($s, CURLOPT_POSTFIELDS, $data);
curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($s);
curl_close($s);
print_r( $contents );
帶入 token 取得會員資料
url : http://{domain_name}/index.php/rest/V1/customers/me
- get data by postman

- get data by curl
<?php
$url = 'http://{domain_name}/index.php/rest/V1/customers/me';
$token = 'e0ex8ivttqnrlkonmppij1ycq8fhou6x';
$CURLOPT_HTTPHEADER = array('Content-Type: application/json',
                                                           'Authorization: Bearer '.$token);
$s = curl_init();
curl_setopt($s,CURLOPT_URL,$url);
curl_setopt($s, CURLOPT_HTTPHEADER, $CURLOPT_HTTPHEADER);
curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($s);
curl_close($s);
print_r( $contents );
自訂的 API 程式
將 \Astralweb\Tech\etc\webapi.xml
修改為
<?xml version="1.0"?> <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd"> <route url="/V1/hello/name/:name" method="GET"> <service class="Astralweb\Tech\Api\HelloInterface" method="name"/> <resources> <resource ref="self"/> </resources> </route> </routes>
此時一般的連線就連不上了
需帶 token 才能正常連上
下一篇將再繼續介紹不同權限的API建立方法 – 後台管理者權限,請鎖定收看喔!
或想了解其他關於Magento的訊息,可追蹤我們的文章,甚至關注我們的Facebook的粉絲專頁,我們會不定期新增文章跟大家分享!
 
	 
			 
			 
			 
			 
			 
			
我要留言