若電子商務要吃中國的市場, 銜接微信API已經是家常便飯
微信API也有分三種類型
要選擇哪一種API也要看自己的電商平台的需求
本篇介紹的是使用微信開放平台API進行QR Code登入
微信API介紹
公眾平台: App需要自動回覆訊息, 自行開發手機App要串接微信, 訂閱服務, 獲取用戶地理位置等等
開放平台: 統一登入, 獲取用戶資訊等等
微信支付: 商戶平台金流支付, 訂單資料
微信開放平台 申請API步驟
使用手機開微信App, 並使用微信掃瞄QR Code功能, 掃描自行開發網站使用微信API產生的QR Code進行網站登入與註冊
微信開放平台 官方API說明
- 微信開放平台 > 管理中心 > 網站應用 > 創建網站應用 ( 一個微信帳號只能申請10個網站 )
- 我們會使用到的參數為「AppID」,「AppSecret」,「授權回調域」
- 使用微信API套用至自行開發網站
API取得使用者登入資訊 開發步驟
- 取得 Code
https://open.weixin.qq.com/connect/qrconnect?appid=AppID&redirect_uri=授權回調域底下的串接網站&response_type=code&scope=snsapi_login&state=隨機數#wechat_redirect - 使用 Code 取得 access_token
https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppID&secret=AppSecret&code=第一步驟取得的Code&grant_type=authorization_code - 使用 access_token 取得 使用者個人資訊
https://api.weixin.qq.com/sns/userinfo?access_token=第二步驟取得的Access_token&openid=OPENID
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> </head> <body> <span id="login_qrcode"></span> <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script> <script> /** * 使用微信開放平台API產生QR Code * 手機掃描後自動導頁至 redirect_uri + ?code=&state= */ var obj = new WxLogin({ id:"login_qrcode", appid: "自己申請的appid", scope: "snsapi_login", redirect_uri: encodeURIComponent("http://自己申請的授權回調域的站台/Login.php"), state: Math.ceil(Math.random()*1000), style: "black", href: "" }); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> </head> <body> <style> body{ font-size: 30px; } </style> <h3>1. 掃描後取得的Code</h3> <p><b id="code"></b></p> <hr> <h3>2. 使用 Code 取得 access_token</h3> <p><a href="" target="_block" id="access_token">取得access_token</a></p> <hr> <h3>3. 使用 access_token 取得 使用者個人資訊</h3> Access_token: <input type="text" id="txtAccess_token" ><br> <p><a href="" target="_block" id="userInfo">取得使用者個人資訊</a></p> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(function() { var url = new URL( window.location.href ); $("#code").html( url.searchParams.get("code") ); $("#access_token").attr("href", "https://api.weixin.qq.com/sns/oauth2/access_token?appid=自己申請的appid&secret=自己申請的secret&code=" + url.searchParams.get("code") + "&grant_type=authorization_code"); $("#txtAccess_token").on("change", function(){ $("#userInfo").attr("href", "https://api.weixin.qq.com/sns/userinfo?access_token=" + $("#txtAccess_token").val() + "&openid=OPENID"); }); }); </script> </body> </html>
note: 使用者個人資料包含: openid (唯一Key), 用戶暱稱, 性別, 省份, 城市, 國家, 用戶頭像, 用戶特權信息, unionid
API請求限制
- 使用 Code 取得 access_token: 1萬次/分鐘
- 使用 access_token 取得 使用者個人資訊: 5萬次/分鐘
開發本地端測試
- 必須將本地開發端「127.0.0.1」設定為開放平台授權回調域「設定的網域」
- 設定路徑「C:\Windows\System32\drivers\etc\hosts」
- hosts檔案加一行「127.0.0.1 設定的網域」
- 即可直接在本地端直連「設定的網域」測試微信API
掃描後如果發生錯誤, 會顯示Scope參數錯誤或沒有權限 (如下圖)
如果成功則會直接進入自己開發的頁面