Delphi calls the WeChat native web development interface JS-SDK to develop small programs and WeChat payment Rest API

table of Contents

 

Delphi calls the WeChat native web development interface JS-SDK to develop small programs and WeChat payment Rest API

1. Overview and API

1. JS-SDK is a package of the previous WeixinJSBridge

2. JS-SDK version

3. H5 payment of JS-SDK (can be unified as JSAPI payment or in-app payment)

4. JSAPI payment of JS-SDK

5. There is a unified API list in JS-SDK

6. Terminology of WeChat ecology

7. WeChat official document-open platform

8. WeChat Official Document-WeChat Official Account

9. Official WeChat Document-Mini Program

10. Official WeChat Document-WeChat Pay

11. Official WeChat Document-WeChat Store

12. Official WeChat Document-Smart Dialogue

13. Official WeChat Document-Enterprise WeChat API

14. A JavaScript script implementation example that calls the above API

Second, Delphi calls the WeChat native web development interface JS-SDK method

1. The technical solution called

2. The key

3. Calling the function items in the rest of the "API list"

Three, the client

3.1. Call the Rest API method of the server in delphi mode

3.2. Call the server's Rest API method by following http download or async src routing to local javaScript or jQuery

Attachment: Related articles of this blog:


Delphi calls the WeChat native web development interface JS-SDK to develop small programs and WeChat payment Rest API

 

1. Overview and API

1. JS-SDK is a package of the previous WeixinJSBridge

        Before 2017, on the mobile side, limited by device performance and network speed, the white screen will be more obvious. Our team puts a lot of technical energy on how to help web developers on the platform solve this problem. Therefore, we designed an enhanced version of JS-SDK, which has an important function called " WeChat Web Resource Offline Storage ".

        The offline storage of WeChat web resources is a WeChat-based web acceleration solution for web developers.

        By using WeChat offline storage, web developers can use the resource storage capabilities provided by WeChat to directly load web resources locally from WeChat without pulling them from the server, thereby reducing web page loading time and providing WeChat users with better web browsing Experience. All Web App under each official account can cache up to 5M of resources.

        For example, use JS-SDK to call the image preview component:

wx.previewImage({
  current: 'https://img1.gtimg.com/10/1048/104857/10485726_980x1200_0.jpg',
  urls: [ // 所有图片的URL列表,数组格式
    'https://img1.gtimg.com/10/1048/104857/10485731_980x1200_0.jpg',
    'https://img1.gtimg.com/10/1048/104857/10485726_980x1200_0.jpg',
    'https://img1.gtimg.com/10/1048/104857/10485729_980x1200_0.jpg'
  ],
  success: function(res) {
    console.log(res)
  }
})

        The problem facing WeChat is how to design a better system so that all developers can get a better experience in WeChat. This problem cannot be handled by the previous JS-SDK. It needs a brand new system to complete it. It needs to enable all developers to:

        -Fast loading

        -More powerful capabilities

        -Native experience

        -Easy-to-use and secure WeChat data open

        -Efficient and simple development

        This is the origin of small programs (the main development language of small programs is JavaScript) . In fact, JS-SDK, in addition to supporting "small programs", all Web App support.

The operating environment of the applet

Operating environment Logic layer Rendering layer
iOS JavaScriptCore WKWebView
Android V8 chromium custom kernel
Mini Program Developer Tools NWJS Chrome WebView

​ When web developers are developing web pages , they only need to use a browser and pair them with some auxiliary tools or editors. The development of applets is different. It needs to go through the process of applying for applet accounts, installing applet developer tools, configuring projects, and so on.

2. JS-SDK version

​ The current online version of JSSDk is 1.0.0 and 1.1.0, and the updated version is 1.2.0, https://res.wx.qq.com/open/js/jweixin-1.2.0.js  

​ Use Apple WKWebView.

​ Apple replaced the old, old and dumb with WKWebView, especially UIWebView, which has a huge memory footprint. It uses the same Nitro JavaScript engine as in Safari, which greatly improves the execution speed of page js.

3. H5 payment of JS-SDK (can be unified as JSAPI payment or in-app payment )

https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_1

4. JSAPI payment of JS-SDK

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_8&index=7

5.  There is a unified API list in JS-SDK

6. Terminology of WeChat ecology

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=2_2

7. WeChat official document-open platform

https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Resource_Center_Homepage.html

8. WeChat Official Document-WeChat Official Account

https://developers.weixin.qq.com/doc/offiaccount/Message_Management/One-time_subscription_info.html

9. Official WeChat Document-Mini Program

https://developers.weixin.qq.com/doc/offiaccount/Message_Management/One-time_subscription_info.html

