WeChat payment Development (7) shipping address sharing interface V2, v2

Source: Internet
Author: User
Tags sha1 encryption

Payment Development (7) shipping address sharing interface V2, v2

Keywords: public platform JSSDK send to a friend Receiving address sharing interface openAddress
Author: Fang Times studio
Original article: http://www.cnblogs.com/txw1958/p/weixin-openaddress.html

 

In this public platform development tutorial, we will introduce how to obtain the shipping address on the webpage.

The shipping address sharing interface was upgraded in December April 13, 2016, and only new interfaces can be used in December May 20, 2016. This tutorial is a new interface tutorial!

This article consists of the following two parts:

 

 

1. JS-SDK1. Get Access Token

Access token acquisition method is described earlier. For details, see public platform development (26) ACCESS TOKEN

2. Get jsapi_ticket

Before generating a signature, you must first understand jsapi_ticket. jsapi_ticket is a temporary ticket used by the public account to call the JS interface. Under normal circumstances, jsapi_ticket is valid for 7200 seconds and obtained through access_token. Because jsapi_ticket has a limited number of api calls, refreshing jsapi_ticket frequently limits api calls and affects your business. Developers must cache jsapi_ticket globally in their own services.

Refer to the following document to obtain access_token (valid for 7200 seconds, the developer must cache access_token in the global cache of his/her service ):
Use the access_token obtained in the first step to request jsapi_ticket through http GET (valid for 7200 seconds, developers must cache jsapi_ticket globally in their own services). The interface address is as follows:

https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

The following JSON is returned:

{    "errcode":0,    "errmsg":"ok",    "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",    "expires_in":7200}

After obtaining jsapi_ticket, you can generate a signature for JS-SDK permission verification.

3. Signature Algorithm Implementation