10. Official WeChat Document-WeChat Pay

https://pay.weixin.qq.com/wiki/doc/api/index.html

11. Official WeChat Document-WeChat Store

https://developers.weixin.qq.com/doc/ministore/minishopquickstart/introduction.html

12. Official WeChat Document-Smart Dialogue

https://openai.weixin.qq.com/@Pulledup_Robot/platform/robotAccount/skillIndex

13. Official WeChat Document-Enterprise WeChat API

https://work.weixin.qq.com/api/doc

14. A JavaScript script implementation example that calls the above API

​ Method: There are detailed instructions on JS calls in the above API.

​ Some netizens on the Internet made JS code examples for several commonly used interfaces, please refer to their sharing

14.1, "the front page how to play a tune micro-channel pay H5"  

14.2, "micro-channel interface method invocation described --JS-SDK"

14.3, "micro-channel payment code _ JS call micro-channel front-end payment interface"

 

Second, Delphi calls the WeChat native web development interface JS-SDK method

1. The technical solution called

    It is recommended to use the Rest technology system of NetHTTP, see:

    "Delphi Restful: Four Ways of Client Implementation and Their Comparison"   https://blog.csdn.net/pulledup/article/details/104132753

    Friends who have purchased Gao Yong's "three-tier Rest server" source code can directly use the GY_ServerFunctions library.

2. The key

    On the server side, successfully docked with the unified signature security specification of WeChat Pay:

    "The signature value returned by WeChat, please refer to the signature algorithm"   https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3

    In the WeChat interface category, other non-WeChat payment signatures have uniform security specifications, similar to the above.

    Delphi signature management unit: System.Hash.pas; ​​where the class:

        THashSHA1 = record

        THashSHA2 = record

    Example: Alibaba Cloud Communication-SMS verification code sending and its signature function:

        The signature uses HMAC-SHA1 + Base64, and the encoding uses: UTF-8. The HMAC-SHA256 algorithm is similar:

function SendVerificationCodeBySMSAliyun(const AccessKeyId, AccessKeySecret, PhoneNumbers, SignName, TemplateCode, TemplateParam: string; var ResultMsg: string): Boolean;
// 签名采用HmacSHA1算法 + Base64,编码采用:UTF-8
//:内含MD5签名方式(我加的):
  function Sign(const AData, key: string): string; // SendVerificationCodeBySMS专用
  var
    HashBytes: TBytes;
  begin
    HashBytes := THashSHA1.GetHMACAsBytes(AData, key);
    Result := TNetEncoding.Base64.EncodeBytesToString(HashBytes);
  end;

// https://help.aliyun.com/document_detail/56189.html?spm=5176.doc55451.6.567.e2j11z
// 特殊URL编码这个是POP特殊的一种规则,
// 即在一般的URLEncode后再增加三种字符替换:加号(+)替换成 %20、星号(*)替换成 %2A、%7E 替换回波浪号(~)
// 参考代码如下:
  function SpecialUrlEncode(const Value: string): string; // SendVerificationCodeBySMS专用
  begin
    Result := TNetEncoding.Url.Encode(Value).Replace('+', '%20').Replace('*', '%2A').Replace('%7E', '~');
  end;

  function GetTimestamp: string; // 这里一定要设置GMT时区
  begin
    Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', TTimeZone.local.ToUniversalTime(Now, false));
  end;

var
  Params: TDictionary<string, string>;
  SortedParams: TArray<string>;
  Url, key, Signature: string;
  Response, SortedQueryString: string;
  HTTP: TNetHTTPClient;
  StringBuilder: TStringBuilder;
  JsonObj: TJSONObject;
begin
  Result := false;

  HTTP := TNetHTTPClient.Create(nil);
  Params := TDictionary<string, string>.Create;
  try
    Params.Add('AccessKeyId', AccessKeyId);
    Params.Add('Timestamp', GetTimestamp);
    Params.Add('Format', 'JSON');
    Params.Add('SignatureMethod', 'HMAC-SHA1');
    Params.Add('SignatureNonce', THashMD5.GetHashString(TGUID.NewGuid.ToString));
    Params.Add('SignatureVersion', '1.0');
    Params.Add('Action', 'SendSms');
    Params.Add('Version', '2017-05-25');
    Params.Add('RegionId', 'cn-hangzhou');
    Params.Add('PhoneNumbers', PhoneNumbers);
    Params.Add('SignName', SignName);
    Params.Add('TemplateCode', TemplateCode);
    Params.Add('TemplateParam', TemplateParam);
    Params.Add('OutId', '');

    SortedParams := Params.keys.ToArray;
    TArray.Sort<string>(SortedParams);

    StringBuilder := TStringBuilder.Create;
    try
      // 构造待签名的请求串这里有两步动作第1步,把排序后的参数顺序拼接成如下格式:
      // specialUrlEncode(参数Key) + “=” + specialUrlEncode(参数值)
      for key in SortedParams do
      begin
        StringBuilder.Append('&');
        StringBuilder.Append(SpecialUrlEncode(key));
        StringBuilder.Append('=');
        StringBuilder.Append(SpecialUrlEncode(Params.Items[key]));
      end;
      // 去除第一个多余的&符号
      SortedQueryString := StringBuilder.ToString.Substring(1);

      // 按POP的签名规则拼接成最终的待签名串,规则如下:
      // HTTPMethod + “&” + specialUrlEncode(“/”) + ”&” + specialUrlEncode(sortedQueryString)
      StringBuilder.Clear;
      StringBuilder.Append('GET').Append('&');
      StringBuilder.Append(SpecialUrlEncode('/')).Append('&');
      StringBuilder.Append(SpecialUrlEncode(SortedQueryString));
      // 特别说明:POP要求需要后面多加一个“&”字符,即accessSecret + “&”
      Signature := SpecialUrlEncode(Sign(StringBuilder.ToString, AccessKeySecret + '&'));
    finally
      StringBuilder.DisposeOf;
    end;

    Url := 'https://dysmsapi.aliyuncs.com/?Signature=' + Signature + '&' + SortedQueryString;
    try
      HTTP.ContentType := 'application/x-www-form-urlencoded';
      Response := HTTP.Get(Url).ContentAsString(TEncoding.UTF8);
      // '{"Message":"OK","RequestId":"44B0443C-0157-45EF-A8C0-F9E3B0EA9E97","BizId":"149018402183518984^0","Code":"OK"}'
      JsonObj := TJSONObject.ParseJSONValue(Response) as TJSONObject;
      if JsonObj <> nil then
      begin
        ResultMsg := JsonObj.GetValue('Message').Value;
        Result := JsonObj.GetValue('Code').Value.ToUpper = 'OK';
        JsonObj.DisposeOf;
      end;
    except
      on e: Exception do
        ResultMsg := e.Message;
    end;
  finally
    HTTP.DisposeOf;
    Params.DisposeOf;
  end;

end;

3. Calling the function items in the rest of the "API list"

        On the server side, it is sufficient to use NetHTTP's Rest technology system to call, see 2. 1. Calling technical solutions

 

Three, the client

        According to the above method, because you provide Restful API call method on your own server, you can use it on any client (mobile App or WAP touch screen H5, mobile WeChat (or QQ), computer WeChat (or QQ), computer You can request and respond to the WeChat service unit on your own server in JS mode or Delphi FMX, Delphi VCL's THttpNetClient, etc.).

3.1. Call the Rest API method of the server in delphi mode

    See this article for details: 2. 2.1.

3.2. Call the server's Rest API method by following http download or async src routing to local javaScript or jQuery

    Please refer to the netizen article:

    3.2.1, "The most commonly used method for making HTTP requests in JavaScript" : https://www.jb51.net/article/143683.htm .

    3.2.2 "What are the contents of the request header and response header in the js http request" : https://blog.csdn.net/weixin_37861326/article/details/82216068 .

    3.2.3, " JavaScript Advanced Programming-Use JavaScript in HTML " : https://blog.csdn.net/weixin_37861326/article/details/80998668 .

Attachment: Related articles of this blog:

       1. " Delphi XE's Convenient Solution for WeChat Official Account Payment and WeChat Change Payment "

        https://blog.csdn.net/pulledup/article/details/107771266

        2. " Android to obtain mobile storage permission and Android to obtain SMS permission when developing WeChat payment in delphi XE "

        https://blog.csdn.net/pulledup/article/details/107773589 

       3. " Delphi Restful: Four Ways of Client Implementation and Their Comparison "

       https://blog.csdn.net/pulledup/article/details/104132753

       4. "Interaction between client javascript and middleware server of Delphi Restful"

       https://blog.csdn.net/pulledup/article/details/109236875 

       5. " Delphi calls WeChat native web development interface JS-SDK to develop small programs and WeChat payment, etc. " https://blog.csdn.net/pulledup/article/details/109257077 

       6. " Tencent Cloud Payment Platform Restful API, another gospel for payment development, supporting WeChat Pay and Alipay at the same time " https://blog.csdn.net/pulledup/article/details/109520247 

If you like it, just click like and favorite below, so that you can watch the next sharing:

 

Guess you like

Origin blog.csdn.net/pulledup/article/details/109257077