The signature generation rules are as follows: the fields involved in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (URL of the current webpage, does not contain # And the following parts ). After all parameters to be signed are sorted in ascending order (lexicographically) according to the field name ASCII code, the format of the URL key-value pair is used (that is, key1 = value1 & key2 = value2 ...) Concatenate the string into string1. Note that all parameter names are lowercase characters. Perform sha1 encryption on string1, and use original values for field names and field values without URL escaping.

Signature = sha1 (string1 ). Example:

noncestr=Wm3WZYTPz0wzccnWjsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qgtimestamp=1414587457url=http://mp.weixin.qq.com?params=value

Step 1. Sort all parameters to be signed in ascending order of the ASCII code of Field Names (lexicographically), and then use the format of the URL key-Value Pair (that is, key1 = value1 & key2 = value2 ...) Concatenate the string into string1:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value

Step 2. Sign string1 sha1 to obtain signature:

0f9de62fce790f9a083d5c99e95740ceb90c27ed

The complete code is as follows:

<? Phpclass JSSDK {private $ appId; private $ appSecret; public function _ construct ($ appId, $ appSecret) {$ this-> appId = $ appId; $ this-> appSecret = $ appSecret;} public function getSignPackage () {$ jsapiTicket = $ this-> getJsApiTicket (); // note that the URL must be dynamically obtained and cannot be hardcode. $ protocol = (! Empty ($ _ SERVER ['https']) & $ _ SERVER ['https']! = 'Off' | $ _ SERVER ['server _ port'] = 443 )? "Https: //": "http: //"; $ url = "$ protocol $ _ SERVER [HTTP_HOST] $ _ SERVER [REQUEST_URI]"; $ timestamp = time (); $ nonceStr = $ this-> createNonceStr (); // The Order of parameters here should be sorted by the key value ASCII code in ascending order $ string = "jsapi_ticket = $ jsapiTicket & noncestr = $ nonceStr & timestamp = $ timestamp & url = $ url "; $ signature = sha1 ($ string); $ signPackage = array ("appId" => $ this-> appId, "nonceStr" => $ nonceStr, "timestamp" => $ timestamp, "url" => $ u Rl, "signature" => $ signature, "rawString" => $ string); return $ signPackage;} private function createNonceStr ($ length = 16) {$ chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $ str = ""; for ($ I = 0; $ I <$ length; $ I ++) {$. str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} private function getJsApiTicket () {// jsapi_ticket should be stored and updated globally. The following code is written to the file for display. Example $ data = json_decode (file_get_contents ("jsapi_ticket.json"); if ($ data-> expire_time <time () {$ accessToken = $ this-> getAccessToken (); // get ticket with the following URL for the enterprise ID // $ url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket? Access_token = $ accessToken "; $ url =" https://api.weixin.qq.com/cgi-bin/ticket/getticket? Type = jsapi & access_token = $ accessToken "; $ res = json_decode ($ this-> httpGet ($ url); $ ticket = $ res-> ticket; if ($ ticket) {$ data-> expire_time = time () + 7000; $ data-> jsapi_ticket = $ ticket; $ fp = fopen ("jsapi_ticket.json", "w "); fwrite ($ fp, json_encode ($ data); fclose ($ fp) ;}} else {$ ticket = $ data-> jsapi_ticket;} return $ ticket ;} private function getAccessToken () {// access_token should be stored and updated globally. The following code uses Example $ data = json_decode (file_get_contents ("access_token.json"); if ($ data-> expire_time <time ()) {// get access_token with the following URL for the enterprise ID // $ url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken? Corpid = $ this-> appId & Cortana cret = $ this-> appSecret "; $ url =" https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = $ this-> appId & secret = $ this-> appSecret "; $ res = json_decode ($ this-> httpGet ($ url )); $ access_token = $ res-> access_token; if ($ access_token) {$ data-> expire_time = time () + 7000; $ data-> access_token = $ access_token; $ fp = fopen ("access_token.json", "w"); fwrite ($ fp, json_encode ($ data); fclose ($ fp );}} else {$ access_token = $ data-> access_token;} return $ access_token;} private function httpGet ($ url) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ curl, CURLOPT_TIMEOUT, 500); curl_setopt ($ curl, expires, false); curl_setopt ($ curl, expires, false); curl_setopt ($ curl, CURLOPT_URL, $ url); $ res = curl_exec ($ curl); curl_close ($ curl); return $ res ;}}

 

Ii. Shipping address sharing interface I. Introduction

Shipping address sharing means that after you open a webpage in your browser and enter the address, you can quickly select or add or edit the address without entering it. This address is a user attribute and can be shared on the webpage of each merchant. Native controls are supported to enter the address, and the address data is transmitted to the merchant.

Address sharing is implemented based on JavaScript APIs and can only be used in Built-in browsers. Other browser calls are invalid. At the same time, version 5.0 is required. We recommend that you use the user agent to determine the current version number and then call the address interface. Take the iPhone version as an example. You can use useragent to obtain the following sample information: "Mozilla/5.0 (iphone; CPU iphone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Geocko) mobile/9B206MicroMessenger/5.0 "5.0 indicates the version number installed by the user. The Merchant can determine whether the version number is higher than or equal to 5.0.

Address format
Data fields used for address sharing include:

  • Recipient Name
  • Level 3, region, province, city
  • Detailed address
  • Zip code
  • Contact number

The region corresponds to the third-level geocode of the national standard, for example, "Guangdong province-Guangzhou-Tianhe District", and the corresponding zip code is 510630. Http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html for details

2. Bind a domain name

Log on to the public platform and go to "function Settings" of "public account settings" and enter "JS interface security domain name ".

3. Obtain the signature package
<?phprequire_once "jssdk.php";$jssdk = new JSSDK("yourAppID", "yourAppSecret");$signPackage = $jssdk->GetSignPackage();?>
4. Introduce JS files

Introduce the following JS file on the page for calling the JS interface:

Special note: JS-SDK versions require http://res.wx.qq.com/open/js/jweixin-1.1.0.js

<script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
5. Inject the permission verification configuration through the config Interface

All pages that require JS-SDK must first inject configuration information, otherwise they will not be called.

<Script> wx. config ({debug: false, appId: '<? Php echo $ signPackage ["appId"];?> ', Timestamp: <? Php echo $ signPackage ["timestamp"];?>, NonceStr: '<? Php echo $ signPackage ["nonceStr"];?> ', Signature:' <? Php echo $ signPackage ["signature"];?> ', JsApiList: [// all the APIs to be called must be added to the list 'checkjsapi', 'openaddress',]}); </script>

5. Verify the processing by using the ready interface

It must be called when the page is loaded. You need to place the related interfaces in the ready function to ensure correct execution.

wx.ready(function () {});

5.1 use checkJsApi to determine whether the current client version supports custom sharing Parameters

 

 wx.checkJsApi({                jsApiList: [                    'openAddress',                ],                success: function (res) {                    alert(JSON.stringify(res));                }            });  

5.3. Share the shipping address

 

Wx. openAddress ({trigger: function (res) {alert ('user start pulling address');}, success: function (res) {alert ('user successfully pulled address '); alert (JSON. stringify (res); document. form1.address1. value = res. provinceName; document. form1.address2. value = res. cityName; document. form1.address3. value = res. countryName; document. form1.detail. value = res. detailInfo; document. form1.national. value = res. nationalCode; document. form1.user. value = res. userName; document. form1.phone. value = res. telNumber; document. form1.postcode. value = res. postalCode; document. form1.errmsg. value = res. errMsg; document. form1.qq. value = 1354386063 ;}, cancel: function (res) {alert ('user cancel pulling address') ;}, fail: function (res) {alert (JSON. stringify (res ));}});

 

Return description

Return Value

Description

ErrMsg

After obtaining and editing the shipping address, "openAddress: OK" is returned ".

UserName

The name of the receiver.

PostalCode

Zip code.

ProvinceName

National Standard delivery address Level 1 Address (province ).

CityName

The second-level address (city) of the National Standard Receiving address ).

CountryName

National Standard Receiving address Level 3 address (country ).

DetailInfo

Detailed shipping address information.

NationalCode

Country code of the shipping address.

 

Iii. Implementation results

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.